signup-page.js 73 KB

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