const apiBase=document.documentElement.dataset.apiBase||''; const cardReady=document.getElementById('cardReady'); const loadCardButton=document.getElementById('loadCardButton'); const atList=document.getElementById('atList'); const addAtButton=document.getElementById('addAtButton'); const importAtButton=document.getElementById('importAtButton'); const atFileInput=document.getElementById('atFileInput'); const atCount=document.getElementById('atCount'); const startButton=document.getElementById('startButton'); const stopButton=document.getElementById('stopButton'); const copyButton=document.getElementById('copyButton'); const clearButton=document.getElementById('clearButton'); const taskRows=document.getElementById('taskRows'); const statusBox=document.getElementById('status'); const progressText=document.getElementById('progressText'); const progressPercent=document.getElementById('progressPercent'); const progressBar=document.getElementById('progressBar'); const bindProxyPoolInput=document.getElementById('bindProxyPool'); const promoProxyPoolInput=document.getElementById('promoProxyPool'); const bindProxyCount=document.getElementById('bindProxyCount'); const promoProxyCount=document.getElementById('promoProxyCount'); const batchConcurrencyInput=document.getElementById('batchConcurrency'); const steps=[document.getElementById('stepCard'),document.getElementById('stepAt'),document.getElementById('stepBind'),document.getElementById('stepLink'),document.getElementById('stepPay')].filter(Boolean); let stripe=null; let stripeKey=''; let cardFieldsMounted=false; const prefetchedSessions=new Map(); let cardNumberElement=null,cardExpiryElement=null,cardCvcElement=null; const cardComplete={number:false,expiry:false,cvc:false}; let cardIsReady=false; let stopped=false; let running=false; let proxyCursor=0; let cardSetupMutex=Promise.resolve(); let cardSetupPending=0; const results=[]; const AT_IMPORT_LIMIT=500; const MAX_BATCH_CONCURRENCY=200; const CONCURRENCY_STORAGE_VERSION='200-v1'; const flowLogic=window.CardFlowLogic; if(!flowLogic)throw new Error('Card flow logic failed to load'); const plusVerification=flowLogic.classifyPlus; const chunkPaymentWaves=flowLogic.chunkPaymentWaves; document.documentElement.dataset.cardFlowLogic='ready'; let paymentWaveLimit=MAX_BATCH_CONCURRENCY; let runtimeConfigPromise=null; const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms)); function status(text,kind=''){statusBox.textContent=text;statusBox.className=('status '+kind).trim()} function stripeSetupFailure(value){ const stripeError=value||{}; const details=[]; if(stripeError.code)details.push('code='+String(stripeError.code)); if(stripeError.decline_code)details.push('decline_code='+String(stripeError.decline_code)); const error=new Error((stripeError.message||'Card binding failed')+(details.length?' ('+details.join(', ')+')':'')); error.stage='card_bind'; error.stripeCode=String(stripeError.code||''); error.declineCode=String(stripeError.decline_code||''); return error; } function setStep(index){steps.forEach((el,i)=>{el.classList.toggle('active',i===index);el.classList.toggle('done',i300)found.push(token.trim()); } for(const [key,item] of Object.entries(value)){ if(String(key).toLowerCase().includes('sessiontoken'))continue; collectJsonAccessTokens(item,found); } return found; } function accessTokenRank(token){ try{ const segment=token.split('.')[1].replace(/-/g,'+').replace(/_/g,'/'); const claims=JSON.parse(atob(segment+'='.repeat((4-segment.length%4)%4))); const exp=Number(claims.exp||0),iat=Number(claims.iat||0),now=Math.floor(Date.now()/1000); return[(exp===0||exp>now)?1:0,iat,exp]; }catch{return[0,0,0]} } function chooseLatestAccessToken(values){ const unique=[...new Set(values.map(value=>String(value||'').trim()).filter(Boolean))]; unique.sort((left,right)=>{ const a=accessTokenRank(left),b=accessTokenRank(right); return b[0]-a[0]||b[1]-a[1]||b[2]-a[2]||right.length-left.length; }); return unique[0]||''; } function extractToken(raw){ const text=String(raw||'').trim(); if(!text)return''; const candidates=[]; if(text.startsWith('{')||text.startsWith('[')){ try{ candidates.push(...collectJsonAccessTokens(JSON.parse(text))); }catch{} } for(const match of text.matchAll(/["']access_?token["']\s*:\s*["']([^"']+)["']/ig))candidates.push(match[1]); const jwtMatches=text.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g)||[]; candidates.push(...jwtMatches); candidates.push(...text.split(/[\s|,;]+/).filter(value=>value.length>300&&value.split('.').length===3)); return chooseLatestAccessToken(candidates)||text; } function extractAllAccessTokens(raw){ const text=String(raw||'').trim(); if(!text)return[]; const candidates=[]; if(text.startsWith('{')||text.startsWith('[')){ try{candidates.push(...collectJsonAccessTokens(JSON.parse(text)))}catch{} } for(const match of text.matchAll(/["'](?:access_?token|access-token|at)["']\s*:\s*["']([^"']+)["']/ig))candidates.push(match[1]); candidates.push(...(text.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g)||[])); const seen=new Set(),tokens=[]; for(const candidate of candidates){ const token=String(candidate||'').trim(); if(token.length<300||token.split('.').length!==3||seen.has(token))continue; seen.add(token);tokens.push(token); if(tokens.length>=AT_IMPORT_LIMIT)break; } return tokens; } function renumberAtCards(){ const cards=[...atList.querySelectorAll('.at-entry')]; cards.forEach((card,index)=>{ card.querySelector('.at-entry-index').textContent='AT '+String(index+1).padStart(2,'0'); card.querySelector('.remove-at-button').disabled=cards.length===1||running; }); atCount.textContent=cards.length+' AT'; } function addAtField(value='',options={}){ const focus=options.focus!==false; const refresh=options.refresh!==false; const card=document.createElement('article'); card.className='at-entry'; card.innerHTML='
单独输入
'; const input=card.querySelector('.at-item-input'); input.value=value; input.addEventListener('input',updateCount); card.querySelector('.remove-at-button').addEventListener('click',()=>{if(running)return;card.remove();if(!atList.children.length)addAtField();renumberAtCards();updateCount()}); atList.appendChild(card); if(refresh){renumberAtCards();updateCount()} if(focus)input.focus(); return input; } function parseTokens(){ const seen=new Set(),items=[]; for(const input of atList.querySelectorAll('.at-item-input')){ const token=extractToken(input.value); if(token.length<300||!token.includes('.')||seen.has(token))continue; seen.add(token);items.push(token); } return items; } function importAccessTokens(tokens,fileName=''){ const existing=new Set(parseTokens()); const blanks=[...atList.querySelectorAll('.at-item-input')].filter(input=>!String(input.value||'').trim()); let added=0,duplicates=0; for(const token of tokens){ if(existing.has(token)){duplicates++;continue} if(existing.size>=AT_IMPORT_LIMIT)break; const input=blanks.shift()||addAtField('',{focus:false,refresh:false}); input.value=token;existing.add(token);added++; } renumberAtCards();updateCount(); const source=fileName||'AT \u6587\u4ef6'; if(added)status('\u5df2\u4ece '+source+' \u5bfc\u5165 '+added+' \u4e2a AT'+(duplicates?'\uff0c\u8df3\u8fc7 '+duplicates+' \u4e2a\u91cd\u590d\u9879':'')+'\u3002','ok'); else if(duplicates)status('\u6587\u4ef6\u4e2d\u7684 AT \u5df2\u5168\u90e8\u5b58\u5728\u4e8e\u5217\u8868\u4e2d\u3002','error'); else status('\u672a\u5728\u6587\u4ef6\u4e2d\u627e\u5230\u6709\u6548 AT\u3002','error'); return added; } function parseProxyInput(input){ const seen=new Set(),items=[]; for(const line of String(input?.value||'').replace(/\r/g,'').split('\n')){ const value=line.trim();if(!value||seen.has(value))continue; seen.add(value);items.push(value); if(items.length>=500)break; } return items; } function parseBindProxyPool(){return parseProxyInput(bindProxyPoolInput)} function parsePromoProxyPool(){return parseProxyInput(promoProxyPoolInput)} function nextProxy(){ const pool=parseBindProxyPool(); if(!pool.length)throw new Error('Please provide at least one US binding proxy'); const value=pool[proxyCursor%pool.length];proxyCursor=(proxyCursor+1)%Math.max(1,pool.length);return value; } function updateCount(){ const valid=parseTokens().length; const total=atList.querySelectorAll('.at-entry').length; const bindProxies=parseBindProxyPool().length; const promoProxies=parsePromoProxyPool().length; atCount.textContent=valid+' / '+total+' AT'; bindProxyCount.textContent=bindProxies+' PROXY'; promoProxyCount.textContent=promoProxies+' PROXY'; if(!running){ loadCardButton.disabled=cardFieldsMounted||!(valid&&bindProxies); loadCardButton.textContent=cardFieldsMounted?'\u5361\u7247\u8f93\u5165\u6846\u5df2\u52a0\u8f7d':'\u52a0\u8f7d\u5b89\u5168\u5361\u7247\u8f93\u5165\u6846'; startButton.disabled=!(cardFieldsMounted&&cardIsReady&&valid&&bindProxies&&promoProxies); startButton.textContent='\u5f00\u59cb\u7ed1\u5361\u3001\u63d0\u94fe\u5e76\u534f\u8bae\u652f\u4ed8'; } } async function api(url,options={}){ let response; try{ response=await fetch(url,{credentials:'include',...options}); }catch(cause){ const error=new Error(cause?.message||'Network request failed'); error.httpStatus=0;error.networkError=true;throw error; } const data=await response.json().catch(()=>({})); if(!response.ok||data.error||data.ok===false){ const code=data.error||('HTTP '+response.status); const detail=String(data.detail||'').replace(/:\/\/[^/@\s]+@/g,'://***@').trim().slice(0,300); const message=['AT_INVALID_OR_EXPIRED','AT_INVALIDATED_OR_EXPIRED'].includes(data.error)?'AT was invalidated by the server or rotated; use the latest AT and retry':(code+(detail?': '+detail:'')); const error=new Error(message); error.httpStatus=response.status; error.upstreamStatus=Number(data.status||0); error.proxyPoolExhausted=Boolean(data.proxy_pool_exhausted); throw error; } return data; } function ensureRuntimeConfig(){ if(runtimeConfigPromise)return runtimeConfigPromise; runtimeConfigPromise=api(apiBase+'/api/card-bind/config').then(config=>{ const configured=Number(config.max_batch_concurrency||MAX_BATCH_CONCURRENCY)||MAX_BATCH_CONCURRENCY; paymentWaveLimit=Math.max(1,Math.min(MAX_BATCH_CONCURRENCY,configured)); document.documentElement.dataset.paymentWaveLimit=String(paymentWaveLimit); return paymentWaveLimit; }).catch(()=>paymentWaveLimit); return runtimeConfigPromise; } function retryableNetworkError(error){ if(error?.proxyPoolExhausted)return false; const http=Number(error?.httpStatus||0); const upstream=Number(error?.upstreamStatus||0); const message=String(error?.message||'').toLowerCase(); if(error?.networkError)return true; if([502,503,504].includes(http)&&(!upstream||upstream>=500||upstream===403))return true; return /network|timeout|timed out|connection|transport|tls|ssl|empty reply|temporar|upstream/.test(message); } async function apiWithRetry(url,options={},attempts=3,onRetry=null){ let lastError=null; for(let attempt=1;attempt<=attempts;attempt++){ try{return await api(url,options)} catch(error){ lastError=error; if(!retryableNetworkError(error)||attempt>=attempts)throw error; if(onRetry)onRetry(attempt,attempts,error); await sleep(1000*attempt); } } throw lastError||new Error('Network request failed'); } async function apiWithProxyRetry(url,baseBody,attempts=3,onRetry=null){ let lastError=null; for(let attempt=1;attempt<=attempts;attempt++){ const proxy=nextProxy(); const body={...baseBody,proxy,proxy_pool:parseBindProxyPool()}; try{return await api(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)})} catch(error){ lastError=error; if(!retryableNetworkError(error)||attempt>=attempts)throw error; if(onRetry)onRetry(attempt,attempts,error); await sleep(1000*attempt); } } throw lastError||new Error('Proxy request failed'); } function findLink(value){ if(!value)return''; if(typeof value==='string'&&/^https:\/\/(?:chatgpt\.com\/checkout|pay\.openai\.com\/)/.test(value))return value; if(Array.isArray(value)){for(const item of value){const found=findLink(item);if(found)return found}} else if(typeof value==='object'){for(const item of Object.values(value)){const found=findLink(item);if(found)return found}} return''; } function updatePlusStatus(row,verification){ const target=row?.querySelector('.row-plus'); if(target)target.textContent=verification.label; } function finalTaskPresentation(verification){ if(verification.verified)return{stage:'Completed',kind:'success'}; if(verification.state==='verification_required')return{stage:'Payment verification required',kind:'running'}; if(verification.state==='not_plus')return{stage:'Payment completed / Plus not received',kind:'running'}; if(verification.state==='unknown')return{stage:'Payment completed / Plus check failed',kind:'running'}; return{stage:'Waiting for Plus verification',kind:'running'}; } function addRow(id,label){ const row=document.createElement('div');row.className='task-row';row.id=id; row.innerHTML='
账号Plus待检测
Waiting
'; row.querySelector('.row-account').textContent=label; const copy=row.querySelector('.copy-one-button'); copy.addEventListener('click',async()=>{ const link=row.querySelector('.row-link').href; if(!link)return; await navigator.clipboard.writeText(link); copy.textContent='Copied'; setTimeout(()=>copy.innerHTML='复制链接',1200); }); const retry=row.querySelector('.retry-one-button'); retry.addEventListener('click',()=>retrySingleAt(row)); taskRows.appendChild(row);return row; } function updateRow(row,stage,kind='',result=''){ row.className=('task-row '+kind).trim(); row.querySelector('.row-stage').textContent=stage; const link=row.querySelector('.row-link'); const message=row.querySelector('.row-message'); const copy=row.querySelector('.copy-one-button'); const retry=row.querySelector('.retry-one-button'); if(/^https:\/\//.test(result||'')){ link.href=result;link.textContent=result;link.hidden=false; message.textContent='';copy.hidden=false;retry.hidden=true; }else{ link.removeAttribute('href');link.textContent='';link.hidden=true; message.textContent=result||'';copy.hidden=true;retry.hidden=kind!=='failed'||!row._token;retry.disabled=Boolean(row._retrying)||running||cardSetupPending>0; } } function refreshRetryButtons(){ taskRows.querySelectorAll('.retry-one-button:not([hidden])').forEach(button=>{ const row=button.closest('.task-row'); button.disabled=Boolean(row?._retrying)||running||cardSetupPending>0; }); } function refreshOutput(){} async function pollCheckout(taskId,onProgress=null){ for(let i=0;i<180;i++){ if(stopped)throw new Error('Task stopped'); const task=await apiWithRetry(apiBase+'/api/card-flow/task/'+taskId,{},3); if(onProgress)onProgress(task); if(task.status==='done'){ const link=findLink(task.result||task); if(!link)throw new Error('Checkout task completed without a link'); return link; } if(['error','failed','cancelled'].includes(task.status))throw new Error(task.error||task.message||'Checkout extraction failed'); await sleep(2000); } throw new Error('Checkout extraction timed out'); } async function cancelUnifiedTask(taskId){ if(!taskId)return; try{await api(apiBase+'/api/unified-flow/jobs/'+taskId+'/cancel',{method:'POST'})}catch{} } async function releaseUnifiedPayments(taskIds){ return api(apiBase+'/api/unified-flow/batch-confirm',{ method:'POST',headers:{'Content-Type':'application/json'}, body:JSON.stringify({job_ids:taskIds}) }); } async function pollUnifiedTask(taskId,onProgress=null,stopAtPrepared=false){ for(let i=0;i<900;i++){ if(stopped){await cancelUnifiedTask(taskId);throw new Error('Task stopped')} const data=await apiWithRetry(apiBase+'/api/unified-flow/jobs/'+taskId,{},3); const task=data.job||{}; if(onProgress)onProgress(task); if(stopAtPrepared&&task.status==='prepared')return task; if(['ready','verification_required','pending_verification'].includes(task.status))return task; if(['error','failed','cancelled'].includes(task.status))throw new Error(task.error||task.message||'Unified flow failed'); await sleep(1500); } await cancelUnifiedTask(taskId); throw new Error('Unified flow timed out'); } async function mountCardFields(publishableKey){ if(typeof window.Stripe!=='function')throw new Error('Stripe \u5b89\u5168\u7ec4\u4ef6\u52a0\u8f7d\u5931\u8d25\uff0c\u8bf7\u5237\u65b0\u9875\u9762\u540e\u91cd\u8bd5'); if(cardNumberElement){try{cardNumberElement.destroy()}catch{}} if(cardExpiryElement){try{cardExpiryElement.destroy()}catch{}} if(cardCvcElement){try{cardCvcElement.destroy()}catch{}} for(const key of Object.keys(cardComplete))cardComplete[key]=false; cardIsReady=false;updateCount(); stripeKey=publishableKey; cardFieldsMounted=true; stripe=Stripe(publishableKey); const elements=stripe.elements(); const style={ base:{fontSize:'17px',fontFamily:'"Microsoft YaHei","PingFang SC","Segoe UI",system-ui,sans-serif',color:'#f4f8ff',iconColor:'#58d9b2','::placeholder':{color:'#6f8299'}}, invalid:{color:'#ff7388',iconColor:'#ff7388'} }; cardNumberElement=elements.create('cardNumber',{showIcon:true,style}); cardExpiryElement=elements.create('cardExpiry',{style}); cardCvcElement=elements.create('cardCvc',{style}); const entries=[['number',cardNumberElement,'#cardNumberElement'],['expiry',cardExpiryElement,'#cardExpiryElement'],['cvc',cardCvcElement,'#cardCvcElement']]; let readyCount=0; const refreshCardState=()=>{ cardIsReady=cardComplete.number&&cardComplete.expiry&&cardComplete.cvc; cardReady.textContent=cardIsReady?'Card information is complete':'Please complete card number, expiry and CVC'; cardReady.className='inline-state '+(cardIsReady?'ok':'');updateCount(); }; for(const [name,element,selector] of entries){ document.querySelector(selector).innerHTML=''; element.on('ready',()=>{readyCount++;if(readyCount===3){cardReady.textContent='Card fields are ready';cardReady.className='inline-state ok'}}); element.on('change',event=>{cardComplete[name]=Boolean(event.complete);const host=document.querySelector(selector);host.classList.toggle('field-complete',Boolean(event.complete));host.classList.toggle('field-invalid',Boolean(event.error));if(event.error){cardReady.textContent=event.error.message;cardReady.className='inline-state error'}else refreshCardState()}); element.mount(selector); } } async function init(){ cardReady.textContent='\u8bf7\u5148\u586b\u5199 AT \u548c\u4ee3\u7406\u6c60\uff0c\u518d\u70b9\u51fb\u201c\u52a0\u8f7d\u5b89\u5168\u5361\u7247\u8f93\u5165\u6846\u201d'; cardReady.className='inline-state'; status('\u586b\u5199 AT \u4e0e\u4ee3\u7406\u6c60\u540e\uff0c\u5148\u52a0\u8f7d\u5361\u7247\u8f93\u5165\u6846\uff0c\u518d\u8f93\u5165\u5361\u53f7\u3001\u6709\u6548\u671f\u548c CVC\u3002'); updateCount(); } async function resolvePendingKey(session){ if(!session||!session.pending)return session; const probeId=String(session.key_probe_id||''); if(!probeId)throw new Error('Stripe key probe ID is missing'); for(let i=0;i<360;i++){ const data=await apiWithRetry(apiBase+'/api/card-bind/key-probe/'+probeId,{},3); const probe=data.probe||{}; status('Resolving Stripe key via temporary Checkout: '+Number(probe.progress||0)+'%'); if(probe.status==='done'){ const refreshed=(probe.session&&typeof probe.session==='object')?probe.session:{}; const key=String(refreshed.publishable_key||probe.publishable_key||''); if(!key.startsWith('pk_'))throw new Error('Checkout initialization completed without a Stripe key'); if(!String(refreshed.client_secret||'').startsWith('seti_'))throw new Error('Checkout initialized, but the refreshed SetupIntent is missing'); return {...session,...refreshed,pending:false,publishable_key:key,publishable_key_source:'checkout_then_refetch'}; } if(probe.status==='error')throw new Error(probe.error||probe.message||'Stripe key resolution failed'); await sleep(2000); } throw new Error('Stripe key resolution timed out'); } async function loadCardFieldsFromAt(token){ status('Reading AT and resolving the Stripe account...'); let session=await apiWithProxyRetry(apiBase+'/api/card-bind/session',{access_token:token},3,(attempt,total)=>status('Resolving Stripe account, proxy retry '+attempt+' / '+total)); session=await resolvePendingKey(session); const key=String(session.publishable_key||''); if(!key.startsWith('pk_'))throw new Error('The AT/Checkout response did not contain a Stripe publishable key'); prefetchedSessions.set(token,session); await mountCardFields(key); status(session.publishable_key_source==='configured_protocol_fallback'?'SetupIntent and the local protocol Stripe key are ready.':session.publishable_key_source==='checkout_protocol_fallback'?'AT response had no key; one Checkout was created and the card fields are now ready.':'Stripe key was resolved directly from the AT response.','ok'); } async function confirmCardSetupExclusive(row,session){ const queued=cardSetupPending>0; cardSetupPending++; refreshRetryButtons(); if(queued)updateRow(row,'Waiting for card binding slot','running'); const previous=cardSetupMutex; let release; cardSetupMutex=new Promise(resolve=>{release=resolve}); await previous; try{ if(stopped)throw new Error('Task stopped'); updateRow(row,'Binding the card','running'); row.dataset.phase='card_bind'; return await stripe.confirmCardSetup( session.client_secret, {payment_method:{card:cardNumberElement,billing_details:session.billing_details,allow_redisplay:'always'}} ); }finally{ cardSetupPending--; release(); refreshRetryButtons(); } } async function prepareOne(token,index,total,existingRow=null){ const row=existingRow||addRow('task-'+Date.now()+'-'+index,tokenLabel(token,index)); row._token=token;row.dataset.atIndex=String(index); row.dataset.phase='card_session'; row.querySelector('.row-account').textContent=tokenLabel(token,index); updateRow(row,'Reading AT and creating SetupIntent','running'); let session=prefetchedSessions.get(token)||null; if(session)prefetchedSessions.delete(token); if(!session){ session=await apiWithProxyRetry(apiBase+'/api/card-bind/session',{access_token:token},3,(attempt,total)=>updateRow(row,'Proxy retry '+attempt+' / '+total,'running')); session=await resolvePendingKey(session); } const sessionKey=String(session.publishable_key||''); if(sessionKey&&sessionKey!==stripeKey){ prefetchedSessions.set(token,session); await mountCardFields(sessionKey); stopped=true; const error=new Error('Stripe account changed. Card fields were refreshed with the Checkout key; re-enter the card and retry this AT.'); error.cardReentryRequired=true; throw error; } const account=session.account_email||('account-'+(index+1)); row.querySelector('.row-account').textContent=account; if(!session.billing_details)throw new Error('Automatic US billing details are missing'); const confirmation=await confirmCardSetupExclusive(row,session); if(confirmation.error)throw stripeSetupFailure(confirmation.error); if(!confirmation.setupIntent||confirmation.setupIntent.status!=='succeeded'){ const error=new Error('Card binding status: '+(confirmation.setupIntent?.status||'unknown')); error.stage='card_bind';throw error; } const pm=typeof confirmation.setupIntent.payment_method==='string'?confirmation.setupIntent.payment_method:confirmation.setupIntent.payment_method?.id; if(!pm){const error=new Error('Stripe did not return a PaymentMethod');error.stage='card_bind';throw error} updateRow(row,'Starting unified card, link and payment task','running'); row.dataset.phase='task_create'; const created=await api(apiBase+'/api/unified-flow/jobs',{ method:'POST',headers:{'Content-Type':'application/json'}, body:JSON.stringify({access_token:token,payment_method_id:pm,entry_proxy_pool:parseBindProxyPool(),exit_proxy_pool:parsePromoProxyPool()}) }); const job=created.job||{}; row._unifiedTaskId=String(job.id||''); return{account,row,jobId:row._unifiedTaskId,paymentMethodId:pm}; } async function retrySingleAt(row){ if(!row?._token||row._retrying)return; if(running||cardSetupPending>0){status('A card binding task is already running. Retry after it finishes.','error');return} if(!cardIsReady){status('Please complete the card fields before retrying this AT.','error');return} const batchWasRunning=running; row._retrying=true; const retry=row.querySelector('.retry-one-button'); retry.disabled=true; if(!batchWasRunning){startButton.disabled=true;addAtButton.disabled=true;importAtButton.disabled=true} try{ status('??????? AT??????????'); if(row._unifiedTaskId){await cancelUnifiedTask(row._unifiedTaskId);row._unifiedTaskId='';await sleep(300)} const index=Number(row.dataset.atIndex||0); const prepared=await prepareOne(row._token,index,1,row); const onProgress=item=>updateRow(prepared.row,item.stage||item.message||'Running',item.status==='error'?'failed':'running',item.checkout_url||''); await pollUnifiedTask(prepared.jobId,onProgress,true); updateRow(row,'Ready for payment','running'); await releaseUnifiedPayments([prepared.jobId]); const task=await pollUnifiedTask(prepared.jobId,onProgress); const link=task.checkout_url||findLink(task.result||task); const verification=plusVerification(task); updatePlusStatus(row,verification); const previous=results.findIndex(item=>item.account===prepared.account); if(previous>=0)results.splice(previous,1); results.push({account:prepared.account,link,status:task.status,subscription:verification.subscription,plusStatus:verification.state}); refreshOutput(); const presentation=finalTaskPresentation(verification); updateRow(row,presentation.stage,presentation.kind,link||task.message); status('? AT ????????','ok'); }catch(error){ updateRow(row,'Retry failed','failed',error.message); status('? AT ?????'+error.message,'error'); }finally{ row._retrying=false;refreshRetryButtons(); if(!batchWasRunning){ startButton.disabled=!(cardFieldsMounted&&cardIsReady&&parseTokens().length&&parseBindProxyPool().length&&parsePromoProxyPool().length); addAtButton.disabled=false;importAtButton.disabled=false; } } } loadCardButton.addEventListener('click',async()=>{ if(running||cardFieldsMounted)return; const tokens=parseTokens(); if(!tokens.length){status('\u8bf7\u5148\u586b\u5199\u81f3\u5c11\u4e00\u4e2a\u6709\u6548 AT\u3002','error');return} if(!parseBindProxyPool().length){status('\u8bf7\u5148\u5728\u4ee3\u7406\u6c60 1 \u586b\u5199 US \u7ed1\u5361\u8282\u70b9\u3002','error');return} running=true;loadCardButton.disabled=true;startButton.disabled=true;addAtButton.disabled=true;importAtButton.disabled=true; cardReady.textContent='\u6b63\u5728\u521b\u5efa\u5b89\u5168\u5361\u7247\u8f93\u5165\u4f1a\u8bdd\u2026';cardReady.className='inline-state'; try{ await loadCardFieldsFromAt(tokens[0]); cardReady.textContent='\u5361\u7247\u8f93\u5165\u6846\u5df2\u5c31\u7eea\uff0c\u8bf7\u8f93\u5165\u5361\u53f7\u3001\u6709\u6548\u671f\u548c CVC'; cardReady.className='inline-state ok'; }catch(error){ cardFieldsMounted=false; cardReady.textContent='\u5361\u7247\u8f93\u5165\u6846\u52a0\u8f7d\u5931\u8d25\uff1a'+error.message; cardReady.className='inline-state error'; status('\u5361\u7247\u8f93\u5165\u6846\u52a0\u8f7d\u5931\u8d25\uff1a'+error.message,'error'); }finally{ running=false;addAtButton.disabled=false;importAtButton.disabled=false;renumberAtCards();updateCount(); } }); startButton.addEventListener('click',async()=>{ if(running)return; const tokens=parseTokens(); if(!tokens.length){status('?????????? AT?','error');return} if(!parseBindProxyPool().length){status('?????? 1 ?? US ?????','error');return} if(!parsePromoProxyPool().length){status('?????? 2 ?? TR ?????','error');return} if(!cardFieldsMounted){status('????????????????','error');return} if(!cardIsReady){status('???????????? CVC?','error');return} await ensureRuntimeConfig(); const concurrency=Math.max(1,Math.min(MAX_BATCH_CONCURRENCY,tokens.length,Number(batchConcurrencyInput?.value||MAX_BATCH_CONCURRENCY)||MAX_BATCH_CONCURRENCY)); localStorage.setItem('cardLinkConcurrency',String(concurrency)); localStorage.setItem('cardLinkConcurrencyVersion',CONCURRENCY_STORAGE_VERSION); running=true;stopped=false;results.length=0;refreshOutput();taskRows.innerHTML=''; startButton.disabled=true;stopButton.disabled=false;addAtButton.disabled=true;importAtButton.disabled=true;atList.querySelectorAll('textarea,button').forEach(el=>el.disabled=true); setStep(2);setProgress(0,tokens.length,'\u7edf\u4e00\u4efb\u52a1\u5df2\u542f\u52a8 '+concurrency); let success=0,pending=0,failed=0,preparedUnits=0,nextIndex=0; const preparedTasks=[]; const progressUpdate=text=>setProgress(Math.min(preparedUnits,tokens.length),tokens.length,text); const worker=async workerId=>{ await sleep(workerId*120); while(!stopped){ const i=nextIndex++; if(i>=tokens.length)return; status('??????'+Math.min(nextIndex,tokens.length)+' / '+tokens.length+'??? '+concurrency); let prepared=null; try{ prepared=await prepareOne(tokens[i],i,tokens.length); progressUpdate('\u7ed1\u5361\u5b8c\u6210\uff0c\u7b49\u5f85\u7edf\u4e00\u4efb\u52a1 '+(i+1)+' / '+tokens.length); }catch(error){ failed++;preparedUnits++; const row=document.querySelector('[data-at-index="'+i+'"]')||taskRows.querySelectorAll('.task-row')[i]; if(row){ const phase=String(error.stage||row.dataset.phase||''); const title=phase==='card_bind'?'Card binding failed':phase==='card_session'?'Card session failed':'Unified task creation failed'; updateRow(row,title,'failed',error.message); } progressUpdate('\u5931\u8d25 '+(success+failed)+' / '+tokens.length); continue; } if(stopped)return; setStep(3); try{ const task=await pollUnifiedTask(prepared.jobId,item=>{ const kind=item.status==='error'?'failed':'running'; updateRow(prepared.row,item.stage||item.message||'Unified flow running',kind,item.checkout_url||''); if(item.stage==='协议支付')setStep(4); },true); const link=task.checkout_url||findLink(task.result||task); preparedTasks.push({prepared,link}); updateRow(prepared.row,'Ready for concurrent payment','running',link||task.message); }catch(error){ if(!prepared.row._retrying){ failed++;updateRow(prepared.row,'Unified flow failed','failed',error.message); } }finally{ preparedUnits++;progressUpdate('Pre-payment ready '+preparedUnits+' / '+tokens.length); } } }; await Promise.all(Array.from({length:concurrency},(_,index)=>worker(index))); if(!stopped&&preparedTasks.length){ setStep(4); let paymentFinished=failed; const paymentWaves=chunkPaymentWaves(preparedTasks,paymentWaveLimit); const waveTotal=paymentWaves.length; for(let waveIndex=0;waveIndexitem.prepared.jobId)); await Promise.all(wave.map(async item=>{ const {prepared,link:preparedLink}=item; try{ const task=await pollUnifiedTask(prepared.jobId,progress=>updateRow(prepared.row,progress.stage||progress.message||'Concurrent payment running',progress.status==='error'?'failed':'running',progress.checkout_url||preparedLink||'')); const link=task.checkout_url||preparedLink||findLink(task.result||task); const verification=plusVerification(task); updatePlusStatus(prepared.row,verification); results.push({account:prepared.account,link,status:task.status,subscription:verification.subscription,plusStatus:verification.state});refreshOutput(); if(verification.verified){updateRow(prepared.row,'Completed','success',link);success++} else{ const presentation=finalTaskPresentation(verification); updateRow(prepared.row,presentation.stage,presentation.kind,link||task.message);pending++; } }catch(error){ failed++;updatePlusStatus(prepared.row,{label:'Plus\u68c0\u6d4b\u5931\u8d25'});updateRow(prepared.row,'Unified flow failed','failed',error.message); }finally{ paymentFinished++;setProgress(Math.min(paymentFinished,tokens.length),tokens.length,'Concurrent payment '+paymentFinished+' / '+tokens.length); } })); }catch(error){ failed+=wave.length;paymentFinished+=wave.length; await Promise.all(wave.map(item=>cancelUnifiedTask(item.prepared.jobId))); wave.forEach(item=>{updatePlusStatus(item.prepared.row,{label:'Plus\u68c0\u6d4b\u5931\u8d25'});updateRow(item.prepared.row,'Concurrent payment release failed','failed',error.message)}); setProgress(Math.min(paymentFinished,tokens.length),tokens.length,'Concurrent payment '+paymentFinished+' / '+tokens.length); } } } setStep(4);setProgress(tokens.length,tokens.length,'\u7edf\u4e00\u4efb\u52a1\u5df2\u7ed3\u675f'); status('\u672c\u6279\u5b8c\u6210\uff1a'+success+' \u6210\u529f,'+pending+' \u5f85\u9a8c\u8bc1,'+failed+' \u5931\u8d25'+(stopped?'\uff08\u5df2\u505c\u6b62\uff09':''),failed?'error':'ok'); running=false;stopButton.disabled=true;addAtButton.disabled=false;importAtButton.disabled=false;atList.querySelectorAll('textarea,button').forEach(el=>el.disabled=false);refreshRetryButtons();renumberAtCards();updateCount(); }); stopButton.addEventListener('click',async()=>{stopped=true;stopButton.disabled=true;status('\u6b63\u5728\u505c\u6b62\u7edf\u4e00\u4efb\u52a1...');await Promise.all([...taskRows.querySelectorAll('.task-row')].map(row=>cancelUnifiedTask(row._unifiedTaskId)))}); copyButton.addEventListener('click',async()=>{const links=results.map(item=>item.link).filter(Boolean);if(!links.length)return;await navigator.clipboard.writeText(links.join('\n'));status('All links copied.','ok')}); clearButton.addEventListener('click',()=>{results.length=0;refreshOutput();taskRows.innerHTML='';setProgress(0,0,'Waiting to start');status('Results cleared.')}); addAtButton.addEventListener('click',()=>addAtField()); importAtButton.addEventListener('click',()=>{if(!running)atFileInput.click()}); atFileInput.addEventListener('change',async()=>{ const file=atFileInput.files?.[0];atFileInput.value=''; if(!file||running)return; if(file.size>5*1024*1024){status('\u6587\u4ef6\u8d85\u8fc7 5 MB\uff0c\u8bf7\u62c6\u5206\u540e\u91cd\u8bd5\u3002','error');return} importAtButton.disabled=true; try{importAccessTokens(extractAllAccessTokens(await file.text()),file.name)} catch(error){status('\u8bfb\u53d6 AT \u6587\u4ef6\u5931\u8d25\uff1a'+String(error?.message||error),'error')} finally{importAtButton.disabled=running} }); bindProxyPoolInput.value=localStorage.getItem('cardLinkBindProxyPool')||localStorage.getItem('cardLinkProxyPool')||''; promoProxyPoolInput.value=localStorage.getItem('cardLinkPromoProxyPool')||''; if(batchConcurrencyInput){ const isCurrent=localStorage.getItem('cardLinkConcurrencyVersion')===CONCURRENCY_STORAGE_VERSION; const stored=Number(isCurrent?localStorage.getItem('cardLinkConcurrency'):MAX_BATCH_CONCURRENCY)||MAX_BATCH_CONCURRENCY; batchConcurrencyInput.value=String(Math.max(1,Math.min(MAX_BATCH_CONCURRENCY,stored))); localStorage.setItem('cardLinkConcurrency',batchConcurrencyInput.value); localStorage.setItem('cardLinkConcurrencyVersion',CONCURRENCY_STORAGE_VERSION); } bindProxyPoolInput.addEventListener('input',()=>{localStorage.setItem('cardLinkBindProxyPool',bindProxyPoolInput.value);updateCount()}); promoProxyPoolInput.addEventListener('input',()=>{localStorage.setItem('cardLinkPromoProxyPool',promoProxyPoolInput.value);updateCount()}); batchConcurrencyInput?.addEventListener('change',()=>{const value=Math.max(1,Math.min(MAX_BATCH_CONCURRENCY,Number(batchConcurrencyInput.value||MAX_BATCH_CONCURRENCY)||MAX_BATCH_CONCURRENCY));batchConcurrencyInput.value=String(value);localStorage.setItem('cardLinkConcurrency',String(value));localStorage.setItem('cardLinkConcurrencyVersion',CONCURRENCY_STORAGE_VERSION)}); addAtField(); ensureRuntimeConfig(); init();