signup-page.js 78 KB

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