signup-page.js 79 KB

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