// The fragment never reaches HTTP access logs. Session credentials never enter JS. export function openPreview(url,descriptor){ const nonce=Array.from(crypto.getRandomValues(new Uint8Array(32)),b=>b.toString(16).padStart(2,'0')).join(''); const target=new URL(url,location.origin);target.hash='bridge='+nonce; if(target.searchParams.has('lease'))target.pathname='/preview-launch/'; const child=window.open(target.href,'_blank');if(child)child.opener=null; const result={window:child}; const ready=(async()=>{ // Bind the approval to this actual popup, not to a link another site could send. let proof;const deadline=Date.now()+30000; while(child&&!child.closed&&Date.now()setTimeout(resolve,100)); } if(child&&!proof)throw Error('应用窗口未能打开,请允许新窗口后重试。'); const s=await(await fetch('/api/session',{credentials:'same-origin'})).json(); if(!s.authenticated)throw Error('请先登录工作台。'); const headers={'Content-Type':'application/json','X-CSRF-Token':s.csrf}; const r=await fetch('/space/preview-authorize',{method:'POST',credentials:'same-origin',headers,body:JSON.stringify({...descriptor,nonce,...(proof?{proof}:{})})}); if(!r.ok)throw Error('应用打开未完成,请从当前工程重试。'); if(!child){ let consumed=false;const until=Date.now()+30000; while(Date.now()setTimeout(resolve,250));} if(!consumed)throw Error('请允许应用在新窗口打开。'); // HF opened the isolated window and its one-use grant was actually consumed. // There is intentionally no WindowProxy to control or bypass. result.window={opener:null,close(){}}; } })(); result.ready=ready;return result; } document.addEventListener('click',event=>{ const link=event.target.closest('a[href]');if(!link||event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return; const url=new URL(link.href,location.origin); if(url.origin!==location.origin||!['/preview-site/','/preview-launch/'].includes(url.pathname))return; const query=url.searchParams,descriptor=query.has('lease')?{lease:query.get('lease')}:{kind:query.get('kind'),reference:query.get('reference')}; event.preventDefault();const opened=openPreview(url.href,descriptor);opened.ready.catch(()=>{if(opened.window)opened.window.close();}); });