signup-page.js 78 KB

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