addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
addEventListener('scheduled', event => {
event.waitUntil(handleScheduled(event.scheduledTime))
async function handleRequest(request) {
const url = new URL(request.url)
if (url.pathname === '/login' && request.method === 'POST') {
const formData = await request.formData()
const password = formData.get('password')
if (password === PASSWORD) {
const response = new Response(JSON.stringify({ success: true }), {
headers: { 'Content-Type': 'application/json' }
response.headers.set('Set-Cookie', `auth=${PASSWORD}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=86400`)
return new Response(JSON.stringify({ success: false }), {
headers: { 'Content-Type': 'application/json' }
} else if (url.pathname === '/run' && request.method === 'POST') {
if (!isAuthenticated(request)) {
return new Response('Unauthorized', { status: 401 })
await handleScheduled(new Date().toISOString())
const results = await CRON_RESULTS.get('lastResults', 'json')
return new Response(JSON.stringify(results), {
headers: { 'Content-Type': 'application/json' }
} else if (url.pathname === '/results' && request.method === 'GET') {
if (!isAuthenticated(request)) {
return new Response(JSON.stringify({ authenticated: false }), {
headers: { 'Content-Type': 'application/json' }
const results = await CRON_RESULTS.get('lastResults', 'json')
return new Response(JSON.stringify({ authenticated: true, results: results || [] }), {
headers: { 'Content-Type': 'application/json' }
} else if (url.pathname === '/check-auth' && request.method === 'GET') {
return new Response(JSON.stringify({ authenticated: isAuthenticated(request) }), {
headers: { 'Content-Type': 'application/json' }
return new Response(getHtmlContent(), {
headers: { 'Content-Type': 'text/html' },
function isAuthenticated(request) {
const cookies = request.headers.get('Cookie')
const authCookie = cookies.split(';').find(c => c.trim().startsWith('auth='))
const authValue = authCookie.split('=')[1]
return authValue === PASSWORD
function getHtmlContent() {
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Worker Control Panel</title>
font-family: Arial, sans-serif;
background-color: #f0f0f0;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
background-color: #4CAF50;
border-collapse: collapse;
background-color: #f2f2f2;
<h1>Worker Control Panel</h1>
<input type="password" id="password" placeholder="Enter password">
<button onclick="login()">Login</button>
<button onclick="runScript()">Run Script</button>
<table id="resultsTable">
function showLoginForm() {
document.getElementById('loginForm').style.display = 'block';
document.getElementById('dashboard').style.display = 'none';
function showDashboard() {
document.getElementById('loginForm').style.display = 'none';
document.getElementById('dashboard').style.display = 'block';
async function checkAuth() {
const response = await fetch('/check-auth');
const data = await response.json();
if (data.authenticated) {
password = document.getElementById('password').value;
const formData = new FormData();
formData.append('password', password);
const response = await fetch('/login', {
const result = await response.json();
alert('Incorrect password');
async function runScript() {
const statusDiv = document.getElementById('status');
statusDiv.textContent = 'Executing script...';
const response = await fetch('/run', { method: 'POST' });
const results = await response.json();
statusDiv.textContent = 'Script executed successfully!';
} else if (response.status === 401) {
statusDiv.textContent = 'Unauthorized. Please login again.';
statusDiv.textContent = 'Error executing script.';
statusDiv.textContent = 'Error: ' + error.message;
async function fetchResults() {
const response = await fetch('/results');
const data = await response.json();
if (data.authenticated) {
displayResults(data.results);
console.error('Failed to fetch results');
console.error('Error fetching results:', error);
function displayResults(results) {
const tbody = document.querySelector('#resultsTable tbody');
results.forEach(result => {
result.cronResults.forEach((cronResult, index) => {
const row = tbody.insertRow();
row.insertCell(0).textContent = result.username;
row.insertCell(1).textContent = result.type;
row.insertCell(0).textContent = '';
row.insertCell(1).textContent = '';
row.insertCell(2).textContent = cronResult.success ? 'Success' : 'Failed';
row.insertCell(3).textContent = cronResult.message;
row.insertCell(4).textContent = new Date(result.lastRun).toLocaleString();
document.addEventListener('DOMContentLoaded', checkAuth);
async function handleScheduled(scheduledTime) {
const accountsData = JSON.parse(ACCOUNTS_JSON);
const accounts = accountsData.accounts;
for (const account of accounts) {
const result = await loginAccount(account);
await delay(Math.floor(Math.random() * 8000) + 1000);
await CRON_RESULTS.put('lastResults', JSON.stringify(results));
function generateRandomUserAgent() {
const browsers = ['Chrome', 'Firefox', 'Safari', 'Edge', 'Opera'];
const browser = browsers[Math.floor(Math.random() * browsers.length)];
const version = Math.floor(Math.random() * 100) + 1;
const os = ['Windows NT 10.0', 'Macintosh', 'X11'];
const selectedOS = os[Math.floor(Math.random() * os.length)];
const osVersion = selectedOS === 'X11' ? 'Linux x86_64' : selectedOS === 'Macintosh' ? 'Intel Mac OS X 10_15_7' : 'Win64; x64';
return `Mozilla/5.0 (${selectedOS}; ${osVersion}) AppleWebKit/537.36 (KHTML, like Gecko) ${browser}/${version}.0.0.0 Safari/537.36`;
async function loginAccount(account) {
const { username, password, panelnum, type, cronCommands } = account
let baseUrl = type === 'ct8'
: `https://panel${panelnum}.serv00.com`
let loginUrl = `${baseUrl}/login/?next=/cron/`
const userAgent = generateRandomUserAgent();
const response = await fetch(loginUrl, {
const pageContent = await response.text()
const csrfMatch = pageContent.match(/name="csrfmiddlewaretoken" value="([^"]*)"/)
const csrfToken = csrfMatch ? csrfMatch[1] : null
throw new Error('CSRF token not found')
const initialCookies = response.headers.get('set-cookie') || ''
const formData = new URLSearchParams({
'csrfmiddlewaretoken': csrfToken,
const loginResponse = await fetch(loginUrl, {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': initialCookies,
body: formData.toString(),
if (loginResponse.status === 302 && loginResponse.headers.get('location') === '/cron/') {
const loginCookies = loginResponse.headers.get('set-cookie') || ''
const allCookies = combineCookies(initialCookies, loginCookies)
const cronListUrl = `${baseUrl}/cron/`
const cronListResponse = await fetch(cronListUrl, {
const cronListContent = await cronListResponse.text()
console.log(`Cron list URL: ${cronListUrl}`)
console.log(`Cron list response status: ${cronListResponse.status}`)
console.log(`Cron list content (first 1000 chars): ${cronListContent.substring(0, 1000)}`)
for (const cronCommand of cronCommands) {
if (!cronListContent.includes(cronCommand)) {
const addCronUrl = `${baseUrl}/cron/add`
const addCronPageResponse = await fetch(addCronUrl, {
const addCronPageContent = await addCronPageResponse.text()
console.log(`Add cron page URL: ${addCronUrl}`)
console.log(`Add cron page response status: ${addCronPageResponse.status}`)
console.log(`Add cron page content (first 1000 chars): ${addCronPageContent.substring(0, 1000)}`)
const newCsrfMatch = addCronPageContent.match(/name="csrfmiddlewaretoken" value="([^"]*)"/)
const newCsrfToken = newCsrfMatch ? newCsrfMatch[1] : null
throw new Error('New CSRF token not found for adding cron task')
const formData = new URLSearchParams({
'csrfmiddlewaretoken': newCsrfToken,
'minute_time_interval': 'on',
'hour_time_interval': 'each',
'day_time_interval': 'each',
'month_time_interval': 'each',
'dow_time_interval': 'each',
'comment': 'Auto added cron job'
console.log('Form data being sent:', formData.toString())
const { success, response: addCronResponse, content: addCronResponseContent } = await addCronWithRetry(addCronUrl, {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Upgrade-Insecure-Requests': '1'
body: formData.toString(),
console.log('Full response content:', addCronResponseContent)
if (addCronResponseContent.includes('Cron job has been added') || addCronResponseContent.includes('Zadanie cron zostało dodane')) {
const message = `添加了新的 cron 任务:${cronCommand}`;
await sendTelegramMessage(`账号 ${username} (${type}) ${message}`);
cronResults.push({ success: true, message });
// 如果响应中没有成功信息,再次检查cron列表
const checkCronListResponse = await fetch(cronListUrl, {
const checkCronListContent = await checkCronListResponse.text();
if (checkCronListContent.includes(cronCommand)) {
const message = `确认添加了新的 cron 任务:${cronCommand}`;
await sendTelegramMessage(`账号 ${username} (${type}) ${message}`);
cronResults.push({ success: true, message });
const message = `尝试添加 cron 任务:${cronCommand},但在列表中未找到。可能添加失败。`;
cronResults.push({ success: false, message });
const message = `添加 cron 任务失败:${cronCommand}`;
cronResults.push({ success: false, message });
const message = `cron 任务已存在:${cronCommand}`;
cronResults.push({ success: true, message });
return { username, type, cronResults, lastRun: new Date().toISOString() };
const message = `登录失败,未知原因。请检查账号和密码是否正确。`;
return { username, type, cronResults: [{ success: false, message }], lastRun: new Date().toISOString() };
const message = `登录或添加 cron 任务时出现错误: ${error.message}`;
return { username, type, cronResults: [{ success: false, message }], lastRun: new Date().toISOString() };
async function addCronWithRetry(url, options, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
const response = await fetch(url, options);
const responseContent = await response.text();
console.log(`Attempt ${i + 1} response status:`, response.status);
console.log(`Attempt ${i + 1} response content (first 1000 chars):`, responseContent.substring(0, 1000));
if (response.status === 200 || response.status === 302 || responseContent.includes('Cron job has been added') || responseContent.includes('Zadanie cron zostało dodane')) {
return { success: true, response, content: responseContent };
console.error(`Attempt ${i + 1} failed:`, error);
await delay(2000); // Wait 2 seconds before retrying
return { success: false };
function combineCookies(cookies1, cookies2) {
const cookieMap = new Map()
const parseCookies = (cookieString) => {
cookieString.split(',').forEach(cookie => {
const [fullCookie] = cookie.trim().split(';')
const [name, value] = fullCookie.split('=')
cookieMap.set(name.trim(), value.trim())
return Array.from(cookieMap.entries()).map(([name, value]) => `${name}=${value}`).join('; ')
async function sendTelegramMessage(message) {
const telegramConfig = JSON.parse(TELEGRAM_JSON)
const { telegramBotToken, telegramBotUserId } = telegramConfig
const url = `https://api.telegram.org/bot${telegramBotToken}/sendMessage`
headers: { 'Content-Type': 'application/json' },
chat_id: telegramBotUserId,
console.error('Error sending Telegram message:', error)
return new Promise(resolve => setTimeout(resolve, ms))