标签 自动化注册 下的文章

直接产出 Dreamy-rain/gemini-business2api 所需 json 注册效率~60s 一个
日抛 直接每日重新注册即可

刚刚那个版本有点问题 已修复
已经生成的佬记得把 config_id 后缀的?csesidx=.* 清理掉重新导入

import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs
from datetime import datetime
import time, random, json, os, requests

# 配置
TOTAL_ACCOUNTS = 20
MAIL_API = "https://mail.chatgpt.org.uk"
MAIL_KEY = "gpt-test"
OUTPUT_DIR = "gemini_accounts"
LOGIN_URL = "https://auth.business.gemini.google/login?continueUrl=https:%2F%2Fbusiness.gemini.google%2F&wiffid=CAoSJDIwNTlhYzBjLTVlMmMtNGUxZC1hY2JkLThmOGY2ZDE0ODM1Mg" # XPath
XPATH = {
    "email_input": "/html/body/c-wiz/div/div/div[1]/div/div/div/form/div[1]/div[1]/div/span[2]/input",
    "continue_btn": "/html/body/c-wiz/div/div/div[1]/div/div/div/form/div[2]/div/button",
    "verify_btn": "/html/body/c-wiz/div/div/div[1]/div/div/div/form/div[2]/div/div[1]/span/div[1]/button",
}

NAMES = ["James Smith", "John Johnson", "Robert Williams", "Michael Brown", "William Jones",
         "David Garcia", "Mary Miller", "Patricia Davis", "Jennifer Rodriguez", "Linda Martinez"]

def log(msg, level="INFO"): print(f"[{level}] {msg}")

def create_email():
    """创建临时邮箱""" try:
        r = requests.get(f"{MAIL_API}/api/generate-email",
            headers={"X-API-Key": MAIL_KEY}, timeout=30)
        if r.status_code == 200 and r.json().get('success'):
            email = r.json()['data']['email']
            log(f"邮箱创建: {email}")
            return email
    except Exception as e:
        log(f"创建邮箱失败: {e}", "ERR")
    return None def get_code(email, timeout=30):
    """获取验证码"""
    log(f"等待验证码 (最多{timeout}s)...")
    start = time.time()
    while time.time() - start < timeout:
        try:
            r = requests.get(f"{MAIL_API}/api/emails", params={"email": email},
                headers={"X-API-Key": MAIL_KEY}, timeout=30)
            if r.status_code == 200:
                emails = r.json().get('data', {}).get('emails', [])
                if emails:
                    html = emails[0].get('html_content') or emails[0].get('content', '')
                    soup = BeautifulSoup(html, 'html.parser')
                    span = soup.find('span', class_='verification-code')
                    if span:
                        code = span.get_text().strip()
                        if len(code) == 6:
                            log(f"验证码: {code}")
                            return code
        except: pass print(f"  等待中... ({int(time.time()-start)}s)", end='\r')
        time.sleep(3)
    log("验证码超时", "ERR")
    return None def save_config(email, cookies, url):
    """保存配置"""
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    parsed = urlparse(url)
    path_parts = url.split('/')
    config_id = None for i, p in enumerate(path_parts):
        if p == 'cid' and i+1 < len(path_parts):
            config_id = path_parts[i+1]
            # 清理 config_id 结尾的 ?csesidx=xxx if config_id and '?' in config_id:
                config_id = config_id.split('?')[0]
            break

    cookie_dict = {c['name']: c for c in cookies}
    ses_cookie = cookie_dict.get('__Secure-C_SES', {})

    data = {
        "id": email,
        "csesidx": parse_qs(parsed.query).get('csesidx', [None])[0],
        "config_id": config_id,
        "secure_c_ses": ses_cookie.get('value'),
        "host_c_oses": cookie_dict.get('__Host-C_OSES', {}).get('value'),
        "expires_at": datetime.fromtimestamp(ses_cookie.get('expiry', 0) - 43200).strftime('%Y-%m-%d %H:%M:%S') if ses_cookie.get('expiry') else None
    }

    with open(f"{OUTPUT_DIR}/{email}.json", 'w') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    log(f"配置已保存: {email}.json")
    return data

def register(driver):
    """注册单个账号"""
    email = create_email()
    if not email: return None, False, None

    wait = WebDriverWait(driver, 60)

    # 1. 访问登录页
    driver.get(LOGIN_URL)
    time.sleep(5)

    # 2. 输入邮箱
    log("输入邮箱...")
    inp = wait.until(EC.visibility_of_element_located((By.XPATH, XPATH["email_input"])))
    inp.click(); time.sleep(0.3); inp.clear(); time.sleep(0.3)
    for c in email: inp.send_keys(c); time.sleep(0.05)
    log(f"邮箱: {email}, 实际值: {inp.get_attribute('value')}")
    time.sleep(1)

    # 3. 点击继续
    btn = wait.until(EC.element_to_be_clickable((By.XPATH, XPATH["continue_btn"])))
    driver.execute_script("arguments[0].click();", btn)
    log("点击继续")
    time.sleep(3)

    # 4. 获取验证码
    code = get_code(email)
    if not code: return email, False, None # 5. 输入验证码
    time.sleep(2)
    log(f"输入验证码: {code}")
    try:
        pin = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[name='pinInput']")))
        pin.click(); time.sleep(0.2)
        for c in code: pin.send_keys(c); time.sleep(0.1)
    except:
        try:
            span = driver.find_element(By.CSS_SELECTOR, "span[data-index='0']")
            span.click(); time.sleep(0.3)
            driver.switch_to.active_element.send_keys(code)
        except Exception as e:
            log(f"验证码输入失败: {e}", "ERR")
            return email, False, None # 6. 点击验证
    time.sleep(1)
    try:
        vbtn = driver.find_element(By.XPATH, XPATH["verify_btn"])
        driver.execute_script("arguments[0].click();", vbtn)
    except:
        for btn in driver.find_elements(By.TAG_NAME, "button"):
            if '验证' in btn.text: driver.execute_script("arguments[0].click();", btn); break
    log("点击验证")
    time.sleep(5)

    # 7. 输入姓名 try:
        name_inp = WebDriverWait(driver, 30).until(EC.visibility_of_element_located(
            (By.CSS_SELECTOR, "input[formcontrolname='fullName'], input[placeholder='全名'], input#mat-input-0")))
        name = random.choice(NAMES)
        name_inp.clear(); time.sleep(0.3)
        for c in name: name_inp.send_keys(c); time.sleep(0.03)
        log(f"姓名: {name}")
        from selenium.webdriver.common.keys import Keys
        name_inp.send_keys(Keys.ENTER)
    except Exception as e:
        log(f"姓名输入异常: {e}", "WARN")

    # 8. 等待进入工作台
    log("等待工作台...")
    time.sleep(6)
    for _ in range(30):
        if 'business.gemini.google' in driver.current_url and 'auth' not in driver.current_url:
            break
        time.sleep(2)
    time.sleep(3)

    # 9. 保存配置
    config = save_config(email, driver.get_cookies(), driver.current_url)
    log(f"注册成功: {email}")
    return email, True, config

def main():
    print(f"\n{'='*50}\nGemini Business 批量注册 - 共 {TOTAL_ACCOUNTS} 个\n{'='*50}\n")

    driver = uc.Chrome(options=uc.ChromeOptions(), use_subprocess=True)
    success, fail, accounts = 0, 0, []

    for i in range(TOTAL_ACCOUNTS):
        print(f"\n{'#'*40}\n注册 {i+1}/{TOTAL_ACCOUNTS}\n{'#'*40}\n")

        try:
            driver.current_url  # 检查driver是否有效 except:
            driver = uc.Chrome(options=uc.ChromeOptions(), use_subprocess=True)

        try:
            email, ok, cfg = register(driver)
            if ok: success += 1; accounts.append((email, cfg))
            else: fail += 1 except Exception as e:
            log(f"异常: {e}", "ERR"); fail += 1 try: driver.quit()
            except: pass
            driver = uc.Chrome(options=uc.ChromeOptions(), use_subprocess=True)

        print(f"\n进度: {i+1}/{TOTAL_ACCOUNTS} | 成功: {success} | 失败: {fail}")

        if i < TOTAL_ACCOUNTS - 1:
            try: driver.delete_all_cookies()
            except: pass
            time.sleep(random.randint(3, 5))

    try: driver.quit()
    except: pass print(f"\n{'='*50}\n完成! 成功: {success}, 失败: {fail}\n配置保存在: {OUTPUT_DIR}/\n{'='*50}")

if __name__ == "__main__":
    main()


感谢佬友的临时邮箱 gptmail 也感谢谷大善人不限域名大赦天下

特别感谢 2api 作者 大家也别忘了给他的帖子和仓库 star 一下~


📌 转载信息
原作者:
SnapSheep
转载时间:
2026/1/12 10:33:02

Gemini bussiness 自动刷新逻辑,接入 yescapture 打码服务,做到了基本 100% 的成功率

【回顾】 在之前的自动化注册或者刷新中会出现验证码发送错误的情况,原因在于获取的谷歌验证分数太低导致发送接口错误

【探索】通过抓包发现,以下接口就是发送邮件的接口

https://accountverification.business.gemini.google/_/IdentityPlatformFrontendUI/data/batchexecute?rpcids=IjXaFf&source-path=%2Fv1%2Fverify-oob-code&bl=boq_cloud-identity-identityplatform-frontend_20251210.10_p1&hl=en&rt=c

请求体为
f.req:[[["IjXaFf",,null,"generic"]]]

里面的 0cAFcWe 就是开头的验证

因此,只需要接入打码服务即可完成再次发送,测试结果为成功率基本 100%

完整 nodejs 代码如下:

 const fs = require('fs');
const os = require('os');
const path = require('path');
const axios = require('axios');
const express = require('express');
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
const { ImapFlow } = require('imapflow');
const { simpleParser } = require('mailparser');

puppeteer.use(StealthPlugin());

const app = express();
const port = 3000;

// =============================== // 配置项 // =============================== const WEBSITE_KEY = '6Ld8dCcrAAAAAFVbDMVZy8aNRwCjakBVaDEdRUH8';
const WEBSITE_URL = 'https://accountverification.business.gemini.google';

const sleep = (ms) => new Promise(r => setTimeout(r, ms));

function createTempUserDataDir() {
  return fs.mkdtempSync(path.join(os.tmpdir(), 'pptr-profile-'));
}

/**
* 邮件获取类
*/
class GeminiFetcher { constructor(email, clientId, refreshToken) { this.email = email; this.clientId = clientId; this.refreshToken = refreshToken; } async getAccessToken() { const params = new URLSearchParams({ client_id: this.clientId, grant_type: 'refresh_token', refresh_token: this.refreshToken }); const res = await axios.post('https://login.microsoftonline.com/consumers/oauth2/v2.0/token', params.toString()); return res.data.access_token; } async tryFetchOnce() { const token = await this.getAccessToken(); const client = new ImapFlow({ host: 'outlook.office365.com', port: 993, secure: true, auth: { user: this.email, accessToken: token }, logger: false }); await client.connect(); let code = null; try { for (const mailbox of ['INBOX', 'Junk']) { let lock; try { lock = await client.getMailboxLock(mailbox); const messages = await client.search({ all: true }); const lastUids = messages.slice(-5).reverse(); const tenMinutesAgo = Date.now() - 10 * 60 * 1000; for (let uid of lastUids) { let msg = await client.fetchOne(uid, { source: true }); let parsed = await simpleParser(msg.source); if (parsed.date.getTime() > tenMinutesAgo && parsed.subject && (parsed.subject.includes('Gemini') || parsed.subject.includes('Google'))) { const content = parsed.text + (parsed.html || ""); const match = content.match(/[A-Z0-9]{6}/); if (match) { code = match[0]; break; } } } } catch (e) { } finally { if (lock) lock.release(); } if (code) break; } } finally { await client.logout(); } return code; } } async function startPollingForCode(email, clientId, refreshToken) { const fetcher = new GeminiFetcher(email, clientId, refreshToken); for (let i = 1; i <= 10; i++) { try { console.log(`[${email}] 尝试获取邮件验证码 (${i}/10)...`); const code = await fetcher.tryFetchOnce(); if (code) { console.log(`[${email}] 成功获取到验证码: ${code}`); return code; } } catch (err) { console.error(`[${email}] 获取验证码报错: ${err.message}`); } await sleep(4000); } return null; } async function getCaptchaToken(apiKey) { try { console.log('🤖 正在向 YesCaptcha 请求人机识别 Token...'); const createResp = await axios.post('https://api.yescaptcha.com/createTask', { clientKey: apiKey, task: { websiteURL: WEBSITE_URL, websiteKey: WEBSITE_KEY, pageAction: 'verify_oob_code', type: 'RecaptchaV3TaskProxylessM1' } }); const taskId = createResp.data.taskId; for (let i = 0; i < 20; i++) { await sleep(3000); const resultResp = await axios.post('https://api.yescaptcha.com/getTaskResult', { clientKey: apiKey, taskId: taskId }); if (resultResp.data.status === 'ready') { console.log('🤖 YesCaptcha Token 获取成功'); return resultResp.data.solution.gRecaptchaResponse; } } } catch (error) { console.error(`❌ YesCaptcha 错误: ${error.message}`); return null; } } function patchPayload(rawBody, newToken) { const params = new URLSearchParams(rawBody); let fReq = params.get('f.req'); if (!fReq) return rawBody; const tokenRegex = /0[3c]AFc[a-zA-Z0-9_\-]{50,}/g; if (tokenRegex.test(fReq)) { params.set('f.req', fReq.replace(tokenRegex, newToken)); } return params.toString(); } // =============================== // 核心任务逻辑 // =============================== async function runLoginTask(accountData, apiKey) { const parts = accountData.split('----'); const [email, password, clientId, refreshToken] = parts; const userDataDir = createTempUserDataDir(); console.log(`🚀 [任务开始] 账号: ${email}`); let resolveCodeSent; const codeSentBarrier = new Promise((resolve) => { resolveCodeSent = resolve; }); let resolveAuthBarrier; const authBarrier = new Promise((resolve) => { resolveAuthBarrier = resolve; }); console.log('🌐 正在启动浏览器...'); const browser = await puppeteer.launch({ headless: "new", userDataDir, args: ['--no-sandbox', '--disable-setuid-sandbox', '--window-size=1280,800'] }); try { const page = await browser.newPage(); await page.setRequestInterception(true); page.on('request', req => { if (['image', 'media', 'font'].includes(req.resourceType())) return req.abort().catch(() => {}); req.continue().catch(() => {}); }); page.on('response', async res => { const url = res.url(); if (url.includes('batchexecute')) { try { const text = await res.text(); // 监控验证码发送状态 if (text.includes('LookupVerifiedEmail') || text.includes('SendVerificationCode')) { console.log('✅ [网络监控] 监听到 SendVerificationCode 响应,服务器已发信!'); resolveCodeSent(); } // 监控验证码报错 if (text.includes('CAPTCHA_CHECK_FAILED')) { console.log('⚠️ [网络监控] 检测到人机验证码拦截,准备打码补丁...'); const newToken = await getCaptchaToken(apiKey); if (newToken) { const originalRequest = res.request(); const newPostData = patchPayload(originalRequest.postData(), newToken); console.log('🔄 [补丁] 正在重发带 Token 的 Payload...'); await page.evaluate(async (u, h, b) => { await fetch(u, { method: 'POST', headers: h, body: b }); }, url, originalRequest.headers(), newPostData); resolveAuthBarrier(); } } else if (text.includes('inner_api_status')) { resolveAuthBarrier(); } } catch (e) { } } }); console.log('🍪 正在设置初始 XSRF Cookie...'); await page.goto('https://auth.business.gemini.google/', { waitUntil: 'domcontentloaded' }); await page.setCookie( { name: '__Host-AP_SignInXsrf', value: 'KdLRzKwwBTD5wo8nUollAbY6cW0', domain: 'auth.business.gemini.google', path: '/', secure: true }, { name: '_GRECAPTCHA', value: '09ABCL...', domain: '.google.com', path: '/', secure: true } ); const targetUrl = `https://auth.business.gemini.google/login/email?continueUrl=https%3A%2F%2Fbusiness.gemini.google%2F&loginHint=${encodeURIComponent(email)}&xsrfToken=KdLRzKwwBTD5wo8nUollAbY6cW0`; console.log('🔗 正在加载登录页面...'); await page.goto(targetUrl, { waitUntil: 'domcontentloaded' }); console.log('🖱️ 正在点击 [通过电子邮件发送验证码] 按钮...'); await page.waitForSelector('#sign-in-with-email', { visible: true }); await page.click('#sign-in-with-email'); console.log('🔎 等待验证码输入框出现...'); const inputSelector = 'input[jsname="ovqh0b"]'; await page.waitForSelector(inputSelector, { timeout: 30000 }); console.log('⏳ [关键等待] 正在等待发信确认信号 (由网络响应触发)...'); const waitStart = Date.now(); await Promise.race([codeSentBarrier, sleep(12000)]); console.log(`⏱️ 等待结束,耗时: ${Date.now() - waitStart}ms`); console.log('📫 开始爬取邮箱验证码...'); const code = await startPollingForCode(email, clientId, refreshToken); if (!code) throw new Error("获取验证码超时"); console.log('⌨️ 正在输入验证码并提交...'); await page.type(inputSelector, code, { delay: 100 }); await page.click('button[jsname="XooR8e"]'); console.log('🔄 等待登录跳转...'); await sleep(4000); if (page.url().includes('/admin/create')) { console.log('📄 进入创建页面,检测是否有 [同意] 按钮...'); const btn = await page.waitForSelector('button.agree-button', { visible: true, timeout: 5000 }).catch(() => null); if (btn) { console.log('🖱️ 点击同意按钮'); await btn.click(); await sleep(2000); } } console.log('🍪 正在通过 CDP 协议提取全量 Cookie...'); let hostCoses = '', secureCSes = ''; for (let i = 0; i < 15; i++) { const client = await page.target().createCDPSession(); const { cookies } = await client.send('Network.getAllCookies'); await client.detach(); for (const c of cookies) { if (c.name === '__Host-C_OSES') hostCoses = c.value; if (c.name === '__Secure-C_SES') secureCSes = c.value; } if (hostCoses && secureCSes) { console.log('✨ 核心 Cookie 提取完毕'); break; } console.log(`📭 第 ${i+1} 次提取 Cookie 未果,继续轮询...`); await sleep(1000); if (i === 5) { console.log('🔄 提取超时,尝试跳转业务主域名促活 Cookie...'); await page.goto('https://business.gemini.google/', { waitUntil: 'networkidle2' }).catch(() => {}); } } if (!hostCoses || !secureCSes) throw new Error('Cookie 提取失败'); console.log('🏁 [任务成功] 正在返回结果'); return `${email}|${password}|${hostCoses.trim()}::${secureCSes.trim()}`; } finally { console.log('🧹 正在关闭浏览器并清理临时文件...'); await browser.close(); try { fs.rmSync(userDataDir, { recursive: true, force: true }); } catch (e) {} } } app.get('/login', async (req, res) => { const { data, apikey } = req.query; if (!data || !apikey) return res.status(400).send('Missing params'); try { const result = await runLoginTask(data, apikey); res.send(result); } catch (err) { console.error(`❌ 接口报错: ${err.message}`); res.status(500).send(`Error: ${err.message}`); } }); app.listen(port, () => { console.log(); console.log(`🚀 服务运行中: http://localhost:${port}`); console.log(`📝 请求示例: /login?data=email----pass----id----token&apikey=xxx`); console.log(); });

运行成功后请求示例为:
http://localhost:3000/login?data=CharlesHoward4117@outlook.com----rrom1652910----dbc8e03a-b00c-46bd-ae65-b683e7707cb0----M.C539_BL2.0.U.-Cn78r6PhJ0VI48KtRppemAxUI038pVKjd9Kyu*lxTsFW9cyZqou7zcWsKmg0DdlxCURrppr3paaCrZHMIY1gzBcD4p*p*TQHz4DqDF0xeUTOtkTlpy!B6leXglSy3O1Uj9hDUkq3f!75ha4A0VrC7agSXDzUaV!tPIJ7AA6fgdKeehLjzhNaHr5XqvTM39Gr1OR9H8VnYBB!K6yGDAhWWsYd5blEfhqVoAzG3TBDTcdrho3fwU2uR8V8oVtJfQ*aGyw9XwCj*gIRq1SdfWR5h!PSZ4TuFSJVqeLB7qbIOHLfWPtVkz*ya6jxMX4DqJASLQIIILno1lJznm1VAeQJPze!REpnD9L9F9t!dwRwpmd1235SbqnYAEG5rFXKSOqikRjSYSWeCVmZYBkWSWBLEuQ$&apikey=c169a2dbd972acac69b4f30c52c060bfbbe0854f84831

其中 data 就是邮箱的基本信息,这里只适配了微软邮箱
apikey 就是 yes 的 apikey

默认如果浏览器可以成功发送则不调用 yes 打码服务,返回示例

CharlesHoward4117@outlook.com|rrom1652910|COS.AW82PoFnmTPemeKaOLiqi59wSPBs5Q6mSkgqGsk2OwOP0c_vBgAo4L3k8IdN-La_tMrJbjbatQy9Uw6QllD2VL0xdhdbG8Ks2tlCGGEfxZgj3FhTP2fNSeEfk3ed1PL_l6oTfMiLL5ivKwKCYE5sbuI::CSE.AdwtfTBBmOWOWWkad3G32S_ut5NlmYWQhJCRohzHwevu9ZpYyKrRHpviThBTJNh8_KdlBLAUbSQT5zD6RGoggxO8air-J0l9qO_XtmbdLhXYDOCmMdNgDFq40G1HmpgeGfUtXEVB-cT2lf33J9xSx_F0w9ZmWrrI96KJk8ijQ_qc5T5nt3grRfI5B9YpHHOww_Uqo14z0Yg1899rHDdNpgg9y_X9xK3nDn8C3lYKerslcKak12VC_Rxq9JJDYNsysUjhfNmyt-tyU9xLaJV_vR_FG7nnkO7bmRL664yEpAzRD0dB9ZnxXrCb45q1Q7HRs3jjxoId1DVYw2aSbU5URDDY-q5bCDbHModdg36rRuICHmxQQRsz39YivNknIDe7kvOnubDYU1M9wmhX7bsLkKawILuj0jwsqNRb0jh-phY3D8DZhydEHROjjba99MAsIvkH8ZytY_x3Aw

COS 与 CSE 的 cookie 都有返回,一个账户大概 30s 左右,可并发,一分钟基本可以刷新或者注册 40 个账户(并发 20)

欢迎更多开发者去完善自动化注册和刷新的逻辑…


📌 转载信息
转载时间:
2026/1/3 12:07:27

// ==UserScript==
// @name         Grok/X.ai 自动化注册机 (集成自动清理与循环版)
// @namespace    http://tampermonkey.net/
// @version      5.0
// @description  全自动流程:注册 -> 提取Token -> 清理Cookie -> 循环重启
// @author       Bytebender
// @match        *://*/*
// @match        https://x.ai/*
// @match        https://www.x.ai/*
// @match        https://accounts.x.ai/*
// @match        https://grok.com/*
// @match        https://www.grok.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// @grant        GM_notification
// @grant        GM_xmlhttpRequest
// @grant        GM_setClipboard
// @grant        GM_cookie
// @connect      mail.chatgpt.org.uk
// @connect      100.64.0.101
// @connect      api.x.ai
// @connect      x.ai
// @connect      grok.com
// @connect      www.grok.com
// @connect      accounts.x.ai
// ==/UserScript==

(function() {
    'use strict';

    // ========================================================
    // 1. 随机数据生成工具
    // ========================================================

    // 生成随机姓名 (首字母大写)
    function getRandomName() {
        const chars = 'abcdefghijklmnopqrstuvwxyz';
        const len = Math.floor(Math.random() * 5) + 4; // 长度 4-8
        let result = '';
        for (let i = 0; i < len; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result.charAt(0).toUpperCase() + result.slice(1);
    }

    // 生成强密码 (12位,包含大小写+数字+特殊符号)
    function getRandomPassword() {
        const lower = "abcdefghijklmnopqrstuvwxyz";
        const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const nums = "0123456789";
        const symbols = "!@#$%^&*";

        // 1. 确保每种字符至少有一个
        let pass = "";
        pass += lower[Math.floor(Math.random() * lower.length)];
        pass += upper[Math.floor(Math.random() * upper.length)];
        pass += nums[Math.floor(Math.random() * nums.length)];
        pass += symbols[Math.floor(Math.random() * symbols.length)];

        // 2. 补足剩余长度
        const allChars = lower + upper + nums + symbols;
        for (let i = 0; i < 8; i++) {
            pass += allChars[Math.floor(Math.random() * allChars.length)];
        }

        // 3. 打乱顺序 (洗牌)
        return pass.split('').sort(() => 0.5 - Math.random()).join('');
    }

    // ========================================================
    // 2. 任务编排配置
    // ========================================================
    const actions = [
        // --- 阶段一:Grok 首页跳转 ---
        {
            "step_name": "1. 点击 Grok 首页入口",
            "type": "click",
            "selector": "html > body > div:nth-of-type(2) > div > div > div > main > div > div > div:nth-of-type(3) > div:nth-of-type(2) > a:nth-of-type(2)",
            "url_keyword": "grok.com"
        },
        // --- 阶段二:进入注册页 (X.ai) ---
        {
            "step_name": "2. 点击 X.ai 注册/登录按钮",
            "type": "click",
            "selector": "html > body > div:nth-of-type(2) > div > div > div:nth-of-type(2) > div > div:nth-of-type(2) > button",
            "url_keyword": "accounts.x.ai"
        },
        // --- 阶段三:自动化邮箱 ---
        {
            "step_name": "3. 自动申请并填写临时邮箱",
            "type": "get_email",
            "selector": "html > body > div:nth-of-type(2) > div > div > div:nth-of-type(2) > div > form > div > div > input",
        },
        {
            "step_name": "4. 点击下一步 (提交邮箱)",
            "type": "click",
            "selector": "html > body > div:nth-of-type(2) > div > div > div:nth-of-type(2) > div > form > div:nth-of-type(2) > button"
        },
        // --- 阶段四:验证码 ---
        {
            "step_name": "5. 等待邮件验证码并自动填写",
            "type": "fill_code",
            "selector": "input[name='code']"
        },
        // --- 阶段五:填写个人信息 (全随机) ---
        {
            "step_name": "6. 填写名 (First Name)",
            "type": "input",
            "selector": "input[name='givenName']",
            "value": "__RANDOM__"
        },
        {
            "step_name": "7. 填写姓 (Last Name)",
            "type": "input",
            "selector": "input[name='familyName']",
            "value": "__RANDOM__"
        },
        {
            "step_name": "8. 填写密码 (强密码)",
            "type": "input",
            "selector": "input[name='password']",
            "value": "__RANDOM_PASS__"
        },
        // --- 阶段六:提交 ---
        {
            "step_name": "9. 点击最终提交",
            "type": "click",
            "selector": "button[type='submit']"
        },
        // --- 阶段七:提取 Token ---
        {
            "step_name": "10. 检查跳转并上传 Token",
            "type": "wait_url_and_upload",
            "target_url": "grok.com"
        },
        // --- 阶段八:清理环境并循环 ---
        {
            "step_name": "11. 清理 Cookie 并重启循环",
            "type": "clean_and_restart",
            "clean_targets": [
                "https://x.ai/",
                "https://www.x.ai/",
                "https://accounts.x.ai/",
                "https://grok.com/",
                "https://www.grok.com/"
            ]
        }
    ];

    // ========================================================
    // 3. 核心功能类 (邮箱/网络/Cookie)
    // ========================================================

    // 3.1 网络请求封装
    function gmFetch(url, options) {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                url: url,
                method: options.method || 'GET',
                headers: options.headers || {},
                data: options.body || null,
                onload: (response) => {
                    if (response.status >= 200 && response.status < 300) {
                        try { resolve(JSON.parse(response.responseText)); }
                        catch (e) { resolve(response.responseText); }
                    } else { reject(new Error(`HTTP Error: ${response.status}`)); }
                },
                onerror: () => reject(new Error('Network Error')),
                ontimeout: () => reject(new Error('Timeout'))
            });
        });
    }

    // 3.2 临时邮箱客户端
    class TempMailClient {
        constructor() {
            this.baseUrl = "https://mail.chatgpt.org.uk/api";
            this.headers = {
                "User-Agent": "Mozilla/5.0",
                "Origin": "https://mail.chatgpt.org.uk",
                "Referer": "https://mail.chatgpt.org.uk/"
            };
        }
        async getEmail() {
            const result = await gmFetch(`${this.baseUrl}/generate-email`, {
                method: "GET",
                headers: { ...this.headers, "content-type": "application/json" }
            });
            if (result && result.success && result.data?.email) return result.data.email;
            throw new Error("邮箱API返回异常");
        }
        async fetchMessages(email) {
            const url = `${this.baseUrl}/emails?email=${encodeURIComponent(email)}`;
            const result = await gmFetch(url, {
                method: "GET",
                headers: { ...this.headers, "cache-control": "no-cache" }
            });
            return (result.success && result.data?.emails) ? result.data.emails : [];
        }
        async waitForCode(email, timeoutSec = 120) {
            console.log(`[Mail] 开始监听 ${email} ...`);
            const startTime = Date.now();
            const codeRegex = /\b[A-Z0-9]{3}-[A-Z0-9]{3}\b|\b\d{6}\b/;
            return new Promise((resolve, reject) => {
                const timer = setInterval(async () => {
                    if (Date.now() - startTime > timeoutSec * 1000) {
                        clearInterval(timer);
                        reject(new Error("等待验证码超时"));
                    }
                    try {
                        const msgs = await this.fetchMessages(email);
                        if (msgs.length > 0) {
                            for (const msg of msgs) {
                                const content = (msg.subject || "") + " " + (msg.html_content || "");
                                const match = content.match(codeRegex);
                                if (match) {
                                    clearInterval(timer);
                                    resolve(match[0]);
                                    return;
                                }
                            }
                        }
                    } catch(e) { console.warn("Polling error:", e); }
                }, 3000);
            });
        }
    }

    // 3.3 Token 上传逻辑
    async function extractAndUploadToken() {
        return new Promise((resolve, reject) => {
            GM_cookie.list({ name: "sso" }, (cookies, error) => {
                if (error || !cookies || cookies.length === 0) {
                    return reject(new Error("SSO Cookie missing"));
                }
                const ssoToken = cookies[0].value;
                console.log("获取到 Token:", ssoToken.substring(0, 10) + "...");

                GM_xmlhttpRequest({
                    url: "http://xxx/api/tokens/add",
                    method: "POST",
                    headers: {
                        "content-type": "application/json",
                        "authorization": "Bearer xxxxx"
                    },
                    data: JSON.stringify({ tokens: [ssoToken], token_type: "sso" }),
                    onload: (response) => {
                        if (response.status >= 200 && response.status < 300) {
                            console.log("Token 上传成功!");
                            resolve();
                        } else {
                            reject(new Error("Upload failed: " + response.responseText));
                        }
                    },
                    onerror: (err) => reject(err)
                });
            });
        });
    }

    // 3.4 Cookie 清理逻辑
    function executeCleanCookies(targetUrls) {
        return new Promise((resolve) => {
            if (!targetUrls || targetUrls.length === 0) return resolve();
            let completed = 0;
            targetUrls.forEach(url => {
                GM_cookie.list({ url: url }, function(cookies, error) {
                    if (cookies && cookies.length > 0) {
                        cookies.forEach(c => {
                            GM_cookie.delete({ name: c.name, url: url }, () => {});
                        });
                    }
                    completed++;
                    if (completed === targetUrls.length) {
                        setTimeout(resolve, 800); // 缓冲
                    }
                });
            });
        });
    }

    // 3.5 Native 输入模拟 (绕过 React/Vue 绑定)
    function setNativeValue(element, value) {
        const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
        const prototype = Object.getPrototypeOf(element);
        const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
        if (valueSetter && valueSetter !== prototypeValueSetter) {
            prototypeValueSetter.call(element, value);
        } else {
            valueSetter.call(element, value);
        }
        element.dispatchEvent(new Event('input', { bubbles: true }));
    }

    // 3.6 元素等待
    const waitForElement = (selector, timeout = 10000) => {
        return new Promise((resolve, reject) => {
            const el = document.querySelector(selector);
            if (el) return resolve(el);
            const observer = new MutationObserver(() => {
                const el = document.querySelector(selector);
                if (el) { observer.disconnect(); resolve(el); }
            });
            observer.observe(document.body, { childList: true, subtree: true });
            setTimeout(() => { observer.disconnect(); reject(new Error('元素超时: ' + selector)); }, timeout);
        });
    };

    // ========================================================
    // 4. 自动化执行引擎
    // ========================================================
    const mailClient = new TempMailClient();
    let isRunning = GM_getValue('script_is_running', false);
    let currentIndex = GM_getValue('script_step_index', 0);

    console.log(`🚀 [注册机状态] Running: ${isRunning} | Step: ${currentIndex}`);

    GM_registerMenuCommand(`▶️ 启动/继续`, () => {
        GM_setValue('script_is_running', true);
        isRunning = true;
        runCurrentStep();
    });

    GM_registerMenuCommand("🔄 强制重置", () => {
        GM_setValue('script_step_index', 0);
        GM_setValue('script_is_running', false);
        GM_setValue('current_temp_email', '');
        location.reload();
    });

    async function runCurrentStep() {
        if (!GM_getValue('script_is_running', false)) return;

        // 异常保护:索引越界重置
        if (currentIndex >= actions.length) {
            GM_setValue('script_step_index', 0);
            return location.reload();
        }

        const action = actions[currentIndex];
        console.log(`[Step ${currentIndex + 1}] ${action.step_name} (${action.type})`);

        // URL 检查 (如果不在目标域名,等待跳转)
        if (action.url_keyword && !location.href.includes(action.url_keyword)) {
            console.log(`等待跳转到 ${action.url_keyword}...`);
            return setTimeout(runCurrentStep, 2000);
        }

        try {
            await new Promise(r => setTimeout(r, 3000)); // 基础缓冲
            let el = null;
            if (action.selector) el = await waitForElement(action.selector);

            // --- 动作分发 ---
            if (action.type === 'get_email') {
                const email = await mailClient.getEmail();
                console.log("获取邮箱:", email);
                GM_setValue('current_temp_email', email);
                GM_setClipboard(email);

                el.click(); el.focus();
                setNativeValue(el, email);
                el.dispatchEvent(new Event('change', { bubbles: true }));
                el.blur();
            }
            else if (action.type === 'fill_code') {
                const email = GM_getValue('current_temp_email');
                const rawCode = await mailClient.waitForCode(email);
                const code = rawCode.replace(/-/g, ''); // 清洗连字符
                console.log('填入验证码:', code);

                el.scrollIntoView({block: "center"});
                el.click(); el.focus();
                const nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
                nativeSetter.call(el, code);
                el.dispatchEvent(new Event('input', { bubbles: true }));
                el.dispatchEvent(new Event('change', { bubbles: true }));
                await new Promise(r => setTimeout(r, 500));
                el.blur();
            }
            else if (action.type === 'input') {
                el.focus();
                let val = action.value;

                // 处理随机变量
                if (val === '__RANDOM__') val = getRandomName();
                if (val === '__RANDOM_PASS__') val = getRandomPassword();

                console.log(`[Input] 填写值: ${val}`);
                setNativeValue(el, val);
                el.blur();
            }
            else if (action.type === 'wait_url_and_upload') {
                if (!location.href.includes(action.target_url)) {
                    return setTimeout(runCurrentStep, 1500); // URL不对,继续等待
                }

                // 尝试多次上传,防止 Cookie 未即时写入
                let retry = 0;
                while (retry < 5) {
                    try {
                        await extractAndUploadToken();
                        GM_notification({ text: 'Token 上传成功!准备清理...', title: '成功' });
                        break;
                    } catch (e) {
                        console.warn("Token提取失败,重试中...", e);
                        await new Promise(r => setTimeout(r, 2000));
                        retry++;
                    }
                }
                // 继续下一步
            }
            else if (action.type === 'clean_and_restart') {
                GM_notification({ text: '清理 Cookie 并重启循环...', title: '系统维护' });
                await executeCleanCookies(action.clean_targets);

                GM_setValue('script_step_index', 0);
                GM_setValue('current_temp_email', '');

                console.log(">>> 循环重置完成,3秒后刷新");
                setTimeout(() => {
                    window.location.href = "https://grok.com/";
                }, 3000);
                return; // 结束本次执行栈
            }
            else if (action.type === 'click') {
                el.click();
            }

            // --- 步进逻辑 ---
            currentIndex++;
            GM_setValue('script_step_index', currentIndex);
            setTimeout(runCurrentStep, 1500);

        } catch (e) {
            console.error("执行出错:", e);
            // 遇到严重错误可以考虑刷新页面重试
            // setTimeout(() => location.reload(), 5000);
        }
    }

    // 启动检测
    function tryStart() {
        if (isRunning) {
            setTimeout(runCurrentStep, 1500);
        }
    }

    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        tryStart();
    } else {
        window.addEventListener('load', tryStart);
    }

})();

修改 extractAndUploadToken 填入自己的 Grok2api 地址和凭证

开启无痕窗口打开 Grok,接着启动脚本即可

会自动生成邮箱、填写注册信息和验证码

IP 不好 CF 验证不会自动过,需要手动继续和点击下一步

IP 好就全自动了啦

循环注册 w