signup-page.js 72 KB

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