signup-page.js 78 KB

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