signup-page.js 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341
  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 (oauthConsentPage) {
  876. return {
  877. ...baseState,
  878. state: 'oauth_consent_page',
  879. };
  880. }
  881. if (passwordInput || switchTrigger) {
  882. return {
  883. ...baseState,
  884. state: 'password_page',
  885. };
  886. }
  887. if (emailInput) {
  888. return {
  889. ...baseState,
  890. state: 'email_page',
  891. };
  892. }
  893. if (verificationVisible) {
  894. return {
  895. ...baseState,
  896. state: 'verification_page',
  897. };
  898. }
  899. return baseState;
  900. }
  901. function serializeLoginAuthState(snapshot) {
  902. return {
  903. state: snapshot?.state || 'unknown',
  904. url: snapshot?.url || location.href,
  905. path: snapshot?.path || location.pathname || '',
  906. retryEnabled: Boolean(snapshot?.retryEnabled),
  907. titleMatched: Boolean(snapshot?.titleMatched),
  908. detailMatched: Boolean(snapshot?.detailMatched),
  909. hasVerificationTarget: Boolean(snapshot?.verificationTarget),
  910. hasPasswordInput: Boolean(snapshot?.passwordInput),
  911. hasEmailInput: Boolean(snapshot?.emailInput),
  912. hasSubmitButton: Boolean(snapshot?.submitButton),
  913. hasSwitchTrigger: Boolean(snapshot?.switchTrigger),
  914. verificationVisible: Boolean(snapshot?.verificationVisible),
  915. addPhonePage: Boolean(snapshot?.addPhonePage),
  916. oauthConsentPage: Boolean(snapshot?.oauthConsentPage),
  917. consentReady: Boolean(snapshot?.consentReady),
  918. };
  919. }
  920. function getLoginAuthStateLabel(snapshot) {
  921. switch (snapshot?.state) {
  922. case 'verification_page':
  923. return '登录验证码页';
  924. case 'password_page':
  925. return '密码页';
  926. case 'email_page':
  927. return '邮箱输入页';
  928. case 'login_timeout_error_page':
  929. return '登录超时报错页';
  930. case 'oauth_consent_page':
  931. return 'OAuth 授权页';
  932. case 'add_phone_page':
  933. return '手机号页';
  934. default:
  935. return '未知页面';
  936. }
  937. }
  938. async function waitForKnownLoginAuthState(timeout = 15000) {
  939. const start = Date.now();
  940. let snapshot = inspectLoginAuthState();
  941. while (Date.now() - start < timeout) {
  942. throwIfStopped();
  943. snapshot = inspectLoginAuthState();
  944. if (snapshot.state !== 'unknown') {
  945. return snapshot;
  946. }
  947. await sleep(200);
  948. }
  949. return snapshot;
  950. }
  951. async function waitForLoginVerificationPageReady(timeout = 10000) {
  952. const start = Date.now();
  953. let snapshot = inspectLoginAuthState();
  954. while (Date.now() - start < timeout) {
  955. throwIfStopped();
  956. snapshot = inspectLoginAuthState();
  957. if (snapshot.state === 'verification_page') {
  958. return snapshot;
  959. }
  960. if (snapshot.state !== 'unknown') {
  961. break;
  962. }
  963. await sleep(200);
  964. }
  965. throw new Error(
  966. `当前未进入登录验证码页面,请先重新完成步骤 6。当前状态:${getLoginAuthStateLabel(snapshot)}。URL: ${snapshot?.url || location.href}`
  967. );
  968. }
  969. function createStep6SuccessResult(snapshot, options = {}) {
  970. return {
  971. step6Outcome: 'success',
  972. state: snapshot?.state || 'verification_page',
  973. url: snapshot?.url || location.href,
  974. via: options.via || '',
  975. loginVerificationRequestedAt: options.loginVerificationRequestedAt || null,
  976. };
  977. }
  978. function createStep6RecoverableResult(reason, snapshot, options = {}) {
  979. return {
  980. step6Outcome: 'recoverable',
  981. reason,
  982. state: snapshot?.state || 'unknown',
  983. url: snapshot?.url || location.href,
  984. message: options.message || '',
  985. loginVerificationRequestedAt: options.loginVerificationRequestedAt || null,
  986. };
  987. }
  988. function throwForStep6FatalState(snapshot) {
  989. switch (snapshot?.state) {
  990. case 'oauth_consent_page':
  991. throw new Error(`当前页面已进入 OAuth 授权页,未经过登录验证码页,无法完成步骤 6。URL: ${snapshot.url}`);
  992. case 'add_phone_page':
  993. throw new Error(`当前页面已进入手机号页面,未经过登录验证码页,无法完成步骤 6。URL: ${snapshot.url}`);
  994. case 'unknown':
  995. throw new Error(`无法识别当前登录页面状态。URL: ${snapshot?.url || location.href}`);
  996. default:
  997. return;
  998. }
  999. }
  1000. async function triggerLoginSubmitAction(button, fallbackField) {
  1001. const form = button?.form || fallbackField?.form || button?.closest?.('form') || fallbackField?.closest?.('form') || null;
  1002. await humanPause(400, 1100);
  1003. if (button && isActionEnabled(button)) {
  1004. simulateClick(button);
  1005. return;
  1006. }
  1007. if (form && typeof form.requestSubmit === 'function') {
  1008. if (button && button.form === form) {
  1009. form.requestSubmit(button);
  1010. } else {
  1011. form.requestSubmit();
  1012. }
  1013. return;
  1014. }
  1015. if (button && typeof button.click === 'function') {
  1016. button.click();
  1017. return;
  1018. }
  1019. throw new Error('未找到可用的登录提交按钮。URL: ' + location.href);
  1020. }
  1021. function isSignupPasswordErrorPage() {
  1022. return Boolean(getSignupPasswordTimeoutErrorPageState());
  1023. }
  1024. function isSignupEmailAlreadyExistsPage() {
  1025. return isSignupPasswordPage() && SIGNUP_EMAIL_EXISTS_PATTERN.test(getPageTextSnapshot());
  1026. }
  1027. function inspectSignupVerificationState() {
  1028. if (isStep5Ready()) {
  1029. return { state: 'step5' };
  1030. }
  1031. if (isVerificationPageStillVisible()) {
  1032. return { state: 'verification' };
  1033. }
  1034. if (isSignupPasswordErrorPage()) {
  1035. const timeoutPage = getSignupPasswordTimeoutErrorPageState();
  1036. return {
  1037. state: 'error',
  1038. retryButton: timeoutPage?.retryButton || null,
  1039. };
  1040. }
  1041. if (isSignupEmailAlreadyExistsPage()) {
  1042. return { state: 'email_exists' };
  1043. }
  1044. const passwordInput = getSignupPasswordInput();
  1045. if (passwordInput) {
  1046. return {
  1047. state: 'password',
  1048. passwordInput,
  1049. submitButton: getSignupPasswordSubmitButton({ allowDisabled: true }),
  1050. };
  1051. }
  1052. return { state: 'unknown' };
  1053. }
  1054. async function waitForSignupVerificationTransition(timeout = 5000) {
  1055. const start = Date.now();
  1056. while (Date.now() - start < timeout) {
  1057. throwIfStopped();
  1058. const snapshot = inspectSignupVerificationState();
  1059. if (snapshot.state === 'step5' || snapshot.state === 'verification' || snapshot.state === 'error' || snapshot.state === 'email_exists') {
  1060. return snapshot;
  1061. }
  1062. await sleep(200);
  1063. }
  1064. return inspectSignupVerificationState();
  1065. }
  1066. async function prepareSignupVerificationFlow(payload = {}, timeout = 30000) {
  1067. const { password } = payload;
  1068. const start = Date.now();
  1069. let recoveryRound = 0;
  1070. const maxRecoveryRounds = 3;
  1071. while (Date.now() - start < timeout && recoveryRound < maxRecoveryRounds) {
  1072. throwIfStopped();
  1073. const roundNo = recoveryRound + 1;
  1074. log(`步骤 4:等待页面进入验证码阶段(第 ${roundNo}/${maxRecoveryRounds} 轮,先等待 5 秒)...`, 'info');
  1075. const snapshot = await waitForSignupVerificationTransition(5000);
  1076. if (snapshot.state === 'step5') {
  1077. log('步骤 4:页面已进入验证码后的下一阶段,本步骤按已完成处理。', 'ok');
  1078. return { ready: true, alreadyVerified: true, retried: recoveryRound };
  1079. }
  1080. if (snapshot.state === 'verification') {
  1081. log(`步骤 4:验证码页面已就绪${recoveryRound ? `(期间自动恢复 ${recoveryRound} 次)` : ''}。`, 'ok');
  1082. return { ready: true, retried: recoveryRound };
  1083. }
  1084. if (snapshot.state === 'email_exists') {
  1085. throw new Error('当前邮箱已存在,需要重新开始新一轮。');
  1086. }
  1087. recoveryRound += 1;
  1088. if (snapshot.state === 'error') {
  1089. if (snapshot.retryButton && isActionEnabled(snapshot.retryButton)) {
  1090. log(`步骤 4:检测到密码页超时报错,正在点击“重试”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  1091. await humanPause(350, 900);
  1092. simulateClick(snapshot.retryButton);
  1093. await sleep(1200);
  1094. continue;
  1095. }
  1096. log(`步骤 4:检测到异常页,但“重试”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  1097. continue;
  1098. }
  1099. if (snapshot.state === 'password') {
  1100. if (!password) {
  1101. throw new Error('当前回到了密码页,但没有可用密码,无法自动重新提交。');
  1102. }
  1103. if ((snapshot.passwordInput.value || '') !== password) {
  1104. log('步骤 4:页面仍停留在密码页,正在重新填写密码...', 'warn');
  1105. await humanPause(450, 1100);
  1106. fillInput(snapshot.passwordInput, password);
  1107. }
  1108. if (snapshot.submitButton && isActionEnabled(snapshot.submitButton)) {
  1109. log(`步骤 4:页面仍停留在密码页,正在重新点击“继续”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  1110. await humanPause(350, 900);
  1111. simulateClick(snapshot.submitButton);
  1112. await sleep(1200);
  1113. continue;
  1114. }
  1115. log(`步骤 4:页面仍停留在密码页,但“继续”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  1116. continue;
  1117. }
  1118. log(`步骤 4:页面仍在切换中,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  1119. }
  1120. throw new Error(`等待注册验证码页面就绪超时或自动恢复失败(已尝试 ${recoveryRound}/${maxRecoveryRounds} 轮)。URL: ${location.href}`);
  1121. }
  1122. async function waitForVerificationSubmitOutcome(step, timeout) {
  1123. const resolvedTimeout = timeout ?? (step === 7 ? 30000 : 12000);
  1124. const start = Date.now();
  1125. while (Date.now() - start < resolvedTimeout) {
  1126. throwIfStopped();
  1127. const errorText = getVerificationErrorText();
  1128. if (errorText) {
  1129. return { invalidCode: true, errorText };
  1130. }
  1131. if (step === 4 && isStep5Ready()) {
  1132. return { success: true };
  1133. }
  1134. if (step === 7 && isStep8Ready()) {
  1135. return { success: true };
  1136. }
  1137. if (step === 7 && isAddPhonePageReady()) {
  1138. return { success: true, addPhonePage: true };
  1139. }
  1140. await sleep(150);
  1141. }
  1142. if (isVerificationPageStillVisible()) {
  1143. return {
  1144. invalidCode: true,
  1145. errorText: getVerificationErrorText() || '提交后仍停留在验证码页面,准备重新发送验证码。',
  1146. };
  1147. }
  1148. return { success: true, assumed: true };
  1149. }
  1150. async function fillVerificationCode(step, payload) {
  1151. const { code } = payload;
  1152. if (!code) throw new Error('未提供验证码。');
  1153. log(`步骤 ${step}:正在填写验证码:${code}`);
  1154. if (step === 7) {
  1155. await waitForLoginVerificationPageReady();
  1156. }
  1157. // Find code input — could be a single input or multiple separate inputs
  1158. // Retry with 405 error recovery if needed
  1159. const maxRetries = 3;
  1160. let codeInput = null;
  1161. for (let retry = 0; retry <= maxRetries; retry++) {
  1162. throwIfStopped();
  1163. // Before looking for input, check if page is in 405 error state
  1164. if (is405MethodNotAllowedPage()) {
  1165. log(`步骤 ${step}:检测到 405 错误页面,正在恢复...`, 'warn');
  1166. await handle405ResendError(step, 30000);
  1167. continue;
  1168. }
  1169. try {
  1170. codeInput = await waitForElement(VERIFICATION_CODE_INPUT_SELECTOR, 10000);
  1171. break; // Found it
  1172. } catch {
  1173. // Check for multiple single-digit inputs (common pattern)
  1174. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  1175. if (singleInputs.length >= 6) {
  1176. log(`步骤 ${step}:发现分开的单字符验证码输入框,正在逐个填写...`);
  1177. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  1178. fillInput(singleInputs[i], code[i]);
  1179. await sleep(100);
  1180. }
  1181. const outcome = await waitForVerificationSubmitOutcome(step);
  1182. if (outcome.invalidCode) {
  1183. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  1184. } else if (outcome.addPhonePage) {
  1185. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  1186. } else {
  1187. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  1188. }
  1189. return outcome;
  1190. }
  1191. // No input found — check if it's a 405 error and can be recovered
  1192. if (is405MethodNotAllowedPage() && retry < maxRetries) {
  1193. log(`步骤 ${step}:未找到验证码输入框且页面出现 405 错误,正在恢复...`, 'warn');
  1194. await handle405ResendError(step, 30000);
  1195. continue;
  1196. }
  1197. throw new Error('未找到验证码输入框。URL: ' + location.href);
  1198. }
  1199. }
  1200. if (!codeInput) {
  1201. throw new Error('未找到验证码输入框。URL: ' + location.href);
  1202. }
  1203. fillInput(codeInput, code);
  1204. log(`步骤 ${step}:验证码已填写`);
  1205. // Report complete BEFORE submit (page may navigate away)
  1206. // Submit
  1207. await sleep(500);
  1208. const submitBtn = document.querySelector('button[type="submit"]')
  1209. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证/i, 5000).catch(() => null);
  1210. if (submitBtn) {
  1211. await humanPause(450, 1200);
  1212. simulateClick(submitBtn);
  1213. log(`步骤 ${step}:验证码已提交`);
  1214. }
  1215. const outcome = await waitForVerificationSubmitOutcome(step);
  1216. if (outcome.invalidCode) {
  1217. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  1218. } else if (outcome.addPhonePage) {
  1219. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  1220. } else {
  1221. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  1222. }
  1223. return outcome;
  1224. }
  1225. // ============================================================
  1226. // Step 6: Login with registered account (on OAuth auth page)
  1227. // ============================================================
  1228. async function waitForStep6EmailSubmitTransition(emailSubmittedAt, timeout = 12000) {
  1229. const start = Date.now();
  1230. let snapshot = inspectLoginAuthState();
  1231. while (Date.now() - start < timeout) {
  1232. throwIfStopped();
  1233. snapshot = inspectLoginAuthState();
  1234. if (snapshot.state === 'verification_page') {
  1235. return {
  1236. action: 'done',
  1237. result: createStep6SuccessResult(snapshot, {
  1238. via: 'email_submit',
  1239. loginVerificationRequestedAt: emailSubmittedAt,
  1240. }),
  1241. };
  1242. }
  1243. if (snapshot.state === 'password_page') {
  1244. return { action: 'password', snapshot };
  1245. }
  1246. if (snapshot.state === 'login_timeout_error_page') {
  1247. return {
  1248. action: 'recoverable',
  1249. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1250. message: '提交邮箱后进入登录超时报错页。',
  1251. }),
  1252. };
  1253. }
  1254. if (snapshot.state === 'oauth_consent_page') {
  1255. throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1256. }
  1257. if (snapshot.state === 'add_phone_page') {
  1258. throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1259. }
  1260. await sleep(250);
  1261. }
  1262. snapshot = inspectLoginAuthState();
  1263. if (snapshot.state === 'verification_page') {
  1264. return {
  1265. action: 'done',
  1266. result: createStep6SuccessResult(snapshot, {
  1267. via: 'email_submit',
  1268. loginVerificationRequestedAt: emailSubmittedAt,
  1269. }),
  1270. };
  1271. }
  1272. if (snapshot.state === 'password_page') {
  1273. return { action: 'password', snapshot };
  1274. }
  1275. if (snapshot.state === 'login_timeout_error_page') {
  1276. return {
  1277. action: 'recoverable',
  1278. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1279. message: '提交邮箱后进入登录超时报错页。',
  1280. }),
  1281. };
  1282. }
  1283. if (snapshot.state === 'oauth_consent_page') {
  1284. throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1285. }
  1286. if (snapshot.state === 'add_phone_page') {
  1287. throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1288. }
  1289. return {
  1290. action: 'recoverable',
  1291. result: createStep6RecoverableResult('email_submit_stalled', snapshot, {
  1292. message: '提交邮箱后长时间未进入密码页或登录验证码页。',
  1293. }),
  1294. };
  1295. }
  1296. async function waitForStep6PasswordSubmitTransition(passwordSubmittedAt, timeout = 10000) {
  1297. const start = Date.now();
  1298. let snapshot = inspectLoginAuthState();
  1299. while (Date.now() - start < timeout) {
  1300. throwIfStopped();
  1301. snapshot = inspectLoginAuthState();
  1302. if (snapshot.state === 'verification_page') {
  1303. return {
  1304. action: 'done',
  1305. result: createStep6SuccessResult(snapshot, {
  1306. via: 'password_submit',
  1307. loginVerificationRequestedAt: passwordSubmittedAt,
  1308. }),
  1309. };
  1310. }
  1311. if (snapshot.state === 'login_timeout_error_page') {
  1312. return {
  1313. action: 'recoverable',
  1314. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1315. message: '提交密码后进入登录超时报错页。',
  1316. }),
  1317. };
  1318. }
  1319. if (snapshot.state === 'oauth_consent_page') {
  1320. throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1321. }
  1322. if (snapshot.state === 'add_phone_page') {
  1323. throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1324. }
  1325. await sleep(250);
  1326. }
  1327. snapshot = inspectLoginAuthState();
  1328. if (snapshot.state === 'verification_page') {
  1329. return {
  1330. action: 'done',
  1331. result: createStep6SuccessResult(snapshot, {
  1332. via: 'password_submit',
  1333. loginVerificationRequestedAt: passwordSubmittedAt,
  1334. }),
  1335. };
  1336. }
  1337. if (snapshot.state === 'login_timeout_error_page') {
  1338. return {
  1339. action: 'recoverable',
  1340. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1341. message: '提交密码后进入登录超时报错页。',
  1342. }),
  1343. };
  1344. }
  1345. if (snapshot.state === 'oauth_consent_page') {
  1346. throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1347. }
  1348. if (snapshot.state === 'add_phone_page') {
  1349. throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1350. }
  1351. if (snapshot.state === 'password_page' && snapshot.switchTrigger) {
  1352. return { action: 'switch', snapshot };
  1353. }
  1354. return {
  1355. action: 'recoverable',
  1356. result: createStep6RecoverableResult('password_submit_stalled', snapshot, {
  1357. message: '提交密码后仍未进入登录验证码页。',
  1358. }),
  1359. };
  1360. }
  1361. async function waitForStep6SwitchTransition(loginVerificationRequestedAt, timeout = 10000) {
  1362. const start = Date.now();
  1363. let snapshot = inspectLoginAuthState();
  1364. while (Date.now() - start < timeout) {
  1365. throwIfStopped();
  1366. snapshot = inspectLoginAuthState();
  1367. if (snapshot.state === 'verification_page') {
  1368. return createStep6SuccessResult(snapshot, {
  1369. via: 'switch_to_one_time_code_login',
  1370. loginVerificationRequestedAt,
  1371. });
  1372. }
  1373. if (snapshot.state === 'login_timeout_error_page') {
  1374. return createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1375. message: '切换到一次性验证码登录后进入登录超时报错页。',
  1376. });
  1377. }
  1378. if (snapshot.state === 'oauth_consent_page') {
  1379. throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1380. }
  1381. if (snapshot.state === 'add_phone_page') {
  1382. throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1383. }
  1384. await sleep(250);
  1385. }
  1386. snapshot = inspectLoginAuthState();
  1387. if (snapshot.state === 'verification_page') {
  1388. return createStep6SuccessResult(snapshot, {
  1389. via: 'switch_to_one_time_code_login',
  1390. loginVerificationRequestedAt,
  1391. });
  1392. }
  1393. if (snapshot.state === 'login_timeout_error_page') {
  1394. return createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1395. message: '切换到一次性验证码登录后进入登录超时报错页。',
  1396. });
  1397. }
  1398. if (snapshot.state === 'oauth_consent_page') {
  1399. throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1400. }
  1401. if (snapshot.state === 'add_phone_page') {
  1402. throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1403. }
  1404. return createStep6RecoverableResult('one_time_code_switch_stalled', snapshot, {
  1405. message: '点击一次性验证码登录后仍未进入登录验证码页。',
  1406. });
  1407. }
  1408. async function step6SwitchToOneTimeCodeLogin(snapshot) {
  1409. const switchTrigger = snapshot?.switchTrigger || findOneTimeCodeLoginTrigger();
  1410. if (!switchTrigger || !isActionEnabled(switchTrigger)) {
  1411. return createStep6RecoverableResult('missing_one_time_code_trigger', inspectLoginAuthState(), {
  1412. message: '当前登录页没有可用的一次性验证码登录入口。',
  1413. });
  1414. }
  1415. log('步骤 6:已检测到一次性验证码登录入口,准备切换...');
  1416. const loginVerificationRequestedAt = Date.now();
  1417. await humanPause(350, 900);
  1418. simulateClick(switchTrigger);
  1419. log('步骤 6:已点击一次性验证码登录');
  1420. await sleep(1200);
  1421. return waitForStep6SwitchTransition(loginVerificationRequestedAt);
  1422. }
  1423. async function step6LoginFromPasswordPage(payload, snapshot) {
  1424. const currentSnapshot = snapshot || inspectLoginAuthState();
  1425. if (currentSnapshot.passwordInput) {
  1426. if (!payload.password) {
  1427. throw new Error('登录时缺少密码,步骤 6 无法继续。');
  1428. }
  1429. log('步骤 6:已进入密码页,准备填写密码...');
  1430. await humanPause(550, 1450);
  1431. fillInput(currentSnapshot.passwordInput, payload.password);
  1432. log('步骤 6:已填写密码');
  1433. await sleep(500);
  1434. const passwordSubmittedAt = Date.now();
  1435. await triggerLoginSubmitAction(currentSnapshot.submitButton, currentSnapshot.passwordInput);
  1436. log('步骤 6:已提交密码');
  1437. const transition = await waitForStep6PasswordSubmitTransition(passwordSubmittedAt);
  1438. if (transition.action === 'done') {
  1439. log('步骤 6:已进入登录验证码页面。', 'ok');
  1440. return transition.result;
  1441. }
  1442. if (transition.action === 'recoverable') {
  1443. log(`步骤 6:${transition.result.message || '提交密码后仍未进入登录验证码页面,准备重新执行步骤 6。'}`, 'warn');
  1444. return transition.result;
  1445. }
  1446. if (transition.action === 'switch') {
  1447. return step6SwitchToOneTimeCodeLogin(transition.snapshot);
  1448. }
  1449. return createStep6RecoverableResult('password_submit_unknown', inspectLoginAuthState(), {
  1450. message: '提交密码后未得到可用的下一步状态。',
  1451. });
  1452. }
  1453. if (currentSnapshot.switchTrigger) {
  1454. return step6SwitchToOneTimeCodeLogin(currentSnapshot);
  1455. }
  1456. return createStep6RecoverableResult('password_page_unactionable', currentSnapshot, {
  1457. message: '当前停留在登录页,但没有可提交密码的输入框,也没有一次性验证码登录入口。',
  1458. });
  1459. }
  1460. async function step6LoginFromEmailPage(payload, snapshot) {
  1461. const currentSnapshot = snapshot || inspectLoginAuthState();
  1462. const emailInput = currentSnapshot.emailInput || getLoginEmailInput();
  1463. if (!emailInput) {
  1464. throw new Error('在登录页未找到邮箱输入框。URL: ' + location.href);
  1465. }
  1466. if ((emailInput.value || '').trim() !== payload.email) {
  1467. await humanPause(500, 1400);
  1468. fillInput(emailInput, payload.email);
  1469. log('步骤 6:已填写邮箱');
  1470. } else {
  1471. log('步骤 6:邮箱已在输入框中,准备提交...');
  1472. }
  1473. await sleep(500);
  1474. const emailSubmittedAt = Date.now();
  1475. await triggerLoginSubmitAction(currentSnapshot.submitButton, emailInput);
  1476. log('步骤 6:已提交邮箱');
  1477. const transition = await waitForStep6EmailSubmitTransition(emailSubmittedAt);
  1478. if (transition.action === 'done') {
  1479. log('步骤 6:已进入登录验证码页面。', 'ok');
  1480. return transition.result;
  1481. }
  1482. if (transition.action === 'recoverable') {
  1483. log(`步骤 6:${transition.result.message || '提交邮箱后仍未进入目标页面,准备重新执行步骤 6。'}`, 'warn');
  1484. return transition.result;
  1485. }
  1486. if (transition.action === 'password') {
  1487. return step6LoginFromPasswordPage(payload, transition.snapshot);
  1488. }
  1489. return createStep6RecoverableResult('email_submit_unknown', inspectLoginAuthState(), {
  1490. message: '提交邮箱后未得到可用的下一步状态。',
  1491. });
  1492. }
  1493. async function step6_login(payload) {
  1494. const { email } = payload;
  1495. if (!email) throw new Error('登录时缺少邮箱地址。');
  1496. log(`步骤 6:正在使用 ${email} 登录...`);
  1497. const snapshot = await waitForKnownLoginAuthState(15000);
  1498. if (snapshot.state === 'verification_page') {
  1499. log('步骤 6:登录验证码页面已就绪。', 'ok');
  1500. return createStep6SuccessResult(snapshot, { via: 'already_on_verification_page' });
  1501. }
  1502. if (snapshot.state === 'login_timeout_error_page') {
  1503. log('步骤 6:检测到登录超时报错,准备重新执行步骤 6。', 'warn');
  1504. return createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1505. message: '当前页面处于登录超时报错页。',
  1506. });
  1507. }
  1508. if (snapshot.state === 'email_page') {
  1509. return step6LoginFromEmailPage(payload, snapshot);
  1510. }
  1511. if (snapshot.state === 'password_page') {
  1512. return step6LoginFromPasswordPage(payload, snapshot);
  1513. }
  1514. throwForStep6FatalState(snapshot);
  1515. throw new Error(`无法识别当前登录页面状态。URL: ${snapshot?.url || location.href}`);
  1516. }
  1517. // ============================================================
  1518. // Step 8: Find "继续" on OAuth consent page for debugger click
  1519. // ============================================================
  1520. // After login + verification, page shows:
  1521. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  1522. // Background performs the actual click through the debugger Input API.
  1523. async function step8_findAndClick() {
  1524. log('步骤 8:正在查找 OAuth 同意页的“继续”按钮...');
  1525. const continueBtn = await prepareStep8ContinueButton();
  1526. const rect = getSerializableRect(continueBtn);
  1527. log('步骤 8:已找到“继续”按钮并准备好调试器点击坐标。');
  1528. return {
  1529. rect,
  1530. buttonText: (continueBtn.textContent || '').trim(),
  1531. url: location.href,
  1532. };
  1533. }
  1534. function getStep8State() {
  1535. const continueBtn = getPrimaryContinueButton();
  1536. const state = {
  1537. url: location.href,
  1538. consentPage: isOAuthConsentPage(),
  1539. consentReady: isStep8Ready(),
  1540. verificationPage: isVerificationPageStillVisible(),
  1541. addPhonePage: isAddPhonePageReady(),
  1542. buttonFound: Boolean(continueBtn),
  1543. buttonEnabled: isButtonEnabled(continueBtn),
  1544. buttonText: continueBtn ? getActionText(continueBtn) : '',
  1545. };
  1546. if (continueBtn) {
  1547. try {
  1548. state.rect = getSerializableRect(continueBtn);
  1549. } catch {
  1550. state.rect = null;
  1551. }
  1552. }
  1553. return state;
  1554. }
  1555. async function step8_triggerContinue(payload = {}) {
  1556. const strategy = payload?.strategy || 'requestSubmit';
  1557. const continueBtn = await prepareStep8ContinueButton({
  1558. findTimeoutMs: payload?.findTimeoutMs,
  1559. enabledTimeoutMs: payload?.enabledTimeoutMs,
  1560. });
  1561. const form = continueBtn.form || continueBtn.closest('form');
  1562. switch (strategy) {
  1563. case 'requestSubmit':
  1564. if (!form || typeof form.requestSubmit !== 'function') {
  1565. throw new Error('“继续”按钮当前不在可提交的 form 中,无法使用 requestSubmit。URL: ' + location.href);
  1566. }
  1567. form.requestSubmit(continueBtn);
  1568. break;
  1569. case 'nativeClick':
  1570. continueBtn.click();
  1571. break;
  1572. case 'dispatchClick':
  1573. simulateClick(continueBtn);
  1574. break;
  1575. default:
  1576. throw new Error(`未知的 Step 8 触发策略:${strategy}`);
  1577. }
  1578. log(`Step 8: continue button triggered via ${strategy}.`);
  1579. return {
  1580. strategy,
  1581. ...getStep8State(),
  1582. };
  1583. }
  1584. async function prepareStep8ContinueButton(options = {}) {
  1585. const {
  1586. findTimeoutMs = 10000,
  1587. enabledTimeoutMs = 8000,
  1588. } = options;
  1589. const continueBtn = await findContinueButton(findTimeoutMs);
  1590. await waitForButtonEnabled(continueBtn, enabledTimeoutMs);
  1591. await humanPause(250, 700);
  1592. continueBtn.scrollIntoView({ behavior: 'auto', block: 'center' });
  1593. continueBtn.focus();
  1594. await waitForStableButtonRect(continueBtn);
  1595. return continueBtn;
  1596. }
  1597. async function findContinueButton(timeout = 10000) {
  1598. const start = Date.now();
  1599. while (Date.now() - start < timeout) {
  1600. throwIfStopped();
  1601. if (isAddPhonePageReady()) {
  1602. throw new Error('当前页面已进入手机号页面,不是 OAuth 授权同意页。URL: ' + location.href);
  1603. }
  1604. const button = getPrimaryContinueButton();
  1605. if (button && isStep8Ready()) {
  1606. return button;
  1607. }
  1608. await sleep(150);
  1609. }
  1610. throw new Error('在 OAuth 同意页未找到“继续”按钮,或页面尚未进入授权同意状态。URL: ' + location.href);
  1611. }
  1612. async function waitForButtonEnabled(button, timeout = 8000) {
  1613. const start = Date.now();
  1614. while (Date.now() - start < timeout) {
  1615. throwIfStopped();
  1616. if (isButtonEnabled(button)) return;
  1617. await sleep(150);
  1618. }
  1619. throw new Error('“继续”按钮长时间不可点击。URL: ' + location.href);
  1620. }
  1621. function isButtonEnabled(button) {
  1622. return Boolean(button)
  1623. && !button.disabled
  1624. && button.getAttribute('aria-disabled') !== 'true';
  1625. }
  1626. async function waitForStableButtonRect(button, timeout = 1500) {
  1627. let previous = null;
  1628. let stableSamples = 0;
  1629. const start = Date.now();
  1630. while (Date.now() - start < timeout) {
  1631. throwIfStopped();
  1632. const rect = button?.getBoundingClientRect?.();
  1633. if (rect && rect.width > 0 && rect.height > 0) {
  1634. const snapshot = {
  1635. left: rect.left,
  1636. top: rect.top,
  1637. width: rect.width,
  1638. height: rect.height,
  1639. };
  1640. if (
  1641. previous
  1642. && Math.abs(snapshot.left - previous.left) < 1
  1643. && Math.abs(snapshot.top - previous.top) < 1
  1644. && Math.abs(snapshot.width - previous.width) < 1
  1645. && Math.abs(snapshot.height - previous.height) < 1
  1646. ) {
  1647. stableSamples += 1;
  1648. if (stableSamples >= 2) {
  1649. return;
  1650. }
  1651. } else {
  1652. stableSamples = 0;
  1653. }
  1654. previous = snapshot;
  1655. }
  1656. await sleep(80);
  1657. }
  1658. }
  1659. function getSerializableRect(el) {
  1660. const rect = el.getBoundingClientRect();
  1661. if (!rect.width || !rect.height) {
  1662. throw new Error('滚动后“继续”按钮没有可点击尺寸。URL: ' + location.href);
  1663. }
  1664. return {
  1665. left: rect.left,
  1666. top: rect.top,
  1667. width: rect.width,
  1668. height: rect.height,
  1669. centerX: rect.left + (rect.width / 2),
  1670. centerY: rect.top + (rect.height / 2),
  1671. };
  1672. }
  1673. // ============================================================
  1674. // Step 5: Fill Name & Birthday / Age
  1675. // ============================================================
  1676. async function step5_fillNameBirthday(payload) {
  1677. const { firstName, lastName, age, year, month, day } = payload;
  1678. if (!firstName || !lastName) throw new Error('未提供姓名数据。');
  1679. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  1680. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  1681. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  1682. throw new Error('未提供生日或年龄数据。');
  1683. }
  1684. const fullName = `${firstName} ${lastName}`;
  1685. log(`步骤 5:正在填写姓名:${fullName}`);
  1686. // Actual DOM structure:
  1687. // - Full name: <input name="name" placeholder="全名" type="text">
  1688. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  1689. // - Age: <input name="age" type="text|number">
  1690. // --- Full Name (single field, not first+last) ---
  1691. let nameInput = null;
  1692. try {
  1693. nameInput = await waitForElement(
  1694. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  1695. 10000
  1696. );
  1697. } catch {
  1698. throw new Error('未找到姓名输入框。URL: ' + location.href);
  1699. }
  1700. await humanPause(500, 1300);
  1701. fillInput(nameInput, fullName);
  1702. log(`步骤 5:姓名已填写:${fullName}`);
  1703. let birthdayMode = false;
  1704. let ageInput = null;
  1705. let yearSpinner = null;
  1706. let monthSpinner = null;
  1707. let daySpinner = null;
  1708. let hiddenBirthday = null;
  1709. let yearReactSelect = null;
  1710. let monthReactSelect = null;
  1711. let dayReactSelect = null;
  1712. let visibleAgeInput = false;
  1713. let visibleBirthdaySpinners = false;
  1714. let visibleBirthdaySelects = false;
  1715. for (let i = 0; i < 100; i++) {
  1716. yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1717. monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1718. daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1719. hiddenBirthday = document.querySelector('input[name="birthday"]');
  1720. ageInput = document.querySelector('input[name="age"]');
  1721. yearReactSelect = findBirthdayReactAriaSelect('年');
  1722. monthReactSelect = findBirthdayReactAriaSelect('月');
  1723. dayReactSelect = findBirthdayReactAriaSelect('天');
  1724. visibleAgeInput = Boolean(ageInput && isVisibleElement(ageInput));
  1725. visibleBirthdaySpinners = Boolean(
  1726. yearSpinner
  1727. && monthSpinner
  1728. && daySpinner
  1729. && isVisibleElement(yearSpinner)
  1730. && isVisibleElement(monthSpinner)
  1731. && isVisibleElement(daySpinner)
  1732. );
  1733. visibleBirthdaySelects = Boolean(
  1734. yearReactSelect?.button
  1735. && monthReactSelect?.button
  1736. && dayReactSelect?.button
  1737. && isVisibleElement(yearReactSelect.button)
  1738. && isVisibleElement(monthReactSelect.button)
  1739. && isVisibleElement(dayReactSelect.button)
  1740. );
  1741. if (visibleAgeInput) break;
  1742. if (visibleBirthdaySpinners || visibleBirthdaySelects) {
  1743. birthdayMode = true;
  1744. break;
  1745. }
  1746. await sleep(100);
  1747. }
  1748. if (birthdayMode) {
  1749. if (!hasBirthdayData) {
  1750. throw new Error('检测到生日字段,但未提供生日数据。');
  1751. }
  1752. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1753. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1754. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1755. const yearReactSelect = findBirthdayReactAriaSelect('年');
  1756. const monthReactSelect = findBirthdayReactAriaSelect('月');
  1757. const dayReactSelect = findBirthdayReactAriaSelect('天');
  1758. if (yearReactSelect?.nativeSelect && monthReactSelect?.nativeSelect && dayReactSelect?.nativeSelect) {
  1759. const desiredDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1760. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1761. log('步骤 5:检测到 React Aria 下拉生日字段,正在填写生日...');
  1762. await humanPause(450, 1100);
  1763. await setReactAriaBirthdaySelect(yearReactSelect, year);
  1764. await humanPause(250, 650);
  1765. await setReactAriaBirthdaySelect(monthReactSelect, month);
  1766. await humanPause(250, 650);
  1767. await setReactAriaBirthdaySelect(dayReactSelect, day);
  1768. if (hiddenBirthday) {
  1769. const start = Date.now();
  1770. while (Date.now() - start < 2000) {
  1771. if ((hiddenBirthday.value || '') === desiredDate) break;
  1772. await sleep(100);
  1773. }
  1774. if ((hiddenBirthday.value || '') !== desiredDate) {
  1775. throw new Error(`生日值未成功写入页面。期望 ${desiredDate},实际 ${(hiddenBirthday.value || '空')}。`);
  1776. }
  1777. }
  1778. log(`步骤 5:React Aria 生日已填写:${desiredDate}`);
  1779. }
  1780. if (yearSpinner && monthSpinner && daySpinner) {
  1781. log('步骤 5:检测到生日字段,正在填写生日...');
  1782. async function setSpinButton(el, value) {
  1783. el.focus();
  1784. await sleep(100);
  1785. document.execCommand('selectAll', false, null);
  1786. await sleep(50);
  1787. const valueStr = String(value);
  1788. for (const char of valueStr) {
  1789. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  1790. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  1791. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  1792. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  1793. await sleep(50);
  1794. }
  1795. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  1796. el.blur();
  1797. await sleep(100);
  1798. }
  1799. await humanPause(450, 1100);
  1800. await setSpinButton(yearSpinner, year);
  1801. await humanPause(250, 650);
  1802. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  1803. await humanPause(250, 650);
  1804. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  1805. log(`步骤 5:生日已填写:${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  1806. }
  1807. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1808. if (hiddenBirthday) {
  1809. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1810. hiddenBirthday.value = dateStr;
  1811. hiddenBirthday.dispatchEvent(new Event('input', { bubbles: true }));
  1812. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  1813. log(`步骤 5:已设置隐藏生日输入框:${dateStr}`);
  1814. }
  1815. } else if (ageInput) {
  1816. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  1817. throw new Error('检测到年龄字段,但未提供年龄数据。');
  1818. }
  1819. await humanPause(500, 1300);
  1820. fillInput(ageInput, String(resolvedAge));
  1821. log(`步骤 5:年龄已填写:${resolvedAge}`);
  1822. } else {
  1823. throw new Error('未找到生日或年龄输入项。URL: ' + location.href);
  1824. }
  1825. // 韩国IP判断勾选框""I agree"
  1826. const allConsentCheckbox = Array.from(document.querySelectorAll('input[name="allCheckboxes"][type="checkbox"]'))
  1827. .find((el) => {
  1828. const checkboxLabel = el.closest('label');
  1829. const labelText = normalizeInlineText(checkboxLabel?.textContent || '');
  1830. return (!checkboxLabel || isVisibleElement(checkboxLabel))
  1831. && /I\s+agree\s+to\s+all\s+of\s+the\s+following/i.test(labelText);
  1832. }) || null;
  1833. if (allConsentCheckbox) {
  1834. if (!allConsentCheckbox.checked) {
  1835. const checkboxLabel = allConsentCheckbox.closest('label');
  1836. await humanPause(500, 1500);
  1837. if (checkboxLabel && isVisibleElement(checkboxLabel)) {
  1838. simulateClick(checkboxLabel);
  1839. } else {
  1840. simulateClick(allConsentCheckbox);
  1841. }
  1842. await sleep(250);
  1843. if (!allConsentCheckbox.checked) {
  1844. allConsentCheckbox.click();
  1845. await sleep(250);
  1846. }
  1847. if (!allConsentCheckbox.checked) {
  1848. throw new Error('未能勾选 “I agree to all of the following” 复选框。');
  1849. }
  1850. log('步骤 5:已勾选 “I agree to all of the following”。');
  1851. } else {
  1852. log('步骤 5:“I agree to all of the following” 已勾选,跳过。');
  1853. }
  1854. }
  1855. // Click "完成帐户创建" button
  1856. await sleep(500);
  1857. const completeBtn = document.querySelector('button[type="submit"]')
  1858. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  1859. if (!completeBtn) {
  1860. throw new Error('未找到“完成帐户创建”按钮。URL: ' + location.href);
  1861. }
  1862. const isAgeMode = !birthdayMode && Boolean(ageInput);
  1863. if (isAgeMode) {
  1864. log('步骤 5:当前为年龄输入模式,点击“继续”后将直接视为完成并进入步骤 6。', 'warn');
  1865. reportComplete(5, {
  1866. skippedPostSubmitCheck: true,
  1867. directProceedToStep6: true,
  1868. });
  1869. }
  1870. await humanPause(500, 1300);
  1871. simulateClick(completeBtn);
  1872. if (isAgeMode) {
  1873. log('步骤 5:年龄模式已点击“继续”,已跳过后续结果等待。', 'warn');
  1874. return;
  1875. }
  1876. log('步骤 5:已点击“完成帐户创建”,正在等待页面结果...');
  1877. const outcome = await waitForStep5SubmitOutcome();
  1878. if (outcome.invalidProfile) {
  1879. throw new Error(`步骤 5:${outcome.errorText}`);
  1880. }
  1881. if (outcome.chatgptOnboarding || outcome.chatgptHome) {
  1882. if (outcome.chatgptOnboarding) {
  1883. log('步骤 5:资料已通过,页面已跳转到 ChatGPT 引导页。', 'ok');
  1884. } else {
  1885. log('步骤 5:资料已通过,页面已进入已登录的 ChatGPT 页面。', 'ok');
  1886. }
  1887. reportComplete(5, {
  1888. chatgptOnboarding: Boolean(outcome.chatgptOnboarding),
  1889. chatgptHome: Boolean(outcome.chatgptHome),
  1890. });
  1891. return {
  1892. chatgptOnboarding: Boolean(outcome.chatgptOnboarding),
  1893. chatgptHome: Boolean(outcome.chatgptHome),
  1894. };
  1895. }
  1896. log(`步骤 5:资料已通过。`, 'ok');
  1897. reportComplete(5, { addPhonePage: Boolean(outcome.addPhonePage) });
  1898. }
  1899. // ============================================================
  1900. // ChatGPT Onboarding: Skip buttons after signup redirect
  1901. // ============================================================
  1902. function findChatgptSkipButton() {
  1903. // Look for buttons containing "Skip" or "跳过" text with btn-ghost class
  1904. const buttons = document.querySelectorAll('button');
  1905. for (const btn of buttons) {
  1906. if (!isVisibleElement(btn)) continue;
  1907. const text = (btn.textContent || '').trim();
  1908. if (/^(skip|跳过)$/i.test(text) && /btn-ghost/i.test(btn.className)) {
  1909. return btn;
  1910. }
  1911. }
  1912. // Fallback: look for any button matching skip text without class constraint
  1913. for (const btn of buttons) {
  1914. if (!isVisibleElement(btn)) continue;
  1915. const text = (btn.textContent || '').trim();
  1916. if (/^(skip|跳过)$/i.test(text)) {
  1917. return btn;
  1918. }
  1919. }
  1920. return null;
  1921. }
  1922. async function waitForChatgptSkipButton(timeout = 15000) {
  1923. const start = Date.now();
  1924. while (Date.now() - start < timeout) {
  1925. throwIfStopped();
  1926. const btn = findChatgptSkipButton();
  1927. if (btn && isVisibleElement(btn)) {
  1928. return btn;
  1929. }
  1930. await sleep(300);
  1931. }
  1932. return null;
  1933. }
  1934. async function skipChatgptOnboarding() {
  1935. log('ChatGPT 页面:正在确认是引导页还是已登录主页...');
  1936. const initialState = await waitForChatgptPostSignupState(15000);
  1937. if (initialState === 'home') {
  1938. log('ChatGPT 页面:未出现可跳过引导,已进入登录后的 ChatGPT 页面,按注册成功处理。', 'ok');
  1939. return { success: true, alreadyCompleted: true };
  1940. }
  1941. if (initialState !== 'onboarding') {
  1942. throw new Error('ChatGPT 页面:未检测到可跳过引导,也未确认进入登录后的主页。URL: ' + location.href);
  1943. }
  1944. log('ChatGPT 引导页:正在查找第一个"Skip/跳过"按钮...');
  1945. // Find first Skip button: sibling of "Next" button, with btn-ghost class
  1946. const firstSkipBtn = await waitForChatgptSkipButton(15000);
  1947. if (!firstSkipBtn) {
  1948. throw new Error('ChatGPT 引导页:未找到第一个"Skip/跳过"按钮。URL: ' + location.href);
  1949. }
  1950. await humanPause(500, 1200);
  1951. simulateClick(firstSkipBtn);
  1952. log('ChatGPT 引导页:已点击第一个"Skip/跳过"按钮,等待第二个按钮出现...');
  1953. // Wait 3 seconds for the second skip button to appear
  1954. await sleep(3000);
  1955. // Find second Skip button: sibling of "Continue" button, with btn-ghost class
  1956. const secondSkipBtn = await waitForChatgptSkipButton(5000);
  1957. if (!secondSkipBtn) {
  1958. if (isChatgptAuthenticatedHomePage()) {
  1959. log('ChatGPT 引导页:未找到第二个"Skip/跳过"按钮,但页面已进入登录后的 ChatGPT 页面。', 'ok');
  1960. } else {
  1961. log('ChatGPT 引导页:5秒内未找到第二个"Skip/跳过"按钮,判定注册已完成。', 'ok');
  1962. }
  1963. return { success: true };
  1964. }
  1965. await humanPause(500, 1200);
  1966. simulateClick(secondSkipBtn);
  1967. log('ChatGPT 引导页:已点击第二个"Skip/跳过"按钮,注册流程完成。', 'ok');
  1968. return { success: true };
  1969. }