signup-page.js 76 KB

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