╔══════════════════════════════════════════════════╗ ║ CODE REPOSITORY ARCHIVE ║ ╠══════════════════════════════════════════════════╣ ║ Repository: Wc ║ ║ Generated: 8/31/2026, 11:25:26 AM ║ ║ Files: 1 ║ ║ Description: Wc 1,9 ║ ╚══════════════════════════════════════════════════╝ FILE SUMMARY ──────────────────────────────────────────────────── Total files: 1 Total size: 148975 characters Folder structure: Wc/ Languages: - javascript: 1 files FILE CONTENTS ════════════════════════════════════════════════════ ┌── FILE 01: Wc/_worker.js │ Size: 148975 characters │ Language: javascript │ Created: 7/5/2026 └──────────────────────────────────────────────────── const CF_BASE_URL = "https://api.cloudflare.com/client/v4"; function jsonResponse(payload, status = 200) { return new Response(JSON.stringify(payload), { status, headers: { ...corsHeaders, "Content-Type": "application/json" } }); } function sanitizeWorkerName(name) { const fallback = `wc-${Date.now().toString(36)}`; const clean = String(name || fallback) .toLowerCase() .replace(/[^a-z0-9-]/g, '-') .replace(/-+/g, '-') .replace(/^-|-$/g, '') .slice(0, 63); return clean || fallback; } function cleanHost(value) { return String(value || '') .trim() .toLowerCase() .replace(/^https?:\/\//, '') .replace(/\/.*$/, '') .replace(/\s+/g, '') .replace(/^\.+|\.+$/g, ''); } function validBaseHost(host) { host = cleanHost(host); return !!host && host.length <= 253 && !host.includes('..') && host.split('.').every(label => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label) ); } function validHost(host) { host = cleanHost(host); if (!host) return false; if (host.startsWith('*.')) return validBaseHost(host.slice(2)); return validBaseHost(host); } function autoNodeCount(totalHosts, targetMode = 'multi_failover') { const mode = String(targetMode || '').toLowerCase(); if (mode === 'single' || mode === 'existing') return 1; const total = Math.max(1, Number.parseInt(String(totalHosts || '1'), 10) || 1); if (total <= 8) return 2; if (total <= 30) return 4; if (total <= 100) return 6; if (total <= 250) return 8; if (total <= 600) return 10; return 12; } function statusFromDomain(domain) { if (!domain) return 'not_found'; const values = [ domain.status, domain.state, domain.certificate_status, domain.ssl_status, domain?.certificate?.status, domain?.ssl?.status, domain?.ownership_verification?.status, domain?.verification?.status ].filter(v => v !== undefined && v !== null).map(v => String(v).toLowerCase()); if (values.some(v => v.includes('active') || v.includes('success') || v.includes('valid') || v.includes('issued') || v.includes('ready'))) return 'active'; if (values.some(v => v.includes('pending') || v.includes('initial') || v.includes('verify'))) return 'pending'; if (values.some(v => v.includes('fail') || v.includes('error') || v.includes('blocked'))) return 'error'; return values[0] || 'listed'; } class CfClient { constructor(email, apiKey) { this.email = String(email || '').trim(); this.apiKey = String(apiKey || '').trim(); } headers(contentType = 'application/json') { const h = { "X-Auth-Email": this.email, "X-Auth-Key": this.apiKey, "User-Agent": "Wildcard-Manager/1.9" }; if (contentType) h["Content-Type"] = contentType; return h; } async _fetch(path, options = {}) { if (!this.email || !this.apiKey) throw new Error('Email/API Key kosong. Import akun dulu.'); const url = path.startsWith('http') ? path : `${CF_BASE_URL}${path}`; const response = await fetch(url, { method: options.method || 'GET', headers: this.headers(options.contentType === undefined ? 'application/json' : options.contentType), body: options.body }); const text = await response.text(); let data = {}; if (text) { try { data = JSON.parse(text); } catch (_) { if (!response.ok) throw new Error(`Cloudflare API Error ${response.status}: ${text.slice(0, 180)}`); data = { success: true, result: text }; } } if (!response.ok || data?.success === false) { const msg = data?.errors?.map(e => e.message).join('; ') || data?.messages?.map(e => e.message).join('; ') || `Cloudflare API Error ${response.status}`; throw new Error(msg); } return data; } async getAccounts() { return this._fetch('/accounts?per_page=100'); } async listZones(status = 'active') { const all = []; for (let page = 1; page <= 10; page++) { let path = `/zones?per_page=100&page=${page}`; if (status) path += `&status=${encodeURIComponent(status)}`; const data = await this._fetch(path); const rows = Array.isArray(data.result) ? data.result : []; all.push(...rows); const info = data.result_info || {}; if (!rows.length || (info.total_pages && page >= info.total_pages)) break; } return { success: true, result: all }; } async listDnsRecords(zoneId, name = '') { let path = `/zones/${zoneId}/dns_records?per_page=100`; if (name) path += `&name=${encodeURIComponent(name)}`; return this._fetch(path); } async deleteDnsRecord(zoneId, recordId) { return this._fetch(`/zones/${zoneId}/dns_records/${recordId}`, { method: 'DELETE', contentType: null }); } async createZone(accountId, domainName) { return this._fetch('/zones', { method: 'POST', body: JSON.stringify({ account: { id: accountId }, name: domainName, jump_start: true, type: 'full' }) }); } async deleteZone(zoneId) { return this._fetch(`/zones/${zoneId}`, { method: 'DELETE', contentType: null }); } async createDnsRecord(zoneId, record) { return this._fetch(`/zones/${zoneId}/dns_records`, { method: 'POST', body: JSON.stringify(record) }); } async updateZoneSetting(zoneId, setting, value) { return this._fetch(`/zones/${zoneId}/settings/${setting}`, { method: 'PATCH', body: JSON.stringify({ value }) }); } async getUniversalSslSetting(zoneId) { return this._fetch(`/zones/${zoneId}/ssl/universal/settings`); } async updateUniversalSslSetting(zoneId, enabled = true) { return this._fetch(`/zones/${zoneId}/ssl/universal/settings`, { method: 'PATCH', body: JSON.stringify({ enabled: !!enabled }) }); } async getSslSettings(zoneId) { const settingNames = ['ssl', 'always_use_https', 'automatic_https_rewrites', 'min_tls_version']; const settings = {}; for (const name of settingNames) { try { const res = await this._fetch(`/zones/${zoneId}/settings/${name}`); settings[name] = res.result || res; } catch (e) { settings[name] = { value: null, error: e.message }; } } try { const universal = await this.getUniversalSslSetting(zoneId); settings.universal_ssl = universal.result || universal; } catch (e) { settings.universal_ssl = { enabled: null, error: e.message }; } return settings; } async activateSslRecommended(zoneId) { const steps = [ { label: 'Universal SSL', run: () => this.updateUniversalSslSetting(zoneId, true) }, { label: 'SSL/TLS mode Full', run: () => this.updateZoneSetting(zoneId, 'ssl', 'full') }, { label: 'Always Use HTTPS', run: () => this.updateZoneSetting(zoneId, 'always_use_https', 'on') }, { label: 'Automatic HTTPS Rewrites', run: () => this.updateZoneSetting(zoneId, 'automatic_https_rewrites', 'on') }, { label: 'Minimum TLS 1.2', run: () => this.updateZoneSetting(zoneId, 'min_tls_version', '1.2') } ]; const results = []; for (const step of steps) { try { const res = await step.run(); results.push({ label: step.label, success: true, result: res.result || res }); } catch (e) { results.push({ label: step.label, success: false, message: e.message }); } } return results; } async updateWorker(accountId, workerName, scriptContent) { const boundary = `----CFWildcardBoundary${Date.now().toString(16)}`; const metadata = { main_module: 'worker.js', compatibility_date: '2024-12-03', compatibility_flags: ['nodejs_compat'] }; const body = [ `--${boundary}`, 'Content-Disposition: form-data; name="worker.js"; filename="worker.js"', 'Content-Type: application/javascript+module', '', scriptContent, `--${boundary}`, 'Content-Disposition: form-data; name="metadata"', 'Content-Type: application/json', '', JSON.stringify(metadata), `--${boundary}--`, '' ].join('\r\n'); return this._fetch(`/accounts/${accountId}/workers/services/${workerName}/environments/production`, { method: 'PUT', contentType: `multipart/form-data; boundary=${boundary}`, body }); } async getOrCreateSubdomain(accountId) { try { const data = await this._fetch(`/accounts/${accountId}/workers/subdomain`); if (data?.result?.subdomain) return data.result.subdomain; } catch (_) {} const base = (this.email.split('@')[0] || 'worker') .toLowerCase() .replace(/[^a-z0-9-]/g, '') .slice(0, 28) || `wc${Date.now().toString(36)}`; const data = await this._fetch(`/accounts/${accountId}/workers/subdomain`, { method: 'PUT', body: JSON.stringify({ subdomain: base }) }); return data?.result?.subdomain || base; } async createWorker(accountId, workerName, scriptContent) { await this.updateWorker(accountId, workerName, scriptContent); try { await this._fetch(`/accounts/${accountId}/workers/services/${workerName}/environments/production/subdomain`, { method: 'POST', body: JSON.stringify({ enabled: true }) }); } catch (_) {} return { workerName, subdomain: await this.getOrCreateSubdomain(accountId) }; } async registerCustomDomain(accountId, workerName, hostname, zoneId) { return this._fetch(`/accounts/${accountId}/workers/domains`, { method: 'PUT', body: JSON.stringify({ environment: 'production', hostname, service: workerName, zone_id: zoneId }) }); } async findWorkerDomain(accountId, hostname, workerName) { const data = await this._fetch(`/accounts/${accountId}/workers/domains?hostname=${encodeURIComponent(hostname)}`); const rows = Array.isArray(data.result) ? data.result : []; const lowerHost = String(hostname || '').toLowerCase(); const lowerWorker = String(workerName || '').toLowerCase(); return rows.find(d => String(d.hostname || '').toLowerCase() === lowerHost && String(d.service || '').toLowerCase() === lowerWorker) || rows.find(d => String(d.hostname || '').toLowerCase() === lowerHost) || null; } async listPagesProjects(accountId) { const data = await this._fetch(`/accounts/${accountId}/pages/projects`); return { success: true, result: Array.isArray(data.result) ? data.result : [] }; } async createPagesProject(accountId, projectName) { return this._fetch(`/accounts/${accountId}/pages/projects`, { method: 'POST', body: JSON.stringify({ name: projectName, production_branch: 'main' }) }); } async deployPagesProject(accountId, projectName, scriptContent) { const boundary = '----Boundary' + Date.now().toString(36); let body = '--' + boundary + '\r\nContent-Disposition: form-data; name="manifest"\r\n\r\n{"name":"' + projectName + '"}\r\n'; body += '--' + boundary + '\r\nContent-Disposition: form-data; name="_worker.js"; filename="_worker.js"\r\nContent-Type: application/javascript\r\n\r\n' + scriptContent + '\r\n'; body += '--' + boundary + '--\r\n'; return this._fetch(`/accounts/${accountId}/pages/projects/${encodeURIComponent(projectName)}/deployments`, { method: 'POST', contentType: 'multipart/form-data; boundary=' + boundary, body: body }); } async listPagesDomains(accountId, projectName) { const data = await this._fetch(`/accounts/${accountId}/pages/projects/${encodeURIComponent(projectName)}/domains`); return { success: true, result: Array.isArray(data.result) ? data.result : [] }; } async addPagesDomain(accountId, projectName, domainName) { return this._fetch(`/accounts/${accountId}/pages/projects/${encodeURIComponent(projectName)}/domains`, { method: 'POST', body: JSON.stringify({ name: domainName }) }); } async deletePagesDomain(accountId, projectName, domainName) { return this._fetch(`/accounts/${accountId}/pages/projects/${encodeURIComponent(projectName)}/domains/${encodeURIComponent(domainName)}`, { method: 'DELETE', contentType: null }); } async triggerPagesVerification(accountId, projectName, domainName) { return this._fetch(`/accounts/${accountId}/pages/projects/${encodeURIComponent(projectName)}/domains/${encodeURIComponent(domainName)}`, { method: 'PATCH' }); } } const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' }; async function handleApiRequest(request) { if (request.method === 'OPTIONS') return new Response(null, { headers: corsHeaders }); const url = new URL(request.url); const path = url.pathname; let body = {}; try { body = await request.json(); } catch (_) { body = {}; } try { const email = body.email; const apiKey = body.apiKey; const accountId = String(body.accountId || '').trim(); const client = new CfClient(email, apiKey); if (path === '/api/accounts') return jsonResponse(await client.getAccounts()); // DOMAIN MANAGER API if (path === '/api/domainManager/list') { if (!accountId) throw new Error('Account ID kosong. Import akun format email|apiKey|accountId atau biarkan sistem mengambil otomatis.'); const data = await client.listZones(''); const domains = (Array.isArray(data.result) ? data.result : []).map(z => ({ id: z.id, name: z.name, status: z.status || '', paused: !!z.paused, type: z.type || '', name_servers: Array.isArray(z.name_servers) ? z.name_servers : [], plan: z.plan && z.plan.name ? z.plan.name : '' })).filter(z => z.id && z.name).sort((a, b) => a.name.localeCompare(b.name)); return jsonResponse({ success: true, domains }); } if (path === '/api/domainManager/add') { if (!accountId) throw new Error('Account ID kosong.'); const domainName = cleanHost(body.domainName); if (!validBaseHost(domainName) || domainName.split('.').length < 2) throw new Error('Nama domain tidak valid.'); const data = await client.createZone(accountId, domainName); return jsonResponse({ success: true, domain: data.result || data }); } if (path === '/api/domainManager/delete') { const data = await client.deleteZone(String(body.domainId || '').trim()); return jsonResponse({ success: true, result: data.result || data }); } if (path === '/api/domainManager/dnsList') { const data = await client.listDnsRecords(String(body.domainId || '').trim()); const records = (Array.isArray(data.result) ? data.result : []).map(r => ({ id: r.id, type: r.type, name: r.name, content: r.content, proxied: !!r.proxied, ttl: r.ttl, priority: r.priority })).sort((a, b) => String(a.name || '').localeCompare(String(b.name || '')) || String(a.type || '').localeCompare(String(b.type || ''))); return jsonResponse({ success: true, records }); } if (path === '/api/domainManager/fetchBulkText') { const res = await fetch(String(body.url || '').trim(), { method: 'GET', headers: { 'User-Agent': 'CF-Manager-Pro-BulkDNS/1.0' }, cf: { cacheTtl: 0 } }); if (!res.ok) throw new Error('Gagal mengambil URL raw: HTTP ' + res.status); return jsonResponse({ success: true, text: await res.text() }); } if (path === '/api/domainManager/dnsAdd') { const domainId = String(body.domainId || '').trim(), domainName = cleanHost(body.domainName), type = String(body.type || '').trim().toUpperCase(); let name = cleanHost(body.name); const content = String(body.content || '').trim(); if (!name || name === '@') name = domainName; else if (!(name === domainName || name.endsWith('.' + domainName))) name = `${name}.${domainName}`; const record = { type, name, content, ttl: Number(body.ttl || 1) }; if (type === 'MX') record.priority = Number(body.priority || 10); if (['A', 'AAAA', 'CNAME'].includes(type)) record.proxied = body.proxied === true; const data = await client.createDnsRecord(domainId, record); return jsonResponse({ success: true, record: data.result || data }); } if (path === '/api/domainManager/dnsDelete') { const data = await client.deleteDnsRecord(String(body.domainId || '').trim(), String(body.recordId || '').trim()); return jsonResponse({ success: true, result: data.result || data }); } if (path === '/api/domainManager/sslSettings') { const settings = await client.getSslSettings(String(body.domainId || '').trim()); return jsonResponse({ success: true, settings }); } if (path === '/api/domainManager/sslUpdate') { const data = await client.updateZoneSetting(String(body.domainId || '').trim(), String(body.setting || '').trim(), String(body.value || '').trim()); return jsonResponse({ success: true, result: data.result || data }); } if (path === '/api/domainManager/sslUniversal') { const data = await client.updateUniversalSslSetting(String(body.domainId || '').trim(), body.enabled !== false); return jsonResponse({ success: true, result: data.result || data }); } if (path === '/api/domainManager/sslActivate') { const results = await client.activateSslRecommended(String(body.domainId || '').trim()); return jsonResponse({ success: true, results }); } // ========================================== // SERVICE MANAGER API (PAGES & WORKER) // ========================================== if (path === '/api/serviceManager/projects') { if (!accountId) throw new Error('Account ID kosong.'); if (body.engine === 'pages') { const data = await client.listPagesProjects(accountId); const projects = (Array.isArray(data.result) ? data.result : []).map(p => ({ name: p.name })).sort((a, b) => a.name.localeCompare(b.name)); return jsonResponse({ success: true, projects }); } else { const data = await client._fetch(`/accounts/${accountId}/workers/services`); const projects = (Array.isArray(data.result) ? data.result : []).map(p => ({ name: p.id })).sort((a, b) => a.name.localeCompare(b.name)); return jsonResponse({ success: true, projects }); } } if (path === '/api/serviceManager/domains') { if (!accountId) throw new Error('Account ID kosong.'); const serviceName = String(body.serviceName || '').trim(); if (!serviceName) throw new Error('Pilih Service/Project dulu.'); if (body.engine === 'pages') { const data = await client.listPagesDomains(accountId, serviceName); const domains = (Array.isArray(data.result) ? data.result : []).map(d => ({ id: d.name, name: d.name, status: d.status || d.validation_status || '', target: d.verification_data?.target || '' })).sort((a, b) => a.name.localeCompare(b.name)); return jsonResponse({ success: true, domains }); } else { const data = await client._fetch(`/accounts/${accountId}/workers/domains`); const domains = (Array.isArray(data.result) ? data.result : []).filter(d => d.service === serviceName).map(d => ({ id: d.id, name: d.hostname, status: 'active', target: '' })).sort((a, b) => a.name.localeCompare(b.name)); return jsonResponse({ success: true, domains }); } } if (path === '/api/serviceManager/bulkAdd') { if (!accountId) throw new Error('Account ID kosong.'); const serviceName = String(body.serviceName || '').trim(); const engine = body.engine; const raw = Array.isArray(body.domains) ? body.domains.join('\n') : String(body.domains || ''); const rows = [...new Set(raw.split(/[\n,;]+/).map(v => cleanHost(v)).filter(validBaseHost))]; if (!rows.length) throw new Error('Tidak ada domain valid.'); const results = []; let zonesCache = null; if (engine === 'worker') { const zData = await client.listZones('active'); zonesCache = Array.isArray(zData.result) ? zData.result : []; } for (const name of rows.slice(0, 50)) { const row = { name, success: false, status: 'unknown' }; try { if (engine === 'pages') { const data = await client.addPagesDomain(accountId, serviceName, name); row.success = true; row.status = statusFromDomain(data.result || {}); } else { const zone = zonesCache.find(z => name === z.name || name.endsWith('.' + z.name)); if (!zone) throw new Error("Domain luar tidak didukung di Worker. Worker butuh Zone ID dari akun ini."); const data = await client.registerCustomDomain(accountId, serviceName, name, zone.id); row.success = true; row.status = 'active'; } } catch (e) { row.error = e.message || String(e); if (/already|exist|duplicate/i.test(row.error)) { row.success = true; row.status = 'already_exists'; } } results.push(row); } return jsonResponse({ success: true, results }); } if (path === '/api/serviceManager/delete') { if (!accountId) throw new Error('Account ID kosong.'); if (body.engine === 'pages') { const data = await client.deletePagesDomain(accountId, String(body.serviceName).trim(), cleanHost(body.domainName)); return jsonResponse({ success: true, result: data.result || data }); } else { if (!body.domainId) throw new Error("Domain ID missing for worker"); const data = await client._fetch(`/accounts/${accountId}/workers/domains/${body.domainId}`, { method: 'DELETE', contentType: null }); return jsonResponse({ success: true, result: data.result || data }); } } // ========================================== // WILDCARD SSL & DEPLOY API // ========================================== if (path === '/api/wildcardSsl/resources') { let workerSubdomain = ''; try { workerSubdomain = await client.getOrCreateSubdomain(accountId); } catch (_) {} const zr = await client.listZones('active'); const zones = (Array.isArray(zr.result) ? zr.result : []).map(z => ({ id: z.id, name: z.name })).filter(z => z.id && z.name).sort((a, b) => a.name.localeCompare(b.name)); return jsonResponse({ success: true, workerSubdomain, zones, warnings: {} }); } if (path === '/api/wildcardSsl/bulk') { const zoneName = cleanHost(body.zoneName), zoneId = String(body.zoneId || '').trim(), prefix = cleanHost(body.prefix); const mode = String(body.mode || 'attach'), engine = String(body.engine || 'worker').toLowerCase(), targetMode = String(body.targetMode || 'multi_failover').toLowerCase(); const proxied = body.proxied !== false; const offset = Math.max(0, Number.parseInt(String(body.offset || '0'), 10) || 0), totalHostCount = Math.max(1, Number.parseInt(String(body.totalHostCount || body.totalHosts || '0'), 10) || 0); const requestedNodeCount = autoNodeCount(totalHostCount || (Array.isArray(body.hostnames) ? body.hostnames.length : 1), targetMode); if (!accountId || !zoneId || !zoneName) throw new Error('Pilih Account dan Root Domain dulu.'); if (mode !== 'attach' && mode !== 'check') throw new Error('Mode wildcard hanya CONNECT dan CEK SSL.'); const baseHost = (!prefix || prefix === '*' || prefix === '@') ? zoneName : (prefix === zoneName || prefix.endsWith('.' + zoneName) ? prefix : `${prefix}.${zoneName}`); let workerName = sanitizeWorkerName(`${engine === 'pages' ? 'ssl' : 'wc'}-${baseHost}`); if (engine === 'pages' && body.pagesProjectName && (targetMode === 'single' || targetMode === 'existing')) { workerName = sanitizeWorkerName(body.pagesProjectName); } else if (engine === 'worker' && targetMode === 'existing' && body.existingName) { workerName = body.existingName; } const targetHost = baseHost, seen = new Set(), hostnames = []; const inSelectedZone = (h) => { h = cleanHost(h); const bare = h.startsWith('*.') ? h.slice(2) : h; return bare === zoneName || bare.endsWith('.' + zoneName); }; const pushHost = (h) => { h = cleanHost(h); if (validHost(h) && inSelectedZone(h) && !seen.has(h)) { seen.add(h); hostnames.push(h); } }; pushHost(baseHost); (Array.isArray(body.hostnames) ? body.hostnames : []).forEach(pushHost); if (!hostnames.length) throw new Error('Tidak ada hostname valid.'); const failoverHosts = [...new Set((Array.isArray(body.workerUrls) ? body.workerUrls.join('\n') : String(body.workerUrls || '')).split(/[\n,;]+/).map(v => cleanHost(v)).filter(validBaseHost))]; const multiEnabled = ['multi', 'balance', 'multi_balance', 'multi_failover', 'shard', 'sharding'].includes(targetMode); let workerNodes = []; if (!multiEnabled) workerNodes = [workerName]; else { for (let i = 1; i <= requestedNodeCount; i++) workerNodes.push(sanitizeWorkerName(`${workerName}-n${String(i).padStart(2, '0')}`)); } const makeWorkerProxyScript = (nodeName, nodeTargets) => `const NODE_NAME = ${JSON.stringify(nodeName)}; const WORKER_URLS = ${JSON.stringify(nodeTargets, null, 2)}; function shuffle(list) { return [...list].sort(() => Math.random() - 0.5); } function cleanHeaders(request) { const h = new Headers(request.headers); h.delete("host"); h.delete("cf-connecting-ip"); h.delete("cf-ipcountry"); h.delete("cf-ray"); h.delete("cf-visitor"); h.delete("x-forwarded-proto"); h.delete("x-real-ip"); h.set("x-wc-node", NODE_NAME); return h; } export default { async fetch(request) { if (!WORKER_URLS.length) return new Response("Worker Node: " + NODE_NAME + "\\nKosong. Isi WORKER_URLS/Target Failover.", { status: 200, headers: { "Content-Type": "text/plain" } }); const method = request.method.toUpperCase(), bodyBuffer = method !== "GET" && method !== "HEAD" ? await request.arrayBuffer() : null; const shuffled = shuffle(WORKER_URLS); for (const host of shuffled) { try { const t = new URL(request.url); t.hostname = host; t.protocol = "https:"; const proxyReq = new Request(t.toString(), { method: request.method, headers: cleanHeaders(request), body: bodyBuffer ? bodyBuffer.slice(0) : null, redirect: "manual" }); const res = await fetch(proxyReq); if (res.status !== 429 && res.status < 500) return res; } catch (e) { continue; } } return new Response("Semua target down. Node: " + NODE_NAME, { status: 503 }); } };`; const makePagesProxyScript = (targets) => { let arr = targets && targets.length > 0 ? targets.map(t => `'${t.trim()}'`).join(', ') : "'payload.goku25.workers.dev'"; return `export default { async fetch(request, env, ctx) { let url = new URL(request.url); let domainBackend = [${arr}]; if(env.HOST) domainBackend = await ADD(env.HOST); let pathUji = env.PATH || '/'; if (pathUji.charAt(0) !== '/') pathUji = '/' + pathUji; let kodeRespon = env.CODE || '200'; async function getValidResponse(request, hosts) { let shuffledHosts = hosts.sort(() => Math.random() - 0.5); for (const host of shuffledHosts) { let testUrl = new URL(url.href); testUrl.hostname = host; testUrl.pathname = pathUji.split('?')[0]; testUrl.search = pathUji.split('?')[1] || ''; try { const res = await fetch(testUrl.href, { method: 'HEAD', redirect: 'manual' }); if (res.status.toString() === kodeRespon || res.status === 302 || res.status === 301) { let finalUrl = new URL(url.href); finalUrl.hostname = host; return await fetch(new Request(finalUrl.href, { method: request.method, headers: new Headers(request.headers), body: request.body, redirect: 'follow' })); } } catch (error) {} } return new Response('Down', { status: 503 }); } return await getValidResponse(request, domainBackend); } }; async function ADD(envadd) { var addtext = envadd.replace(/[\\t |"'\\\`\\r\\n]+/g, ',').replace(/,+/g, ','); if (addtext.charAt(0) == ',') addtext = addtext.slice(1); if (addtext.charAt(addtext.length - 1) == ',') addtext = addtext.slice(0, -1); return addtext.split(','); }`; }; let workerSubdomain = ''; try { workerSubdomain = await client.getOrCreateSubdomain(accountId); } catch (_) {} const workerDnsTargets = Object.fromEntries(workerNodes.map(n => [n, workerSubdomain ? `${n}.${workerSubdomain}.workers.dev` : `${n}.workers.dev`])); if (mode === 'attach' && body.deployWorkers !== false) { for (let i = 0; i < workerNodes.length; i++) { const nodeName = workerNodes[i]; let myTargets = failoverHosts; if (body.distributeTargets && failoverHosts.length > 0) { const lpa = Math.ceil(failoverHosts.length / workerNodes.length), startIdx = i * lpa; myTargets = failoverHosts.slice(startIdx, startIdx + lpa); } if (engine === 'worker') { await client.createWorker(accountId, nodeName, makeWorkerProxyScript(nodeName, myTargets)); } else if (engine === 'pages') { try { await client.createPagesProject(accountId, nodeName); } catch (e) {} try { let scriptToDeploy = body.pagesCustomScript; if (body.pagesMode === 'default' || !scriptToDeploy) scriptToDeploy = makePagesProxyScript(myTargets); await client.deployPagesProject(accountId, nodeName, scriptToDeploy); } catch (e) {} } } } const results = []; let pagesDomainsCache = null; for (let i = 0; i < hostnames.slice(0, 10).length; i++) { const hostname = hostnames[i], assignedIndex = (offset + i) % workerNodes.length, assignedWorkerName = workerNodes[assignedIndex]; const row = { hostname, mode, targetMode, success: false, status: 'unknown', sslActive: false, workerName: assignedWorkerName, assignedWorker: assignedWorkerName, assignedWorkerUrl: workerDnsTargets[assignedWorkerName], targetHost, workerUrls: failoverHosts, workerNodes, proxied, actions: [] }; try { if (mode === 'attach') { try { const records = await client.listDnsRecords(zoneId, hostname); for (const r of (Array.isArray(records.result) ? records.result : [])) { if (['A', 'AAAA', 'CNAME'].includes(String(r.type || '').toUpperCase())) await client.deleteDnsRecord(zoneId, r.id); } } catch (_) {} if (engine === 'pages') { try { await client.addPagesDomain(accountId, assignedWorkerName, hostname); row.actions.push('attached_to_pages'); } catch (e) { if (/already|exist/i.test(e.message)) row.actions.push('pages_domain_exists'); else throw e; } try { await client.createDnsRecord(zoneId, { type: 'CNAME', name: hostname, content: `${assignedWorkerName}.pages.dev`, ttl: 1, proxied }); row.actions.push('cname_created'); } catch (e) { if (!/already/i.test(e.message)) throw e; } try { await client.triggerPagesVerification(accountId, assignedWorkerName, hostname); row.actions.push('ssl_verification_triggered'); } catch (_) {} row.status = 'pending'; row.sslActive = false; row.success = true; row.projectName = assignedWorkerName; } else { try { await client.registerCustomDomain(accountId, assignedWorkerName, hostname, zoneId); row.actions.push('attached_to_' + assignedWorkerName); } catch (e) { if (/already/i.test(e.message)) row.actions.push('exists'); else throw e; } const d = await client.findWorkerDomain(accountId, hostname, assignedWorkerName); row.domainId = d?.id || null; row.status = statusFromDomain(d); row.sslActive = row.status === 'active'; row.success = true; } } else { if (engine === 'pages') { if (!pagesDomainsCache) { try { pagesDomainsCache = (await client.listPagesDomains(accountId, assignedWorkerName)).result || []; } catch(e){ pagesDomainsCache = []; } } const pDomain = pagesDomainsCache.find(d => String(d.name).toLowerCase() === hostname.toLowerCase()); row.status = pDomain ? statusFromDomain(pDomain) : 'not_found'; } else { const d = await client.findWorkerDomain(accountId, hostname, assignedWorkerName); row.domainId = d?.id || null; row.status = statusFromDomain(d); } if (row.status !== 'active') { try { const probe = await fetch(`https://${hostname}/`, { method: 'HEAD', redirect: 'manual', cf: { cacheTtl: 0 } }); if (probe.status > 0 && probe.status < 600) row.status = 'active'; } catch (e) {} } row.sslActive = row.status === 'active'; row.success = true; row.projectName = assignedWorkerName; } } catch (e) { row.success = false; row.error = e.message; } results.push(row); } return jsonResponse({ success: true, baseHost, targetHost, workerName, workerNodes, workerDnsTargets, workerUrls: failoverHosts, targetMode, results }); } return jsonResponse({ success: false, message: 'Not found' }, 404); } catch (error) { return jsonResponse({ success: false, message: error.message || String(error) }, 400); } } function renderHTML() { return `
Domain + Service + Wildcard SSL Suite
Kelola root domain, name server, dan DNS record langsung dari akun yang dipilih.
List project Pages / Worker dan daftar Custom Domain di dalamnya. Berguna untuk nambah bug SNI secara masal.
Worker butuh Zone ID dari akun yang sama. Pages bisa domain luar.
Pilih root domain + prefix → pilih engine → deploy custom proxy → cek SSL sampai active.