signup-page.js 68 KB

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