signup-page.js 77 KB

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