signup-page.js 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342
  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. throwIfStopped();
  450. simulateClick(continueButton);
  451. } catch (error) {
  452. if (!isStopError(error)) {
  453. console.error('[MultiPage:signup-page] deferred signup email submit failed:', error?.message || error);
  454. }
  455. }
  456. }, 120);
  457. return {
  458. submitted: true,
  459. email,
  460. url: location.href,
  461. };
  462. }
  463. // ============================================================
  464. // Step 2: Click Register, fill email, then continue to password page
  465. // ============================================================
  466. async function step2_clickRegister(payload = {}) {
  467. const { email } = payload;
  468. return fillSignupEmailAndContinue(email, 2);
  469. }
  470. // ============================================================
  471. // Step 3: Fill Password
  472. // ============================================================
  473. async function step3_fillEmailPassword(payload) {
  474. const { email, password } = payload;
  475. if (!password) throw new Error('未提供密码,步骤 3 需要可用密码。');
  476. const normalizedEmail = String(email || '').trim().toLowerCase();
  477. let snapshot = inspectSignupEntryState();
  478. if (snapshot.state === 'entry_home') {
  479. throw new Error('当前仍停留在 ChatGPT 官网首页,请先完成步骤 2。');
  480. }
  481. if (snapshot.state === 'email_entry') {
  482. const transition = await fillSignupEmailAndContinue(email, 3);
  483. if (!transition.alreadyOnPasswordPage) {
  484. await sleep(1200);
  485. await ensureSignupPasswordPageReady();
  486. }
  487. snapshot = inspectSignupEntryState();
  488. }
  489. if (snapshot.state !== 'password_page' || !snapshot.passwordInput) {
  490. await ensureSignupPasswordPageReady();
  491. snapshot = inspectSignupEntryState();
  492. }
  493. if (snapshot.state !== 'password_page' || !snapshot.passwordInput) {
  494. throw new Error('在密码页未找到密码输入框。URL: ' + location.href);
  495. }
  496. if (normalizedEmail && snapshot.displayedEmail && snapshot.displayedEmail !== normalizedEmail) {
  497. throw new Error(`当前密码页邮箱为 ${snapshot.displayedEmail},与目标邮箱 ${email} 不一致,请先回到步骤 1 重新开始。`);
  498. }
  499. await humanPause(600, 1500);
  500. fillInput(snapshot.passwordInput, password);
  501. log('步骤 3:密码已填写');
  502. const submitBtn = snapshot.submitButton
  503. || getSignupPasswordSubmitButton({ allowDisabled: true })
  504. || await waitForElementByText('button', /continue|sign\s*up|submit|注册|创建|create/i, 5000).catch(() => null);
  505. // Report complete BEFORE submit, because submit causes page navigation
  506. // which kills the content script connection
  507. const signupVerificationRequestedAt = submitBtn ? Date.now() : null;
  508. const completionPayload = {
  509. email,
  510. signupVerificationRequestedAt,
  511. deferredSubmit: Boolean(submitBtn),
  512. };
  513. reportComplete(3, completionPayload);
  514. if (submitBtn) {
  515. window.setTimeout(async () => {
  516. try {
  517. throwIfStopped();
  518. await sleep(500);
  519. await humanPause(500, 1300);
  520. simulateClick(submitBtn);
  521. log('步骤 3:表单已提交');
  522. } catch (error) {
  523. if (!isStopError(error)) {
  524. console.error('[MultiPage:signup-page] deferred step 3 submit failed:', error?.message || error);
  525. }
  526. }
  527. }, 120);
  528. }
  529. return completionPayload;
  530. }
  531. // ============================================================
  532. // Fill Verification Code (used by step 4 and step 7)
  533. // ============================================================
  534. const INVALID_VERIFICATION_CODE_PATTERN = /代码不正确|验证码不正确|验证码错误|code\s+(?:is\s+)?incorrect|invalid\s+code|incorrect\s+code|try\s+again/i;
  535. 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;
  536. 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;
  537. const OAUTH_CONSENT_FORM_SELECTOR = 'form[action*="/sign-in-with-chatgpt/" i][action*="/consent" i]';
  538. const CONTINUE_ACTION_PATTERN = /继续|continue/i;
  539. const ADD_PHONE_PAGE_PATTERN = /add[\s-]*phone|添加手机号|手机号码|手机号|phone\s+number|telephone/i;
  540. 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;
  541. const AUTH_TIMEOUT_ERROR_TITLE_PATTERN = /糟糕,出错了|something\s+went\s+wrong|oops/i;
  542. const AUTH_TIMEOUT_ERROR_DETAIL_PATTERN = /operation\s+timed\s+out|timed\s+out|请求超时|操作超时/i;
  543. 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;
  544. const authPageRecovery = self.MultiPageAuthPageRecovery?.createAuthPageRecovery?.({
  545. detailPattern: AUTH_TIMEOUT_ERROR_DETAIL_PATTERN,
  546. getActionText,
  547. getPageTextSnapshot,
  548. humanPause,
  549. isActionEnabled,
  550. isVisibleElement,
  551. log,
  552. simulateClick,
  553. sleep,
  554. throwIfStopped,
  555. titlePattern: AUTH_TIMEOUT_ERROR_TITLE_PATTERN,
  556. }) || null;
  557. function getVerificationErrorText() {
  558. const messages = [];
  559. const selectors = [
  560. '.react-aria-FieldError',
  561. '[slot="errorMessage"]',
  562. '[id$="-error"]',
  563. '[data-invalid="true"] + *',
  564. '[aria-invalid="true"] + *',
  565. '[class*="error"]',
  566. ];
  567. for (const selector of selectors) {
  568. document.querySelectorAll(selector).forEach((el) => {
  569. const text = (el.textContent || '').replace(/\s+/g, ' ').trim();
  570. if (text) {
  571. messages.push(text);
  572. }
  573. });
  574. }
  575. const invalidInput = document.querySelector(`${VERIFICATION_CODE_INPUT_SELECTOR}[aria-invalid="true"], ${VERIFICATION_CODE_INPUT_SELECTOR}[data-invalid="true"]`);
  576. if (invalidInput) {
  577. const wrapper = invalidInput.closest('form, [data-rac], ._root_18qcl_51, div');
  578. if (wrapper) {
  579. const text = (wrapper.textContent || '').replace(/\s+/g, ' ').trim();
  580. if (text) {
  581. messages.push(text);
  582. }
  583. }
  584. }
  585. return messages.find((text) => INVALID_VERIFICATION_CODE_PATTERN.test(text)) || '';
  586. }
  587. function isStep5Ready() {
  588. return Boolean(
  589. document.querySelector('input[name="name"], input[autocomplete="name"], input[name="birthday"], input[name="age"], [role="spinbutton"][data-type="year"]')
  590. );
  591. }
  592. function getPageTextSnapshot() {
  593. return (document.body?.innerText || document.body?.textContent || '')
  594. .replace(/\s+/g, ' ')
  595. .trim();
  596. }
  597. function getOAuthConsentForm() {
  598. return document.querySelector(OAUTH_CONSENT_FORM_SELECTOR);
  599. }
  600. function getPrimaryContinueButton() {
  601. const consentForm = getOAuthConsentForm();
  602. if (consentForm) {
  603. const formButtons = Array.from(
  604. consentForm.querySelectorAll('button[type="submit"], input[type="submit"], [role="button"]')
  605. );
  606. const formContinueButton = formButtons.find((el) => {
  607. if (!isVisibleElement(el)) return false;
  608. const ddActionName = el.getAttribute?.('data-dd-action-name') || '';
  609. return ddActionName === 'Continue' || CONTINUE_ACTION_PATTERN.test(getActionText(el));
  610. });
  611. if (formContinueButton) {
  612. return formContinueButton;
  613. }
  614. const firstVisibleSubmit = formButtons.find(isVisibleElement);
  615. if (firstVisibleSubmit) {
  616. return firstVisibleSubmit;
  617. }
  618. }
  619. const continueBtn = document.querySelector(
  620. `${OAUTH_CONSENT_FORM_SELECTOR} button[type="submit"], button[type="submit"][data-dd-action-name="Continue"], button[type="submit"]._primary_3rdp0_107`
  621. );
  622. if (continueBtn && isVisibleElement(continueBtn)) {
  623. return continueBtn;
  624. }
  625. const buttons = document.querySelectorAll('button, [role="button"]');
  626. return Array.from(buttons).find((el) => {
  627. if (!isVisibleElement(el)) return false;
  628. const ddActionName = el.getAttribute?.('data-dd-action-name') || '';
  629. return ddActionName === 'Continue' || CONTINUE_ACTION_PATTERN.test(getActionText(el));
  630. }) || null;
  631. }
  632. function isOAuthConsentPage() {
  633. const pageText = getPageTextSnapshot();
  634. if (OAUTH_CONSENT_PAGE_PATTERN.test(pageText)) {
  635. return true;
  636. }
  637. if (getOAuthConsentForm()) {
  638. return true;
  639. }
  640. return /\bcodex\b/i.test(pageText) && /\bchatgpt\b/i.test(pageText) && Boolean(getPrimaryContinueButton());
  641. }
  642. function isVerificationPageStillVisible() {
  643. if (getCurrentAuthRetryPageState('signup_password') || getCurrentAuthRetryPageState('login')) {
  644. return false;
  645. }
  646. if (getVerificationCodeTarget()) return true;
  647. if (findResendVerificationCodeTrigger({ allowDisabled: true })) return true;
  648. if (document.querySelector('form[action*="email-verification" i]')) return true;
  649. if (!isEmailVerificationPage()) {
  650. return false;
  651. }
  652. return VERIFICATION_PAGE_PATTERN.test(getPageTextSnapshot());
  653. }
  654. function isAddPhonePageReady() {
  655. const path = `${location.pathname || ''} ${location.href || ''}`;
  656. if (/\/add-phone(?:[/?#]|$)/i.test(path)) return true;
  657. const phoneInput = document.querySelector(
  658. 'input[type="tel"]:not([maxlength="6"]), input[name*="phone" i], input[id*="phone" i], input[autocomplete="tel"]'
  659. );
  660. if (phoneInput && isVisibleElement(phoneInput)) {
  661. return true;
  662. }
  663. return ADD_PHONE_PAGE_PATTERN.test(getPageTextSnapshot());
  664. }
  665. function isStep8Ready() {
  666. const continueBtn = getPrimaryContinueButton();
  667. if (!continueBtn) return false;
  668. if (isVerificationPageStillVisible()) return false;
  669. if (isAddPhonePageReady()) return false;
  670. return isOAuthConsentPage();
  671. }
  672. function normalizeInlineText(text) {
  673. return (text || '').replace(/\s+/g, ' ').trim();
  674. }
  675. function findBirthdayReactAriaSelect(labelText) {
  676. const normalizedLabel = normalizeInlineText(labelText);
  677. const roots = document.querySelectorAll('.react-aria-Select');
  678. for (const root of roots) {
  679. const labelEl = Array.from(root.querySelectorAll('span')).find((el) => normalizeInlineText(el.textContent) === normalizedLabel);
  680. if (!labelEl) continue;
  681. const item = root.closest('[class*="selectItem"], ._selectItem_ppsls_113') || root.parentElement;
  682. const nativeSelect = item?.querySelector('[data-testid="hidden-select-container"] select') || null;
  683. const button = root.querySelector('button[aria-haspopup="listbox"]') || null;
  684. const valueEl = root.querySelector('.react-aria-SelectValue') || null;
  685. return { root, item, labelEl, nativeSelect, button, valueEl };
  686. }
  687. return null;
  688. }
  689. async function setReactAriaBirthdaySelect(control, value) {
  690. if (!control?.nativeSelect) {
  691. throw new Error('未找到可写入的生日下拉框。');
  692. }
  693. const desiredValue = String(value);
  694. const option = Array.from(control.nativeSelect.options).find((item) => item.value === desiredValue);
  695. if (!option) {
  696. throw new Error(`生日下拉框中不存在值 ${desiredValue}。`);
  697. }
  698. control.nativeSelect.value = desiredValue;
  699. option.selected = true;
  700. control.nativeSelect.dispatchEvent(new Event('input', { bubbles: true }));
  701. control.nativeSelect.dispatchEvent(new Event('change', { bubbles: true }));
  702. await sleep(120);
  703. }
  704. function getStep5ErrorText() {
  705. const messages = [];
  706. const selectors = [
  707. '.react-aria-FieldError',
  708. '[slot="errorMessage"]',
  709. '[id$="-error"]',
  710. '[id$="-errors"]',
  711. '[role="alert"]',
  712. '[aria-live="assertive"]',
  713. '[aria-live="polite"]',
  714. '[class*="error"]',
  715. ];
  716. for (const selector of selectors) {
  717. document.querySelectorAll(selector).forEach((el) => {
  718. if (!isVisibleElement(el)) return;
  719. const text = normalizeInlineText(el.textContent);
  720. if (text) {
  721. messages.push(text);
  722. }
  723. });
  724. }
  725. const invalidField = Array.from(document.querySelectorAll('[aria-invalid="true"], [data-invalid="true"]'))
  726. .find((el) => isVisibleElement(el));
  727. if (invalidField) {
  728. const wrapper = invalidField.closest('form, fieldset, [data-rac], div');
  729. if (wrapper) {
  730. const text = normalizeInlineText(wrapper.textContent);
  731. if (text) {
  732. messages.push(text);
  733. }
  734. }
  735. }
  736. return messages.find((text) => STEP5_SUBMIT_ERROR_PATTERN.test(text)) || '';
  737. }
  738. function isSignupPasswordPage() {
  739. return /\/create-account\/password(?:[/?#]|$)/i.test(location.pathname || '');
  740. }
  741. function getSignupPasswordInput() {
  742. const input = document.querySelector('input[type="password"]');
  743. return input && isVisibleElement(input) ? input : null;
  744. }
  745. function getSignupPasswordSubmitButton({ allowDisabled = false } = {}) {
  746. const direct = document.querySelector('button[type="submit"]');
  747. if (direct && isVisibleElement(direct) && (allowDisabled || isActionEnabled(direct))) {
  748. return direct;
  749. }
  750. const candidates = document.querySelectorAll('button, [role="button"]');
  751. return Array.from(candidates).find((el) => {
  752. if (!isVisibleElement(el) || (!allowDisabled && !isActionEnabled(el))) return false;
  753. const text = getActionText(el);
  754. return /继续|continue|submit|创建|create/i.test(text);
  755. }) || null;
  756. }
  757. function getAuthRetryButton({ allowDisabled = false } = {}) {
  758. if (authPageRecovery?.getAuthRetryButton) {
  759. return authPageRecovery.getAuthRetryButton({ allowDisabled });
  760. }
  761. const direct = document.querySelector('button[data-dd-action-name="Try again"]');
  762. if (direct && isVisibleElement(direct) && (allowDisabled || isActionEnabled(direct))) {
  763. return direct;
  764. }
  765. const candidates = document.querySelectorAll('button, [role="button"]');
  766. return Array.from(candidates).find((el) => {
  767. if (!isVisibleElement(el) || (!allowDisabled && !isActionEnabled(el))) return false;
  768. const text = getActionText(el);
  769. return /重试|try\s+again/i.test(text);
  770. }) || null;
  771. }
  772. function getAuthTimeoutErrorPageState(options = {}) {
  773. if (authPageRecovery?.getAuthTimeoutErrorPageState) {
  774. return authPageRecovery.getAuthTimeoutErrorPageState(options);
  775. }
  776. const { pathPatterns = [] } = options;
  777. const path = location.pathname || '';
  778. if (pathPatterns.length && !pathPatterns.some((pattern) => pattern.test(path))) {
  779. return null;
  780. }
  781. const retryButton = getAuthRetryButton({ allowDisabled: true });
  782. if (!retryButton) {
  783. return null;
  784. }
  785. const text = getPageTextSnapshot();
  786. const titleMatched = AUTH_TIMEOUT_ERROR_TITLE_PATTERN.test(text)
  787. || AUTH_TIMEOUT_ERROR_TITLE_PATTERN.test(document.title || '');
  788. const detailMatched = AUTH_TIMEOUT_ERROR_DETAIL_PATTERN.test(text);
  789. if (!titleMatched && !detailMatched) {
  790. return null;
  791. }
  792. return {
  793. path,
  794. url: location.href,
  795. retryButton,
  796. retryEnabled: isActionEnabled(retryButton),
  797. titleMatched,
  798. detailMatched,
  799. };
  800. }
  801. function getAuthRetryPathPatternsForFlow(flow = 'auth') {
  802. switch (flow) {
  803. case 'signup_password':
  804. return [/\/create-account\/password(?:[/?#]|$)/i];
  805. case 'login':
  806. return [/\/log-in(?:[/?#]|$)/i];
  807. default:
  808. return [];
  809. }
  810. }
  811. function getCurrentAuthRetryPageState(flow = 'auth') {
  812. return getAuthTimeoutErrorPageState({
  813. pathPatterns: getAuthRetryPathPatternsForFlow(flow),
  814. });
  815. }
  816. async function recoverCurrentAuthRetryPage(payload = {}) {
  817. const {
  818. flow = 'auth',
  819. logLabel = '',
  820. step = null,
  821. timeoutMs = 12000,
  822. waitAfterClickMs = 3000,
  823. } = payload;
  824. const pathPatterns = getAuthRetryPathPatternsForFlow(flow);
  825. if (authPageRecovery?.recoverAuthRetryPage) {
  826. return authPageRecovery.recoverAuthRetryPage({
  827. logLabel,
  828. pathPatterns,
  829. step,
  830. timeoutMs,
  831. waitAfterClickMs,
  832. });
  833. }
  834. const start = Date.now();
  835. let clickCount = 0;
  836. while (Date.now() - start < timeoutMs) {
  837. throwIfStopped();
  838. const retryState = getCurrentAuthRetryPageState(flow);
  839. if (!retryState) {
  840. return {
  841. recovered: clickCount > 0,
  842. clickCount,
  843. url: location.href,
  844. };
  845. }
  846. if (retryState.retryButton && retryState.retryEnabled) {
  847. clickCount += 1;
  848. log(`${logLabel || `步骤 ${step || '?'}:检测到重试页,正在点击“重试”恢复`}(第 ${clickCount} 次)...`, 'warn');
  849. await humanPause(300, 800);
  850. simulateClick(retryState.retryButton);
  851. const settleStart = Date.now();
  852. while (Date.now() - settleStart < waitAfterClickMs) {
  853. throwIfStopped();
  854. if (!getCurrentAuthRetryPageState(flow)) {
  855. return {
  856. recovered: true,
  857. clickCount,
  858. url: location.href,
  859. };
  860. }
  861. await sleep(250);
  862. }
  863. continue;
  864. }
  865. await sleep(250);
  866. }
  867. throw new Error(`${logLabel || `步骤 ${step || '?'}:重试页恢复`}超时。URL: ${location.href}`);
  868. }
  869. function getSignupPasswordTimeoutErrorPageState() {
  870. return getAuthTimeoutErrorPageState({
  871. pathPatterns: [/\/create-account\/password(?:[/?#]|$)/i],
  872. });
  873. }
  874. function getLoginTimeoutErrorPageState() {
  875. return getAuthTimeoutErrorPageState({
  876. pathPatterns: [/\/log-in(?:[/?#]|$)/i],
  877. });
  878. }
  879. function getLoginEmailInput() {
  880. const input = document.querySelector(
  881. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email" i], input[placeholder*="Email"]'
  882. );
  883. return input && isVisibleElement(input) ? input : null;
  884. }
  885. function getLoginPasswordInput() {
  886. const input = document.querySelector('input[type="password"]');
  887. return input && isVisibleElement(input) ? input : null;
  888. }
  889. function getLoginSubmitButton({ allowDisabled = false } = {}) {
  890. const direct = document.querySelector('button[type="submit"], input[type="submit"]');
  891. if (direct && isVisibleElement(direct) && (allowDisabled || isActionEnabled(direct))) {
  892. return direct;
  893. }
  894. const candidates = document.querySelectorAll(
  895. 'button, a, [role="button"], [role="link"], input[type="button"], input[type="submit"]'
  896. );
  897. return Array.from(candidates).find((el) => {
  898. if (!isVisibleElement(el) || (!allowDisabled && !isActionEnabled(el))) return false;
  899. const text = getActionText(el);
  900. if (!text || ONE_TIME_CODE_LOGIN_PATTERN.test(text)) return false;
  901. return /continue|next|submit|sign\s*in|log\s*in|继续|下一步|登录/i.test(text);
  902. }) || null;
  903. }
  904. function inspectLoginAuthState() {
  905. const retryState = getLoginTimeoutErrorPageState();
  906. const verificationTarget = getVerificationCodeTarget();
  907. const passwordInput = getLoginPasswordInput();
  908. const emailInput = getLoginEmailInput();
  909. const switchTrigger = findOneTimeCodeLoginTrigger();
  910. const submitButton = getLoginSubmitButton({ allowDisabled: true });
  911. const verificationVisible = isVerificationPageStillVisible();
  912. const addPhonePage = isAddPhonePageReady();
  913. const consentReady = isStep8Ready();
  914. const oauthConsentPage = isOAuthConsentPage();
  915. const baseState = {
  916. state: 'unknown',
  917. url: location.href,
  918. path: location.pathname || '',
  919. retryButton: retryState?.retryButton || null,
  920. retryEnabled: Boolean(retryState?.retryEnabled),
  921. titleMatched: Boolean(retryState?.titleMatched),
  922. detailMatched: Boolean(retryState?.detailMatched),
  923. verificationTarget,
  924. passwordInput,
  925. emailInput,
  926. submitButton,
  927. switchTrigger,
  928. verificationVisible,
  929. addPhonePage,
  930. oauthConsentPage,
  931. consentReady,
  932. };
  933. if (verificationTarget) {
  934. return {
  935. ...baseState,
  936. state: 'verification_page',
  937. };
  938. }
  939. if (retryState) {
  940. return {
  941. ...baseState,
  942. state: 'login_timeout_error_page',
  943. };
  944. }
  945. if (addPhonePage) {
  946. return {
  947. ...baseState,
  948. state: 'add_phone_page',
  949. };
  950. }
  951. if (passwordInput || switchTrigger) {
  952. return {
  953. ...baseState,
  954. state: 'password_page',
  955. };
  956. }
  957. if (emailInput) {
  958. return {
  959. ...baseState,
  960. state: 'email_page',
  961. };
  962. }
  963. if (verificationVisible) {
  964. return {
  965. ...baseState,
  966. state: 'verification_page',
  967. };
  968. }
  969. return baseState;
  970. }
  971. function serializeLoginAuthState(snapshot) {
  972. return {
  973. state: snapshot?.state || 'unknown',
  974. url: snapshot?.url || location.href,
  975. path: snapshot?.path || location.pathname || '',
  976. retryEnabled: Boolean(snapshot?.retryEnabled),
  977. titleMatched: Boolean(snapshot?.titleMatched),
  978. detailMatched: Boolean(snapshot?.detailMatched),
  979. hasVerificationTarget: Boolean(snapshot?.verificationTarget),
  980. hasPasswordInput: Boolean(snapshot?.passwordInput),
  981. hasEmailInput: Boolean(snapshot?.emailInput),
  982. hasSubmitButton: Boolean(snapshot?.submitButton),
  983. hasSwitchTrigger: Boolean(snapshot?.switchTrigger),
  984. verificationVisible: Boolean(snapshot?.verificationVisible),
  985. addPhonePage: Boolean(snapshot?.addPhonePage),
  986. oauthConsentPage: Boolean(snapshot?.oauthConsentPage),
  987. consentReady: Boolean(snapshot?.consentReady),
  988. };
  989. }
  990. function getLoginAuthStateLabel(snapshot) {
  991. const state = snapshot?.state === 'oauth_consent_page' ? 'unknown' : snapshot?.state;
  992. switch (state) {
  993. case 'verification_page':
  994. return '登录验证码页';
  995. case 'password_page':
  996. return '密码页';
  997. case 'email_page':
  998. return '邮箱输入页';
  999. case 'login_timeout_error_page':
  1000. return '登录超时报错页';
  1001. case 'oauth_consent_page':
  1002. return 'OAuth 授权页';
  1003. case 'add_phone_page':
  1004. return '手机号页';
  1005. default:
  1006. return '未知页面';
  1007. }
  1008. }
  1009. async function waitForKnownLoginAuthState(timeout = 15000) {
  1010. const start = Date.now();
  1011. let snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1012. while (Date.now() - start < timeout) {
  1013. throwIfStopped();
  1014. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1015. if (snapshot.state !== 'unknown') {
  1016. return snapshot;
  1017. }
  1018. await sleep(200);
  1019. }
  1020. return snapshot;
  1021. }
  1022. async function waitForLoginVerificationPageReady(timeout = 10000) {
  1023. const start = Date.now();
  1024. let snapshot = inspectLoginAuthState();
  1025. while (Date.now() - start < timeout) {
  1026. throwIfStopped();
  1027. snapshot = inspectLoginAuthState();
  1028. if (snapshot.state === 'verification_page') {
  1029. return snapshot;
  1030. }
  1031. if (snapshot.state !== 'unknown') {
  1032. break;
  1033. }
  1034. await sleep(200);
  1035. }
  1036. throw new Error(
  1037. `当前未进入登录验证码页面,请先重新完成步骤 7。当前状态:${getLoginAuthStateLabel(snapshot)}。URL: ${snapshot?.url || location.href}`
  1038. );
  1039. }
  1040. function createStep6SuccessResult(snapshot, options = {}) {
  1041. return {
  1042. step6Outcome: 'success',
  1043. state: snapshot?.state || 'verification_page',
  1044. url: snapshot?.url || location.href,
  1045. via: options.via || '',
  1046. loginVerificationRequestedAt: options.loginVerificationRequestedAt || null,
  1047. };
  1048. }
  1049. function createStep6RecoverableResult(reason, snapshot, options = {}) {
  1050. return {
  1051. step6Outcome: 'recoverable',
  1052. reason,
  1053. state: snapshot?.state || 'unknown',
  1054. url: snapshot?.url || location.href,
  1055. message: options.message || '',
  1056. loginVerificationRequestedAt: options.loginVerificationRequestedAt || null,
  1057. };
  1058. }
  1059. async function createStep6LoginTimeoutRecoverableResult(reason, snapshot, message) {
  1060. return createStep6RecoverableResult(reason, normalizeStep6Snapshot(snapshot || inspectLoginAuthState()), {
  1061. message,
  1062. });
  1063. }
  1064. function normalizeStep6Snapshot(snapshot) {
  1065. if (snapshot?.state !== 'oauth_consent_page') {
  1066. return snapshot;
  1067. }
  1068. return {
  1069. ...snapshot,
  1070. state: 'unknown',
  1071. };
  1072. }
  1073. function throwForStep6FatalState(snapshot) {
  1074. snapshot = normalizeStep6Snapshot(snapshot);
  1075. switch (snapshot?.state) {
  1076. case 'oauth_consent_page':
  1077. throw new Error(`当前页面已进入 OAuth 授权页,未经过登录验证码页,无法完成步骤 7。URL: ${snapshot.url}`);
  1078. case 'add_phone_page':
  1079. throw new Error(`当前页面已进入手机号页面,未经过登录验证码页,无法完成步骤 7。URL: ${snapshot.url}`);
  1080. case 'unknown':
  1081. throw new Error(`无法识别当前登录页面状态。URL: ${snapshot?.url || location.href}`);
  1082. default:
  1083. return;
  1084. }
  1085. }
  1086. async function triggerLoginSubmitAction(button, fallbackField) {
  1087. const form = button?.form || fallbackField?.form || button?.closest?.('form') || fallbackField?.closest?.('form') || null;
  1088. await humanPause(400, 1100);
  1089. if (button && isActionEnabled(button)) {
  1090. simulateClick(button);
  1091. return;
  1092. }
  1093. if (form && typeof form.requestSubmit === 'function') {
  1094. if (button && button.form === form) {
  1095. form.requestSubmit(button);
  1096. } else {
  1097. form.requestSubmit();
  1098. }
  1099. return;
  1100. }
  1101. if (button && typeof button.click === 'function') {
  1102. button.click();
  1103. return;
  1104. }
  1105. throw new Error('未找到可用的登录提交按钮。URL: ' + location.href);
  1106. }
  1107. function isSignupPasswordErrorPage() {
  1108. return Boolean(getSignupPasswordTimeoutErrorPageState());
  1109. }
  1110. function isSignupEmailAlreadyExistsPage() {
  1111. return isSignupPasswordPage() && SIGNUP_EMAIL_EXISTS_PATTERN.test(getPageTextSnapshot());
  1112. }
  1113. function inspectSignupVerificationState() {
  1114. if (isStep5Ready()) {
  1115. return { state: 'step5' };
  1116. }
  1117. if (isSignupPasswordErrorPage()) {
  1118. const timeoutPage = getSignupPasswordTimeoutErrorPageState();
  1119. return {
  1120. state: 'error',
  1121. retryButton: timeoutPage?.retryButton || null,
  1122. };
  1123. }
  1124. if (isVerificationPageStillVisible()) {
  1125. return { state: 'verification' };
  1126. }
  1127. if (isSignupEmailAlreadyExistsPage()) {
  1128. return { state: 'email_exists' };
  1129. }
  1130. const passwordInput = getSignupPasswordInput();
  1131. if (passwordInput) {
  1132. return {
  1133. state: 'password',
  1134. passwordInput,
  1135. submitButton: getSignupPasswordSubmitButton({ allowDisabled: true }),
  1136. };
  1137. }
  1138. return { state: 'unknown' };
  1139. }
  1140. async function waitForSignupVerificationTransition(timeout = 5000) {
  1141. const start = Date.now();
  1142. while (Date.now() - start < timeout) {
  1143. throwIfStopped();
  1144. const snapshot = inspectSignupVerificationState();
  1145. if (snapshot.state === 'step5' || snapshot.state === 'verification' || snapshot.state === 'error' || snapshot.state === 'email_exists') {
  1146. return snapshot;
  1147. }
  1148. await sleep(200);
  1149. }
  1150. return inspectSignupVerificationState();
  1151. }
  1152. async function prepareSignupVerificationFlow(payload = {}, timeout = 30000) {
  1153. const { password } = payload;
  1154. const prepareSource = String(payload?.prepareSource || '').trim() || 'step4_execute';
  1155. const prepareLogLabel = String(payload?.prepareLogLabel || '').trim()
  1156. || (prepareSource === 'step3_finalize' ? '步骤 3 收尾' : '步骤 4 执行');
  1157. const start = Date.now();
  1158. let recoveryRound = 0;
  1159. const maxRecoveryRounds = 3;
  1160. while (Date.now() - start < timeout && recoveryRound < maxRecoveryRounds) {
  1161. throwIfStopped();
  1162. const roundNo = recoveryRound + 1;
  1163. log(`${prepareLogLabel}:等待页面进入验证码阶段(第 ${roundNo}/${maxRecoveryRounds} 轮,先等待 5 秒)...`, 'info');
  1164. const snapshot = await waitForSignupVerificationTransition(5000);
  1165. if (snapshot.state === 'step5') {
  1166. log(`${prepareLogLabel}:页面已进入验证码后的下一阶段,本步骤按已完成处理。`, 'ok');
  1167. return { ready: true, alreadyVerified: true, retried: recoveryRound, prepareSource };
  1168. }
  1169. if (snapshot.state === 'verification') {
  1170. log(`${prepareLogLabel}:验证码页面已就绪${recoveryRound ? `(期间自动恢复 ${recoveryRound} 次)` : ''}。`, 'ok');
  1171. return { ready: true, retried: recoveryRound, prepareSource };
  1172. }
  1173. if (snapshot.state === 'email_exists') {
  1174. throw new Error('当前邮箱已存在,需要重新开始新一轮。');
  1175. }
  1176. recoveryRound += 1;
  1177. if (snapshot.state === 'error') {
  1178. await recoverCurrentAuthRetryPage({
  1179. flow: 'signup_password',
  1180. logLabel: `${prepareLogLabel}:检测到密码页超时报错,正在点击“重试”恢复(第 ${recoveryRound}/${maxRecoveryRounds} 次)`,
  1181. step: 4,
  1182. timeoutMs: 12000,
  1183. });
  1184. continue;
  1185. }
  1186. if (snapshot.state === 'password') {
  1187. if (!password) {
  1188. throw new Error('当前回到了密码页,但没有可用密码,无法自动重新提交。');
  1189. }
  1190. if ((snapshot.passwordInput.value || '') !== password) {
  1191. log(`${prepareLogLabel}:页面仍停留在密码页,正在重新填写密码...`, 'warn');
  1192. await humanPause(450, 1100);
  1193. fillInput(snapshot.passwordInput, password);
  1194. }
  1195. if (snapshot.submitButton && isActionEnabled(snapshot.submitButton)) {
  1196. log(`${prepareLogLabel}:页面仍停留在密码页,正在重新点击“继续”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  1197. await humanPause(350, 900);
  1198. simulateClick(snapshot.submitButton);
  1199. await sleep(1200);
  1200. continue;
  1201. }
  1202. log(`${prepareLogLabel}:页面仍停留在密码页,但“继续”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  1203. continue;
  1204. }
  1205. log(`${prepareLogLabel}:页面仍在切换中,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  1206. }
  1207. throw new Error(`等待注册验证码页面就绪超时或自动恢复失败(已尝试 ${recoveryRound}/${maxRecoveryRounds} 轮)。URL: ${location.href}`);
  1208. }
  1209. async function waitForVerificationSubmitOutcome(step, timeout) {
  1210. const resolvedTimeout = timeout ?? (step === 8 ? 30000 : 12000);
  1211. const start = Date.now();
  1212. while (Date.now() - start < resolvedTimeout) {
  1213. throwIfStopped();
  1214. const errorText = getVerificationErrorText();
  1215. if (errorText) {
  1216. return { invalidCode: true, errorText };
  1217. }
  1218. if (step === 4 && isStep5Ready()) {
  1219. return { success: true };
  1220. }
  1221. if (step === 8 && isStep8Ready()) {
  1222. return { success: true };
  1223. }
  1224. if (step === 8 && isAddPhonePageReady()) {
  1225. return { success: true, addPhonePage: true, url: location.href };
  1226. }
  1227. await sleep(150);
  1228. }
  1229. if (isVerificationPageStillVisible()) {
  1230. return {
  1231. invalidCode: true,
  1232. errorText: getVerificationErrorText() || '提交后仍停留在验证码页面,准备重新发送验证码。',
  1233. };
  1234. }
  1235. return { success: true, assumed: true };
  1236. }
  1237. async function fillVerificationCode(step, payload) {
  1238. const { code } = payload;
  1239. if (!code) throw new Error('未提供验证码。');
  1240. log(`步骤 ${step}:正在填写验证码:${code}`);
  1241. if (step === 8) {
  1242. await waitForLoginVerificationPageReady();
  1243. }
  1244. // Find code input — could be a single input or multiple separate inputs
  1245. // Retry with 405 error recovery if needed
  1246. const maxRetries = 3;
  1247. let codeInput = null;
  1248. for (let retry = 0; retry <= maxRetries; retry++) {
  1249. throwIfStopped();
  1250. // Before looking for input, check if page is in 405 error state
  1251. if (is405MethodNotAllowedPage()) {
  1252. log(`步骤 ${step}:检测到 405 错误页面,正在恢复...`, 'warn');
  1253. await handle405ResendError(step, 30000);
  1254. continue;
  1255. }
  1256. try {
  1257. codeInput = await waitForElement(VERIFICATION_CODE_INPUT_SELECTOR, 10000);
  1258. break; // Found it
  1259. } catch {
  1260. // Check for multiple single-digit inputs (common pattern)
  1261. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  1262. if (singleInputs.length >= 6) {
  1263. log(`步骤 ${step}:发现分开的单字符验证码输入框,正在逐个填写...`);
  1264. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  1265. fillInput(singleInputs[i], code[i]);
  1266. await sleep(100);
  1267. }
  1268. const outcome = await waitForVerificationSubmitOutcome(step);
  1269. if (outcome.invalidCode) {
  1270. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  1271. } else if (outcome.addPhonePage) {
  1272. log(`步骤 ${step}:验证码提交后页面进入手机号页面,当前流程将停止自动授权。`, 'warn');
  1273. } else {
  1274. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  1275. }
  1276. return outcome;
  1277. }
  1278. // No input found — check if it's a 405 error and can be recovered
  1279. if (is405MethodNotAllowedPage() && retry < maxRetries) {
  1280. log(`步骤 ${step}:未找到验证码输入框且页面出现 405 错误,正在恢复...`, 'warn');
  1281. await handle405ResendError(step, 30000);
  1282. continue;
  1283. }
  1284. throw new Error('未找到验证码输入框。URL: ' + location.href);
  1285. }
  1286. }
  1287. if (!codeInput) {
  1288. throw new Error('未找到验证码输入框。URL: ' + location.href);
  1289. }
  1290. fillInput(codeInput, code);
  1291. log(`步骤 ${step}:验证码已填写`);
  1292. // Report complete BEFORE submit (page may navigate away)
  1293. // Submit
  1294. await sleep(500);
  1295. const submitBtn = document.querySelector('button[type="submit"]')
  1296. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证/i, 5000).catch(() => null);
  1297. if (submitBtn) {
  1298. await humanPause(450, 1200);
  1299. simulateClick(submitBtn);
  1300. log(`步骤 ${step}:验证码已提交`);
  1301. }
  1302. const outcome = await waitForVerificationSubmitOutcome(step);
  1303. if (outcome.invalidCode) {
  1304. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  1305. } else if (outcome.addPhonePage) {
  1306. log(`步骤 ${step}:验证码提交后页面进入手机号页面,当前流程将停止自动授权。`, 'warn');
  1307. } else {
  1308. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  1309. }
  1310. return outcome;
  1311. }
  1312. // ============================================================
  1313. // Step 6: Login with registered account (on OAuth auth page)
  1314. // ============================================================
  1315. async function waitForStep6EmailSubmitTransition(emailSubmittedAt, timeout = 12000) {
  1316. const start = Date.now();
  1317. let snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1318. while (Date.now() - start < timeout) {
  1319. throwIfStopped();
  1320. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1321. if (snapshot.state === 'verification_page') {
  1322. return {
  1323. action: 'done',
  1324. result: createStep6SuccessResult(snapshot, {
  1325. via: 'email_submit',
  1326. loginVerificationRequestedAt: emailSubmittedAt,
  1327. }),
  1328. };
  1329. }
  1330. if (snapshot.state === 'password_page') {
  1331. return { action: 'password', snapshot };
  1332. }
  1333. if (snapshot.state === 'login_timeout_error_page') {
  1334. return {
  1335. action: 'recoverable',
  1336. result: await createStep6LoginTimeoutRecoverableResult(
  1337. 'login_timeout_error_page',
  1338. snapshot,
  1339. '提交邮箱后进入登录超时报错页。'
  1340. ),
  1341. };
  1342. }
  1343. if (snapshot.state === 'oauth_consent_page') {
  1344. throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1345. }
  1346. if (snapshot.state === 'add_phone_page') {
  1347. throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1348. }
  1349. await sleep(250);
  1350. }
  1351. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1352. if (snapshot.state === 'verification_page') {
  1353. return {
  1354. action: 'done',
  1355. result: createStep6SuccessResult(snapshot, {
  1356. via: 'email_submit',
  1357. loginVerificationRequestedAt: emailSubmittedAt,
  1358. }),
  1359. };
  1360. }
  1361. if (snapshot.state === 'password_page') {
  1362. return { action: 'password', snapshot };
  1363. }
  1364. if (snapshot.state === 'login_timeout_error_page') {
  1365. return {
  1366. action: 'recoverable',
  1367. result: await createStep6LoginTimeoutRecoverableResult(
  1368. 'login_timeout_error_page',
  1369. snapshot,
  1370. '提交邮箱后进入登录超时报错页。'
  1371. ),
  1372. };
  1373. }
  1374. if (snapshot.state === 'oauth_consent_page') {
  1375. throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1376. }
  1377. if (snapshot.state === 'add_phone_page') {
  1378. throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1379. }
  1380. return {
  1381. action: 'recoverable',
  1382. result: createStep6RecoverableResult('email_submit_stalled', snapshot, {
  1383. message: '提交邮箱后长时间未进入密码页或登录验证码页。',
  1384. }),
  1385. };
  1386. }
  1387. async function waitForStep6PasswordSubmitTransition(passwordSubmittedAt, timeout = 10000) {
  1388. const start = Date.now();
  1389. let snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1390. while (Date.now() - start < timeout) {
  1391. throwIfStopped();
  1392. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1393. if (snapshot.state === 'verification_page') {
  1394. return {
  1395. action: 'done',
  1396. result: createStep6SuccessResult(snapshot, {
  1397. via: 'password_submit',
  1398. loginVerificationRequestedAt: passwordSubmittedAt,
  1399. }),
  1400. };
  1401. }
  1402. if (snapshot.state === 'login_timeout_error_page') {
  1403. return {
  1404. action: 'recoverable',
  1405. result: await createStep6LoginTimeoutRecoverableResult(
  1406. 'login_timeout_error_page',
  1407. snapshot,
  1408. '提交密码后进入登录超时报错页。'
  1409. ),
  1410. };
  1411. }
  1412. if (snapshot.state === 'oauth_consent_page') {
  1413. throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1414. }
  1415. if (snapshot.state === 'add_phone_page') {
  1416. throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1417. }
  1418. await sleep(250);
  1419. }
  1420. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1421. if (snapshot.state === 'verification_page') {
  1422. return {
  1423. action: 'done',
  1424. result: createStep6SuccessResult(snapshot, {
  1425. via: 'password_submit',
  1426. loginVerificationRequestedAt: passwordSubmittedAt,
  1427. }),
  1428. };
  1429. }
  1430. if (snapshot.state === 'login_timeout_error_page') {
  1431. return {
  1432. action: 'recoverable',
  1433. result: await createStep6LoginTimeoutRecoverableResult(
  1434. 'login_timeout_error_page',
  1435. snapshot,
  1436. '提交密码后进入登录超时报错页。'
  1437. ),
  1438. };
  1439. }
  1440. if (snapshot.state === 'oauth_consent_page') {
  1441. throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1442. }
  1443. if (snapshot.state === 'add_phone_page') {
  1444. throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1445. }
  1446. if (snapshot.state === 'password_page' && snapshot.switchTrigger) {
  1447. return { action: 'switch', snapshot };
  1448. }
  1449. return {
  1450. action: 'recoverable',
  1451. result: createStep6RecoverableResult('password_submit_stalled', snapshot, {
  1452. message: '提交密码后仍未进入登录验证码页。',
  1453. }),
  1454. };
  1455. }
  1456. async function waitForStep6SwitchTransition(loginVerificationRequestedAt, timeout = 10000) {
  1457. const start = Date.now();
  1458. let snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1459. while (Date.now() - start < timeout) {
  1460. throwIfStopped();
  1461. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1462. if (snapshot.state === 'verification_page') {
  1463. return createStep6SuccessResult(snapshot, {
  1464. via: 'switch_to_one_time_code_login',
  1465. loginVerificationRequestedAt,
  1466. });
  1467. }
  1468. if (snapshot.state === 'login_timeout_error_page') {
  1469. return await createStep6LoginTimeoutRecoverableResult(
  1470. 'login_timeout_error_page',
  1471. snapshot,
  1472. '切换到一次性验证码登录后进入登录超时报错页。'
  1473. );
  1474. }
  1475. if (snapshot.state === 'oauth_consent_page') {
  1476. throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1477. }
  1478. if (snapshot.state === 'add_phone_page') {
  1479. throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1480. }
  1481. await sleep(250);
  1482. }
  1483. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1484. if (snapshot.state === 'verification_page') {
  1485. return createStep6SuccessResult(snapshot, {
  1486. via: 'switch_to_one_time_code_login',
  1487. loginVerificationRequestedAt,
  1488. });
  1489. }
  1490. if (snapshot.state === 'login_timeout_error_page') {
  1491. return await createStep6LoginTimeoutRecoverableResult(
  1492. 'login_timeout_error_page',
  1493. snapshot,
  1494. '切换到一次性验证码登录后进入登录超时报错页。'
  1495. );
  1496. }
  1497. if (snapshot.state === 'oauth_consent_page') {
  1498. throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1499. }
  1500. if (snapshot.state === 'add_phone_page') {
  1501. throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1502. }
  1503. return createStep6RecoverableResult('one_time_code_switch_stalled', snapshot, {
  1504. message: '点击一次性验证码登录后仍未进入登录验证码页。',
  1505. });
  1506. }
  1507. async function step6SwitchToOneTimeCodeLogin(snapshot) {
  1508. const switchTrigger = snapshot?.switchTrigger || findOneTimeCodeLoginTrigger();
  1509. if (!switchTrigger || !isActionEnabled(switchTrigger)) {
  1510. return createStep6RecoverableResult('missing_one_time_code_trigger', normalizeStep6Snapshot(inspectLoginAuthState()), {
  1511. message: '当前登录页没有可用的一次性验证码登录入口。',
  1512. });
  1513. }
  1514. log('步骤 7:已检测到一次性验证码登录入口,准备切换...');
  1515. const loginVerificationRequestedAt = Date.now();
  1516. await humanPause(350, 900);
  1517. simulateClick(switchTrigger);
  1518. log('步骤 7:已点击一次性验证码登录');
  1519. await sleep(1200);
  1520. return waitForStep6SwitchTransition(loginVerificationRequestedAt);
  1521. }
  1522. async function step6LoginFromPasswordPage(payload, snapshot) {
  1523. const currentSnapshot = normalizeStep6Snapshot(snapshot || inspectLoginAuthState());
  1524. if (currentSnapshot.passwordInput) {
  1525. if (!payload.password) {
  1526. throw new Error('登录时缺少密码,步骤 7 无法继续。');
  1527. }
  1528. log('步骤 7:已进入密码页,准备填写密码...');
  1529. await humanPause(550, 1450);
  1530. fillInput(currentSnapshot.passwordInput, payload.password);
  1531. log('步骤 7:已填写密码');
  1532. await sleep(500);
  1533. const passwordSubmittedAt = Date.now();
  1534. await triggerLoginSubmitAction(currentSnapshot.submitButton, currentSnapshot.passwordInput);
  1535. log('步骤 7:已提交密码');
  1536. const transition = await waitForStep6PasswordSubmitTransition(passwordSubmittedAt);
  1537. if (transition.action === 'done') {
  1538. log('步骤 7:已进入登录验证码页面。', 'ok');
  1539. return transition.result;
  1540. }
  1541. if (transition.action === 'recoverable') {
  1542. log(`步骤 7:${transition.result.message || '提交密码后仍未进入登录验证码页面,准备重新执行步骤 7。'}`, 'warn');
  1543. return transition.result;
  1544. }
  1545. if (transition.action === 'switch') {
  1546. return step6SwitchToOneTimeCodeLogin(transition.snapshot);
  1547. }
  1548. return createStep6RecoverableResult('password_submit_unknown', normalizeStep6Snapshot(inspectLoginAuthState()), {
  1549. message: '提交密码后未得到可用的下一步状态。',
  1550. });
  1551. }
  1552. if (currentSnapshot.switchTrigger) {
  1553. return step6SwitchToOneTimeCodeLogin(currentSnapshot);
  1554. }
  1555. return createStep6RecoverableResult('password_page_unactionable', currentSnapshot, {
  1556. message: '当前停留在登录页,但没有可提交密码的输入框,也没有一次性验证码登录入口。',
  1557. });
  1558. }
  1559. async function step6LoginFromEmailPage(payload, snapshot) {
  1560. const currentSnapshot = normalizeStep6Snapshot(snapshot || inspectLoginAuthState());
  1561. const emailInput = currentSnapshot.emailInput || getLoginEmailInput();
  1562. if (!emailInput) {
  1563. throw new Error('在登录页未找到邮箱输入框。URL: ' + location.href);
  1564. }
  1565. if ((emailInput.value || '').trim() !== payload.email) {
  1566. await humanPause(500, 1400);
  1567. fillInput(emailInput, payload.email);
  1568. log('步骤 7:已填写邮箱');
  1569. } else {
  1570. log('步骤 7:邮箱已在输入框中,准备提交...');
  1571. }
  1572. await sleep(500);
  1573. const emailSubmittedAt = Date.now();
  1574. await triggerLoginSubmitAction(currentSnapshot.submitButton, emailInput);
  1575. log('步骤 7:已提交邮箱');
  1576. const transition = await waitForStep6EmailSubmitTransition(emailSubmittedAt);
  1577. if (transition.action === 'done') {
  1578. log('步骤 7:已进入登录验证码页面。', 'ok');
  1579. return transition.result;
  1580. }
  1581. if (transition.action === 'recoverable') {
  1582. log(`步骤 7:${transition.result.message || '提交邮箱后仍未进入目标页面,准备重新执行步骤 7。'}`, 'warn');
  1583. return transition.result;
  1584. }
  1585. if (transition.action === 'password') {
  1586. return step6LoginFromPasswordPage(payload, transition.snapshot);
  1587. }
  1588. return createStep6RecoverableResult('email_submit_unknown', normalizeStep6Snapshot(inspectLoginAuthState()), {
  1589. message: '提交邮箱后未得到可用的下一步状态。',
  1590. });
  1591. }
  1592. async function step6_login(payload) {
  1593. const { email } = payload;
  1594. if (!email) throw new Error('登录时缺少邮箱地址。');
  1595. log(`步骤 7:正在使用 ${email} 登录...`);
  1596. const snapshot = normalizeStep6Snapshot(await waitForKnownLoginAuthState(15000));
  1597. if (snapshot.state === 'verification_page') {
  1598. log('步骤 7:登录验证码页面已就绪。', 'ok');
  1599. return createStep6SuccessResult(snapshot, { via: 'already_on_verification_page' });
  1600. }
  1601. if (snapshot.state === 'login_timeout_error_page') {
  1602. log('步骤 7:检测到登录超时报错,准备重新执行步骤 7。', 'warn');
  1603. return await createStep6LoginTimeoutRecoverableResult(
  1604. 'login_timeout_error_page',
  1605. snapshot,
  1606. '当前页面处于登录超时报错页。'
  1607. );
  1608. }
  1609. if (snapshot.state === 'email_page') {
  1610. return step6LoginFromEmailPage(payload, snapshot);
  1611. }
  1612. if (snapshot.state === 'password_page') {
  1613. return step6LoginFromPasswordPage(payload, snapshot);
  1614. }
  1615. throwForStep6FatalState(snapshot);
  1616. throw new Error(`无法识别当前登录页面状态。URL: ${snapshot?.url || location.href}`);
  1617. }
  1618. // ============================================================
  1619. // Step 9: Find "继续" on OAuth consent page for debugger click
  1620. // ============================================================
  1621. // After login + verification, page shows:
  1622. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  1623. // Background performs the actual click through the debugger Input API.
  1624. async function step8_findAndClick() {
  1625. log('步骤 9:正在查找 OAuth 同意页的“继续”按钮...');
  1626. const continueBtn = await prepareStep8ContinueButton();
  1627. const rect = getSerializableRect(continueBtn);
  1628. log('步骤 9:已找到“继续”按钮并准备好调试器点击坐标。');
  1629. return {
  1630. rect,
  1631. buttonText: (continueBtn.textContent || '').trim(),
  1632. url: location.href,
  1633. };
  1634. }
  1635. function getStep8State() {
  1636. const continueBtn = getPrimaryContinueButton();
  1637. const retryState = getCurrentAuthRetryPageState('auth');
  1638. const state = {
  1639. url: location.href,
  1640. consentPage: isOAuthConsentPage(),
  1641. consentReady: isStep8Ready(),
  1642. verificationPage: isVerificationPageStillVisible(),
  1643. addPhonePage: isAddPhonePageReady(),
  1644. retryPage: Boolean(retryState),
  1645. retryEnabled: Boolean(retryState?.retryEnabled),
  1646. retryTitleMatched: Boolean(retryState?.titleMatched),
  1647. retryDetailMatched: Boolean(retryState?.detailMatched),
  1648. buttonFound: Boolean(continueBtn),
  1649. buttonEnabled: isButtonEnabled(continueBtn),
  1650. buttonText: continueBtn ? getActionText(continueBtn) : '',
  1651. };
  1652. if (continueBtn) {
  1653. try {
  1654. state.rect = getSerializableRect(continueBtn);
  1655. } catch {
  1656. state.rect = null;
  1657. }
  1658. }
  1659. return state;
  1660. }
  1661. async function step8_triggerContinue(payload = {}) {
  1662. const strategy = payload?.strategy || 'requestSubmit';
  1663. const continueBtn = await prepareStep8ContinueButton({
  1664. findTimeoutMs: payload?.findTimeoutMs,
  1665. enabledTimeoutMs: payload?.enabledTimeoutMs,
  1666. });
  1667. const form = continueBtn.form || continueBtn.closest('form');
  1668. switch (strategy) {
  1669. case 'requestSubmit':
  1670. if (!form || typeof form.requestSubmit !== 'function') {
  1671. throw new Error('“继续”按钮当前不在可提交的 form 中,无法使用 requestSubmit。URL: ' + location.href);
  1672. }
  1673. form.requestSubmit(continueBtn);
  1674. break;
  1675. case 'nativeClick':
  1676. continueBtn.click();
  1677. break;
  1678. case 'dispatchClick':
  1679. simulateClick(continueBtn);
  1680. break;
  1681. default:
  1682. throw new Error(`未知的 Step 9 触发策略:${strategy}`);
  1683. }
  1684. log(`Step 9: continue button triggered via ${strategy}.`);
  1685. return {
  1686. strategy,
  1687. ...getStep8State(),
  1688. };
  1689. }
  1690. async function prepareStep8ContinueButton(options = {}) {
  1691. const {
  1692. findTimeoutMs = 10000,
  1693. enabledTimeoutMs = 8000,
  1694. } = options;
  1695. const continueBtn = await findContinueButton(findTimeoutMs);
  1696. await waitForButtonEnabled(continueBtn, enabledTimeoutMs);
  1697. await humanPause(250, 700);
  1698. continueBtn.scrollIntoView({ behavior: 'auto', block: 'center' });
  1699. continueBtn.focus();
  1700. await waitForStableButtonRect(continueBtn);
  1701. return continueBtn;
  1702. }
  1703. async function findContinueButton(timeout = 10000) {
  1704. const start = Date.now();
  1705. while (Date.now() - start < timeout) {
  1706. throwIfStopped();
  1707. if (isAddPhonePageReady()) {
  1708. throw new Error('当前页面已进入手机号页面,不是 OAuth 授权同意页。URL: ' + location.href);
  1709. }
  1710. const button = getPrimaryContinueButton();
  1711. if (button && isStep8Ready()) {
  1712. return button;
  1713. }
  1714. await sleep(150);
  1715. }
  1716. throw new Error('在 OAuth 同意页未找到“继续”按钮,或页面尚未进入授权同意状态。URL: ' + location.href);
  1717. }
  1718. async function waitForButtonEnabled(button, timeout = 8000) {
  1719. const start = Date.now();
  1720. while (Date.now() - start < timeout) {
  1721. throwIfStopped();
  1722. if (isButtonEnabled(button)) return;
  1723. await sleep(150);
  1724. }
  1725. throw new Error('“继续”按钮长时间不可点击。URL: ' + location.href);
  1726. }
  1727. function isButtonEnabled(button) {
  1728. return Boolean(button)
  1729. && !button.disabled
  1730. && button.getAttribute('aria-disabled') !== 'true';
  1731. }
  1732. async function waitForStableButtonRect(button, timeout = 1500) {
  1733. let previous = null;
  1734. let stableSamples = 0;
  1735. const start = Date.now();
  1736. while (Date.now() - start < timeout) {
  1737. throwIfStopped();
  1738. const rect = button?.getBoundingClientRect?.();
  1739. if (rect && rect.width > 0 && rect.height > 0) {
  1740. const snapshot = {
  1741. left: rect.left,
  1742. top: rect.top,
  1743. width: rect.width,
  1744. height: rect.height,
  1745. };
  1746. if (
  1747. previous
  1748. && Math.abs(snapshot.left - previous.left) < 1
  1749. && Math.abs(snapshot.top - previous.top) < 1
  1750. && Math.abs(snapshot.width - previous.width) < 1
  1751. && Math.abs(snapshot.height - previous.height) < 1
  1752. ) {
  1753. stableSamples += 1;
  1754. if (stableSamples >= 2) {
  1755. return;
  1756. }
  1757. } else {
  1758. stableSamples = 0;
  1759. }
  1760. previous = snapshot;
  1761. }
  1762. await sleep(80);
  1763. }
  1764. }
  1765. function getSerializableRect(el) {
  1766. const rect = el.getBoundingClientRect();
  1767. if (!rect.width || !rect.height) {
  1768. throw new Error('滚动后“继续”按钮没有可点击尺寸。URL: ' + location.href);
  1769. }
  1770. return {
  1771. left: rect.left,
  1772. top: rect.top,
  1773. width: rect.width,
  1774. height: rect.height,
  1775. centerX: rect.left + (rect.width / 2),
  1776. centerY: rect.top + (rect.height / 2),
  1777. };
  1778. }
  1779. // ============================================================
  1780. // Step 5: Fill Name & Birthday / Age
  1781. // ============================================================
  1782. function getStep5DirectCompletionPayload({ isAgeMode = false } = {}) {
  1783. const payload = {
  1784. skippedPostSubmitCheck: true,
  1785. directProceedToStep6: true,
  1786. };
  1787. if (isAgeMode) {
  1788. payload.ageMode = true;
  1789. }
  1790. return payload;
  1791. }
  1792. async function step5_fillNameBirthday(payload) {
  1793. const { firstName, lastName, age, year, month, day } = payload;
  1794. if (!firstName || !lastName) throw new Error('未提供姓名数据。');
  1795. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  1796. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  1797. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  1798. throw new Error('未提供生日或年龄数据。');
  1799. }
  1800. const fullName = `${firstName} ${lastName}`;
  1801. log(`步骤 5:正在填写姓名:${fullName}`);
  1802. // Actual DOM structure:
  1803. // - Full name: <input name="name" placeholder="全名" type="text">
  1804. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  1805. // - Age: <input name="age" type="text|number">
  1806. // --- Full Name (single field, not first+last) ---
  1807. let nameInput = null;
  1808. try {
  1809. nameInput = await waitForElement(
  1810. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  1811. 10000
  1812. );
  1813. } catch {
  1814. throw new Error('未找到姓名输入框。URL: ' + location.href);
  1815. }
  1816. await humanPause(500, 1300);
  1817. fillInput(nameInput, fullName);
  1818. log(`步骤 5:姓名已填写:${fullName}`);
  1819. let birthdayMode = false;
  1820. let ageInput = null;
  1821. let yearSpinner = null;
  1822. let monthSpinner = null;
  1823. let daySpinner = null;
  1824. let hiddenBirthday = null;
  1825. let yearReactSelect = null;
  1826. let monthReactSelect = null;
  1827. let dayReactSelect = null;
  1828. let visibleAgeInput = false;
  1829. let visibleBirthdaySpinners = false;
  1830. let visibleBirthdaySelects = false;
  1831. for (let i = 0; i < 100; i++) {
  1832. yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1833. monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1834. daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1835. hiddenBirthday = document.querySelector('input[name="birthday"]');
  1836. ageInput = document.querySelector('input[name="age"]');
  1837. yearReactSelect = findBirthdayReactAriaSelect('年');
  1838. monthReactSelect = findBirthdayReactAriaSelect('月');
  1839. dayReactSelect = findBirthdayReactAriaSelect('天');
  1840. visibleAgeInput = Boolean(ageInput && isVisibleElement(ageInput));
  1841. visibleBirthdaySpinners = Boolean(
  1842. yearSpinner
  1843. && monthSpinner
  1844. && daySpinner
  1845. && isVisibleElement(yearSpinner)
  1846. && isVisibleElement(monthSpinner)
  1847. && isVisibleElement(daySpinner)
  1848. );
  1849. visibleBirthdaySelects = Boolean(
  1850. yearReactSelect?.button
  1851. && monthReactSelect?.button
  1852. && dayReactSelect?.button
  1853. && isVisibleElement(yearReactSelect.button)
  1854. && isVisibleElement(monthReactSelect.button)
  1855. && isVisibleElement(dayReactSelect.button)
  1856. );
  1857. if (visibleAgeInput) break;
  1858. if (visibleBirthdaySpinners || visibleBirthdaySelects) {
  1859. birthdayMode = true;
  1860. break;
  1861. }
  1862. await sleep(100);
  1863. }
  1864. if (birthdayMode) {
  1865. if (!hasBirthdayData) {
  1866. throw new Error('检测到生日字段,但未提供生日数据。');
  1867. }
  1868. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1869. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1870. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1871. const yearReactSelect = findBirthdayReactAriaSelect('年');
  1872. const monthReactSelect = findBirthdayReactAriaSelect('月');
  1873. const dayReactSelect = findBirthdayReactAriaSelect('天');
  1874. if (yearReactSelect?.nativeSelect && monthReactSelect?.nativeSelect && dayReactSelect?.nativeSelect) {
  1875. const desiredDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1876. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1877. log('步骤 5:检测到 React Aria 下拉生日字段,正在填写生日...');
  1878. await humanPause(450, 1100);
  1879. await setReactAriaBirthdaySelect(yearReactSelect, year);
  1880. await humanPause(250, 650);
  1881. await setReactAriaBirthdaySelect(monthReactSelect, month);
  1882. await humanPause(250, 650);
  1883. await setReactAriaBirthdaySelect(dayReactSelect, day);
  1884. if (hiddenBirthday) {
  1885. const start = Date.now();
  1886. while (Date.now() - start < 2000) {
  1887. if ((hiddenBirthday.value || '') === desiredDate) break;
  1888. await sleep(100);
  1889. }
  1890. if ((hiddenBirthday.value || '') !== desiredDate) {
  1891. throw new Error(`生日值未成功写入页面。期望 ${desiredDate},实际 ${(hiddenBirthday.value || '空')}。`);
  1892. }
  1893. }
  1894. log(`步骤 5:React Aria 生日已填写:${desiredDate}`);
  1895. }
  1896. if (yearSpinner && monthSpinner && daySpinner) {
  1897. log('步骤 5:检测到生日字段,正在填写生日...');
  1898. async function setSpinButton(el, value) {
  1899. el.focus();
  1900. await sleep(100);
  1901. document.execCommand('selectAll', false, null);
  1902. await sleep(50);
  1903. const valueStr = String(value);
  1904. for (const char of valueStr) {
  1905. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  1906. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  1907. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  1908. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  1909. await sleep(50);
  1910. }
  1911. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  1912. el.blur();
  1913. await sleep(100);
  1914. }
  1915. await humanPause(450, 1100);
  1916. await setSpinButton(yearSpinner, year);
  1917. await humanPause(250, 650);
  1918. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  1919. await humanPause(250, 650);
  1920. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  1921. log(`步骤 5:生日已填写:${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  1922. }
  1923. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1924. if (hiddenBirthday) {
  1925. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1926. hiddenBirthday.value = dateStr;
  1927. hiddenBirthday.dispatchEvent(new Event('input', { bubbles: true }));
  1928. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  1929. log(`步骤 5:已设置隐藏生日输入框:${dateStr}`);
  1930. }
  1931. } else if (ageInput) {
  1932. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  1933. throw new Error('检测到年龄字段,但未提供年龄数据。');
  1934. }
  1935. await humanPause(500, 1300);
  1936. fillInput(ageInput, String(resolvedAge));
  1937. log(`步骤 5:年龄已填写:${resolvedAge}`);
  1938. } else {
  1939. throw new Error('未找到生日或年龄输入项。URL: ' + location.href);
  1940. }
  1941. // 韩国IP判断勾选框""I agree"
  1942. const allConsentCheckbox = Array.from(document.querySelectorAll('input[name="allCheckboxes"][type="checkbox"]'))
  1943. .find((el) => {
  1944. const checkboxLabel = el.closest('label');
  1945. const labelText = normalizeInlineText(checkboxLabel?.textContent || '');
  1946. return (!checkboxLabel || isVisibleElement(checkboxLabel))
  1947. && /I\s+agree\s+to\s+all\s+of\s+the\s+following/i.test(labelText);
  1948. }) || null;
  1949. if (allConsentCheckbox) {
  1950. if (!allConsentCheckbox.checked) {
  1951. const checkboxLabel = allConsentCheckbox.closest('label');
  1952. await humanPause(500, 1500);
  1953. if (checkboxLabel && isVisibleElement(checkboxLabel)) {
  1954. simulateClick(checkboxLabel);
  1955. } else {
  1956. simulateClick(allConsentCheckbox);
  1957. }
  1958. await sleep(250);
  1959. if (!allConsentCheckbox.checked) {
  1960. allConsentCheckbox.click();
  1961. await sleep(250);
  1962. }
  1963. if (!allConsentCheckbox.checked) {
  1964. throw new Error('未能勾选 “I agree to all of the following” 复选框。');
  1965. }
  1966. log('步骤 5:已勾选 “I agree to all of the following”。');
  1967. } else {
  1968. log('步骤 5:“I agree to all of the following” 已勾选,跳过。');
  1969. }
  1970. }
  1971. // Click "完成帐户创建" button
  1972. await sleep(500);
  1973. const completeBtn = document.querySelector('button[type="submit"]')
  1974. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  1975. if (!completeBtn) {
  1976. throw new Error('未找到“完成帐户创建”按钮。URL: ' + location.href);
  1977. }
  1978. const isAgeMode = !birthdayMode && Boolean(ageInput);
  1979. if (isAgeMode) {
  1980. log('步骤 5:当前为年龄输入模式,点击“完成帐户创建”后将直接完成当前步骤。', 'warn');
  1981. }
  1982. await humanPause(500, 1300);
  1983. simulateClick(completeBtn);
  1984. const completionPayload = getStep5DirectCompletionPayload({ isAgeMode });
  1985. reportComplete(5, completionPayload);
  1986. if (isAgeMode) {
  1987. log('步骤 5:年龄模式已点击“完成帐户创建”,当前步骤直接完成,不再等待页面结果。', 'warn');
  1988. return completionPayload;
  1989. }
  1990. log('步骤 5:已点击“完成帐户创建”,当前步骤直接完成,不再等待页面结果。');
  1991. return completionPayload;
  1992. }