File size: 2,692 Bytes
5fd201e
 
 
 
 
 
fc92530
5fd201e
 
 
 
 
 
 
fc92530
5fd201e
 
fc92530
 
5fd201e
fc92530
 
 
 
 
 
 
 
5fd201e
fc92530
5fd201e
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 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()<deadline){
   try{const candidate=child.zkPopupProof;if(candidate?.nonce===nonce){proof=candidate.proof;break;}}catch{}
   await new Promise(resolve=>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()<until){const status=await fetch('/space/preview-status',{method:'POST',credentials:'same-origin',headers,body:JSON.stringify({nonce})});if(status.ok&&(await status.json()).consumed){consumed=true;break;}await new Promise(resolve=>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();});
});