signup-page.js 73 KB

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