signup-page.js 74 KB

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