@preventive/triage 1.0.0-alpha.67 → 1.0.0-alpha.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/common/managed/routes.js +19 -12
  2. package/out/activity.js +1 -1
  3. package/out/{chunk-LBJVV6UB.js → chunk-2F3CYNPZ.js} +1 -1
  4. package/out/{chunk-U5C2TNNQ.js → chunk-2HGKTQ5Q.js} +1 -1
  5. package/out/chunk-4RS3NDOG.js +1 -0
  6. package/out/{chunk-VR3NRE5V.js → chunk-D37M7J4B.js} +1 -1
  7. package/out/{chunk-LDO42LAC.js → chunk-GZ46SSTF.js} +1 -1
  8. package/out/{chunk-R3WUYD4F.js → chunk-HETCVNO4.js} +1 -1
  9. package/out/{chunk-5F5FPI75.js → chunk-MPXVKVPF.js} +1 -1
  10. package/out/{chunk-A5A3LEMV.js → chunk-OAWY4T6R.js} +1 -1
  11. package/out/{chunk-6YGH7BJG.js → chunk-QPGM3DTI.js} +1 -1
  12. package/out/{chunk-FUHRMY7R.js → chunk-SCN2TBP2.js} +5 -5
  13. package/out/client-managed-import.js +1 -1
  14. package/out/client-managed.js +2 -2
  15. package/out/compare.js +8 -8
  16. package/out/dialogs.js +2 -2
  17. package/out/graph.js +1 -1
  18. package/out/index.html +7 -7
  19. package/out/scan.js +1 -1
  20. package/out/view.css +1 -1
  21. package/out/view.js +1 -1
  22. package/package.json +1 -1
  23. package/server-managed/bundle-build-worker.js +59 -7
  24. package/server-managed/bundle-build.ts +9 -4
  25. package/server-managed/db-neon.ts +4 -1
  26. package/server-managed/dependency-review-comments.ts +13 -10
  27. package/server-managed/dependency-reviews.ts +17 -14
  28. package/server-managed/http.ts +65 -25
  29. package/server-managed/npm-patch.ts +101 -43
  30. package/server-managed/pull-dependencies.ts +9 -6
  31. package/server-managed/pull-dependency-reviews.ts +20 -11
  32. package/server-managed/repository-dependency-reviews.ts +4 -2
  33. package/server-managed/repository-issues.ts +3 -3
  34. package/server-managed/stasis-dependencies.ts +29 -12
  35. package/out/chunk-6ATPGDDI.js +0 -1
package/out/view.js CHANGED
@@ -1,4 +1,4 @@
1
- import"./chunk-R3NZFXVR.js";import{a as e,b as t,c as n,f as r,g as i,h as a,j as o}from"./chunk-A5A3LEMV.js";import{$b as s,$c as c,Ac as l,Ae as u,Bc as d,Be as f,C as p,Cb as m,Ce as h,Cf as g,D as ee,De as _,Df as te,Eb as ne,Ef as re,Fe as ie,Ff as ae,G as oe,Gb as se,Gd as ce,Ge as le,Gf as ue,H as de,Hd as fe,He as pe,I as v,Ib as me,Id as he,Jb as ge,Jd as _e,K as ve,Kb as ye,Kd as be,L as xe,Lb as Se,Mb as Ce,Mc as we,N as Te,Nb as Ee,Nc as De,Oa as Oe,Ob as ke,P as Ae,Pa as je,Pb as Me,Pd as Ne,Q as Pe,Qa as Fe,Qd as Ie,Qe as Le,R as Re,Ra as ze,Rb as y,Re as Be,S as Ve,Sa as He,Sb as Ue,Sc as We,T as b,Tb as Ge,Tc as Ke,Ub as qe,Uc as Je,V as Ye,Vb as Xe,Vc as Ze,Wb as Qe,Wc as $e,Xb as et,Xc as tt,Ya as nt,Yb as x,Yc as rt,Za as it,Zb as at,Zc as ot,_a as S,_b as st,ab as ct,ac as C,ad as lt,bb as w,bc as ut,bd as dt,c as ft,cb as pt,cc as mt,d as T,db as ht,dc as gt,e as _t,ec as vt,f as yt,fb as bt,fc as xt,gb as St,gc as Ct,h as wt,hc as Tt,i as Et,ia as Dt,ic as Ot,ja as kt,jc as At,k as jt,ka as Mt,kc as Nt,l as Pt,la as Ft,lc as It,m as Lt,ma as Rt,mc as E,me as zt,nc as D,ne as Bt,o as Vt,od as Ht,oe as Ut,p as Wt,pa as Gt,pb as Kt,q as qt,qb as Jt,qe as Yt,r as Xt,rb as Zt,rc as Qt,re as $t,rf as en,s as tn,sb as nn,sc as rn,se as an,sf as on,t as sn,tb as cn,tc as ln,te as O,tf as un,ub as dn,uc as fn,ue as pn,uf as mn,v as hn,vb as gn,vc as _n,ve as vn,vf as yn,w as k,wc as bn,we as xn,wf as Sn,x as A,xc as Cn,xe as wn,xf as j,y as Tn,yc as En,ye as M,yf as Dn,za as On,zc as kn,ze as An,zf as jn}from"./chunk-FUHRMY7R.js";import"./chunk-JCIIBLKR.js";import"./chunk-E3LFSUDJ.js";import"./chunk-JMG5DXII.js";import{d as Mn}from"./chunk-LBJVV6UB.js";import{D as Nn,L as Pn,N as Fn,T as In,Y as Ln,_ as N,b as Rn,ba as zn,ea as Bn,n as Vn,t as Hn,u as Un,v as Wn,x as Gn,y as Kn}from"./chunk-U5C2TNNQ.js";import{h as qn,i as Jn}from"./chunk-WFDXHPT2.js";import"./chunk-NRPC74AM.js";import"./chunk-7BKKYVWR.js";import{f as P}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import"./chunk-VFWMQ3LG.js";import{$ as Yn,G as Xn,H as Zn,P as Qn,Q as $n,S as er,a as F,ca as tr,e as nr,g as I,ga as rr,h as L,ha as ir,i as ar,m as or,na as sr,pa as cr,ra as lr,v as ur,y as dr}from"./chunk-6YGH7BJG.js";import{g as fr}from"./chunk-R3WUYD4F.js";import"./chunk-D6NVKGGG.js";import"./chunk-IYPY47MC.js";import{a as pr,d as mr}from"./chunk-PWFUOLZK.js";import{a as hr,e as gr,f as _r,n as vr,o as yr,u as br,w as xr,y as Sr}from"./chunk-6ATPGDDI.js";import{B as Cr,I as wr,l as Tr}from"./chunk-QRKFPLA4.js";import{d as Er,i as Dr,k as Or,l as kr,r as Ar,x as jr}from"./chunk-74AEKRES.js";import"./chunk-C4Z6ZBXV.js";import{a as R,b as Mr,c as z,g as B,i as Nr,j as V}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var Pr={attach:{title:`Synced triage on report attach`,intro:`have triage from your workspace that disagrees with your local view on`,trailingNote:`Other findings in this report whose chain value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep.`,importedSideLabel:`Apply from chain`,applyButton:`Apply`},chain:{title:`Triage conflict from peer update`,intro:`were changed by a peer (or by another tab) in a way that disagrees with your local triage on`,trailingNote:`Other findings whose remote value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep for each — a "keep current" pick re-publishes your local value to the chain on your next save.`,importedSideLabel:`Apply from chain`,applyButton:`Apply`}};function Fr(){gn(async(e,t,n)=>{let r=Ae(e);try{return await Kt(e,r,Pr[n]??Pr.attach)}catch{let t=e.length;return alert(`${n===`attach`?`A report attach`:`A workspace sync`} had ${t} triage disagreement${t===1?``:`s`} with your local view. Kept your local values because another dialog is open. ${n===`attach`?`Detach and re-attach the report to pick again.`:`Your local values will re-publish to the chain on the next change.`}`),null}})}var Ir=class extends bt{static properties={retry:{type:Boolean},_value:{state:!0}};constructor(){super(),this.retry=!1,this._value=``}_finish(e){this._value=``,super._finish(e)}_onCancel=()=>this._finish(null);_onInput=e=>{this._value=e.target.value};_onSubmit=()=>{let e=this._value??``;e&&this._finish(e)};_onKeydown=e=>{e.key===`Enter`&&(e.preventDefault(),this._onSubmit())};render(){let e=(this._value??``).length>0,t=this.retry?`That password didn't match. Try again, or cancel to leave the workspace unsynced for now.`:`This sync server requires a password before it accepts a new workspace. Enter it to create the workspace on the server.`;return z`<dialog @close="${this._onClose}"><header><h3>Sync server password</h3></header><p class="nwd-intro">${t}</p><input type="password" class="nwd-input" placeholder="Password" autocomplete="off" data-1p-ignore="true" data-lpignore="true" data-bwignore="true" data-form-type="other" name="dv-sync-auth" maxlength="4096" .value="${this._value}" @input="${this._onInput}" @keydown="${this._onKeydown}"><footer class="nwd-actions"><span class="nwd-spacer"></span> <button type="button" @click="${this._onCancel}">Cancel</button> <button type="button" class="primary" ?disabled="${!e}" @click="${this._onSubmit}">${this.retry?`Retry`:`Authenticate`}</button></footer></dialog>`}};customElements.define(`sync-auth-dialog`,Ir);function Lr({retry:e=!1}={}){return St(`sync-auth-dialog`,{retry:!!e})}function Rr(){dn(async({retry:e})=>{try{return await Lr({retry:e})}catch(e){return console.warn(`Sync auth dialog failed to open:`,e),null}})}var zr=`https://triage.space/`,Br=[{hostname:`deepaudit.dev`,pathPrefix:`/`,supportsSync:!0},{hostname:`chalker.github.io`,pathPrefix:`/deepview/`,supportsSync:!1}];function Vr(){for(let e of Br)if(location.hostname===e.hostname&&location.pathname.startsWith(e.pathPrefix))return e;return null}var Hr=[`deepview.triage`,`deepview.triage.pending`],Ur=`deepview.repoUrls`;function Wr(){try{for(let e of Hr)if(localStorage.getItem(e))return!0}catch{return!0}try{let e=localStorage.getItem(Ur);if(e){let t=JSON.parse(e);if(t&&typeof t==`object`&&Object.keys(t).length>0)return!0}}catch{return!0}return!1}async function Gr(){if(Wr())return!0;let e=[];try{e=await Tn()}catch{return!0}if(e.length>0)return!0;try{if(xe().length>0)return!0}catch{return!0}try{return await p()}catch{return!0}}var Kr=class extends V{static properties={supportsSync:{attribute:!1}};createRenderRoot(){return this}constructor(){super(),this.supportsSync=!1}firstUpdated(){let e=this.querySelector(`dialog`);e&&e.showModal();let t=this.querySelector(`button.om-stay`);t&&t.focus()}_finish(e){if(this._settled)return;this._settled=!0;let t=this.querySelector(`dialog`);t&&t.close(),this.dispatchEvent(new CustomEvent(`resolve`,{detail:e}))}_onClose=()=>this._finish(!1);_onStay=()=>this._finish(!1);_onMigrate=()=>this._finish(!0);render(){let e=()=>z`<a class="om-link" href="${zr}" target="_blank" rel="noopener noreferrer">${zr}</a>`;return z`<dialog class="origin-migration-dialog" @close="${this._onClose}"><header class="om-head"><h3>This deepview build has moved</h3><p><code>${location.host}${location.pathname}</code> has moved to ${e()}.</p></header><section class="om-body"><p>Workspaces and reports don't migrate automatically — they live in this origin's browser storage (OPFS where available, localStorage as a fallback) and have to be re-imported on ${e()}.</p>${this.supportsSync?z`<p>For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}. Workspaces that had sync configured will pick their triage state back up from the sync server once you re-import them with the same key.</p><p>For triage attached to loose reports (or as a top-up after re-importing workspaces), call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces.</p>`:z`<p>This build has no sync layer. For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}.</p><p>For triage attached to loose reports, call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces. Reports themselves need to be re-dropped from their original JSON on the new origin.</p>`}</section><footer class="om-actions"><button type="button" class="om-stay" @click="${this._onStay}">Keep editing on ${location.host}</button> <button type="button" class="primary om-go" @click="${this._onMigrate}">Switch to triage.space</button></footer></dialog>`}};customElements.define(`origin-migration-dialog`,Kr);function qr(e){return new Promise(t=>{let n=document.createElement(`origin-migration-dialog`);n.supportsSync=e.supportsSync,n.addEventListener(`resolve`,e=>{n.remove(),t(!!e.detail)}),document.body.append(n)})}async function Jr(){let e=Vr();return e?await Gr()?await qr(e)?(location.assign(zr),!0):!1:(location.replace(zr),!0):!1}var H=null,Yr=!1,Xr=null;function Zr(e){if(!e)return`Could not unlock. Try again.`;switch(e.name??``){case`NotAllowedError`:case`AbortError`:return``;case`SecurityError`:return`The site identity does not match the one this passkey was registered for. If you opened DeepView through a different URL (different subdomain, different port), reload via the original URL.`;case`InvalidStateError`:return`The passkey state on this device is inconsistent. Try reloading the page or removing and re-creating the passkey.`;case`NotSupportedError`:return`This browser does not support the WebAuthn PRF extension this site needs. Try a recent Chrome, Safari, or Edge with a platform authenticator.`;case`NetworkError`:return`A network error prevented the passkey from completing. Check your connection and try again.`;case`UnknownError`:return`The authenticator returned an unknown error. Try again, or use a different passkey.`;default:{let t=e.message??String(e);return t.length>200?t.slice(0,197)+`…`:t}}}function Qr(){if(H)return H;H=document.createElement(`div`),H.id=`lock-overlay`,H.setAttribute(`role`,`dialog`),H.setAttribute(`aria-modal`,`true`),H.setAttribute(`aria-label`,`Unlock DeepView`),Nr(z`<div class="lock-overlay-card"><div class="lock-overlay-icon" aria-hidden="true"><svg viewBox="0 0 32 32" width="40" height="40" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="15" width="18" height="12" rx="1.5"/><path d="M11 15v-4a5 5 0 0 1 10 0v4"/></svg></div><h2 class="lock-overlay-title">DeepView is locked</h2><p class="lock-overlay-body">Your triage data and reports are encrypted with a passkey on this device. Unlock to continue.</p><p class="lock-overlay-error" hidden></p><button type="button" class="lock-overlay-button primary">Unlock with passkey</button><p class="lock-overlay-footer">Lost your passkey? <a href="#" class="lock-overlay-wipe">Wipe local data and start over</a></p></div>`,H);let e=H.querySelector(`button`),t=H.querySelector(`.lock-overlay-error`);return e.addEventListener(`click`,async()=>{if(!Yr&&$r()){Yr=!0,t.hidden=!0,t.textContent=``,e.disabled=!0,e.textContent=`Waiting…`,Xr=new AbortController;try{await Et({signal:Xr.signal})}catch(e){let n=Zr(e);t.textContent=n,t.hidden=!n}finally{Yr=!1,Xr=null,e.disabled=!1,e.textContent=`Unlock with passkey`}}}),H.querySelector(`.lock-overlay-wipe`).addEventListener(`click`,async e=>{if(e.preventDefault(),!Yr&&$r()&&confirm(`Wipe ALL local DeepView data and start over?
1
+ import"./chunk-R3NZFXVR.js";import{a as e,b as t,c as n,f as r,g as i,h as a,j as o}from"./chunk-OAWY4T6R.js";import{$b as s,$c as c,Ac as l,Ae as u,Bc as d,Be as f,C as p,Cb as m,Ce as h,Cf as g,D as ee,De as _,Df as te,Eb as ne,Ef as re,Fe as ie,Ff as ae,G as oe,Gb as se,Gd as ce,Ge as le,Gf as ue,H as de,Hd as fe,He as pe,I as v,Ib as me,Id as he,Jb as ge,Jd as _e,K as ve,Kb as ye,Kd as be,L as xe,Lb as Se,Mb as Ce,Mc as we,N as Te,Nb as Ee,Nc as De,Oa as Oe,Ob as ke,P as Ae,Pa as je,Pb as Me,Pd as Ne,Q as Pe,Qa as Fe,Qd as Ie,Qe as Le,R as Re,Ra as ze,Rb as y,Re as Be,S as Ve,Sa as He,Sb as Ue,Sc as We,T as b,Tb as Ge,Tc as Ke,Ub as qe,Uc as Je,V as Ye,Vb as Xe,Vc as Ze,Wb as Qe,Wc as $e,Xb as et,Xc as tt,Ya as nt,Yb as x,Yc as rt,Za as it,Zb as at,Zc as ot,_a as S,_b as st,ab as ct,ac as C,ad as lt,bb as w,bc as ut,bd as dt,c as ft,cb as pt,cc as mt,d as T,db as ht,dc as gt,e as _t,ec as vt,f as yt,fb as bt,fc as xt,gb as St,gc as Ct,h as wt,hc as Tt,i as Et,ia as Dt,ic as Ot,ja as kt,jc as At,k as jt,ka as Mt,kc as Nt,l as Pt,la as Ft,lc as It,m as Lt,ma as Rt,mc as E,me as zt,nc as D,ne as Bt,o as Vt,od as Ht,oe as Ut,p as Wt,pa as Gt,pb as Kt,q as qt,qb as Jt,qe as Yt,r as Xt,rb as Zt,rc as Qt,re as $t,rf as en,s as tn,sb as nn,sc as rn,se as an,sf as on,t as sn,tb as cn,tc as ln,te as O,tf as un,ub as dn,uc as fn,ue as pn,uf as mn,v as hn,vb as gn,vc as _n,ve as vn,vf as yn,w as k,wc as bn,we as xn,wf as Sn,x as A,xc as Cn,xe as wn,xf as j,y as Tn,yc as En,ye as M,yf as Dn,za as On,zc as kn,ze as An,zf as jn}from"./chunk-SCN2TBP2.js";import"./chunk-JCIIBLKR.js";import"./chunk-E3LFSUDJ.js";import"./chunk-JMG5DXII.js";import{d as Mn}from"./chunk-2F3CYNPZ.js";import{D as Nn,L as Pn,N as Fn,T as In,Y as Ln,_ as N,b as Rn,ba as zn,ea as Bn,n as Vn,t as Hn,u as Un,v as Wn,x as Gn,y as Kn}from"./chunk-2HGKTQ5Q.js";import{h as qn,i as Jn}from"./chunk-WFDXHPT2.js";import"./chunk-NRPC74AM.js";import"./chunk-7BKKYVWR.js";import{f as P}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import"./chunk-VFWMQ3LG.js";import{$ as Yn,G as Xn,H as Zn,P as Qn,Q as $n,S as er,a as F,ca as tr,e as nr,g as I,ga as rr,h as L,ha as ir,i as ar,m as or,na as sr,pa as cr,ra as lr,v as ur,y as dr}from"./chunk-QPGM3DTI.js";import{g as fr}from"./chunk-HETCVNO4.js";import"./chunk-D6NVKGGG.js";import"./chunk-IYPY47MC.js";import{a as pr,d as mr}from"./chunk-PWFUOLZK.js";import{a as hr,e as gr,f as _r,n as vr,o as yr,u as br,w as xr,y as Sr}from"./chunk-4RS3NDOG.js";import{B as Cr,I as wr,l as Tr}from"./chunk-QRKFPLA4.js";import{d as Er,i as Dr,k as Or,l as kr,r as Ar,x as jr}from"./chunk-74AEKRES.js";import"./chunk-C4Z6ZBXV.js";import{a as R,b as Mr,c as z,g as B,i as Nr,j as V}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var Pr={attach:{title:`Synced triage on report attach`,intro:`have triage from your workspace that disagrees with your local view on`,trailingNote:`Other findings in this report whose chain value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep.`,importedSideLabel:`Apply from chain`,applyButton:`Apply`},chain:{title:`Triage conflict from peer update`,intro:`were changed by a peer (or by another tab) in a way that disagrees with your local triage on`,trailingNote:`Other findings whose remote value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep for each — a "keep current" pick re-publishes your local value to the chain on your next save.`,importedSideLabel:`Apply from chain`,applyButton:`Apply`}};function Fr(){gn(async(e,t,n)=>{let r=Ae(e);try{return await Kt(e,r,Pr[n]??Pr.attach)}catch{let t=e.length;return alert(`${n===`attach`?`A report attach`:`A workspace sync`} had ${t} triage disagreement${t===1?``:`s`} with your local view. Kept your local values because another dialog is open. ${n===`attach`?`Detach and re-attach the report to pick again.`:`Your local values will re-publish to the chain on the next change.`}`),null}})}var Ir=class extends bt{static properties={retry:{type:Boolean},_value:{state:!0}};constructor(){super(),this.retry=!1,this._value=``}_finish(e){this._value=``,super._finish(e)}_onCancel=()=>this._finish(null);_onInput=e=>{this._value=e.target.value};_onSubmit=()=>{let e=this._value??``;e&&this._finish(e)};_onKeydown=e=>{e.key===`Enter`&&(e.preventDefault(),this._onSubmit())};render(){let e=(this._value??``).length>0,t=this.retry?`That password didn't match. Try again, or cancel to leave the workspace unsynced for now.`:`This sync server requires a password before it accepts a new workspace. Enter it to create the workspace on the server.`;return z`<dialog @close="${this._onClose}"><header><h3>Sync server password</h3></header><p class="nwd-intro">${t}</p><input type="password" class="nwd-input" placeholder="Password" autocomplete="off" data-1p-ignore="true" data-lpignore="true" data-bwignore="true" data-form-type="other" name="dv-sync-auth" maxlength="4096" .value="${this._value}" @input="${this._onInput}" @keydown="${this._onKeydown}"><footer class="nwd-actions"><span class="nwd-spacer"></span> <button type="button" @click="${this._onCancel}">Cancel</button> <button type="button" class="primary" ?disabled="${!e}" @click="${this._onSubmit}">${this.retry?`Retry`:`Authenticate`}</button></footer></dialog>`}};customElements.define(`sync-auth-dialog`,Ir);function Lr({retry:e=!1}={}){return St(`sync-auth-dialog`,{retry:!!e})}function Rr(){dn(async({retry:e})=>{try{return await Lr({retry:e})}catch(e){return console.warn(`Sync auth dialog failed to open:`,e),null}})}var zr=`https://triage.space/`,Br=[{hostname:`deepaudit.dev`,pathPrefix:`/`,supportsSync:!0},{hostname:`chalker.github.io`,pathPrefix:`/deepview/`,supportsSync:!1}];function Vr(){for(let e of Br)if(location.hostname===e.hostname&&location.pathname.startsWith(e.pathPrefix))return e;return null}var Hr=[`deepview.triage`,`deepview.triage.pending`],Ur=`deepview.repoUrls`;function Wr(){try{for(let e of Hr)if(localStorage.getItem(e))return!0}catch{return!0}try{let e=localStorage.getItem(Ur);if(e){let t=JSON.parse(e);if(t&&typeof t==`object`&&Object.keys(t).length>0)return!0}}catch{return!0}return!1}async function Gr(){if(Wr())return!0;let e=[];try{e=await Tn()}catch{return!0}if(e.length>0)return!0;try{if(xe().length>0)return!0}catch{return!0}try{return await p()}catch{return!0}}var Kr=class extends V{static properties={supportsSync:{attribute:!1}};createRenderRoot(){return this}constructor(){super(),this.supportsSync=!1}firstUpdated(){let e=this.querySelector(`dialog`);e&&e.showModal();let t=this.querySelector(`button.om-stay`);t&&t.focus()}_finish(e){if(this._settled)return;this._settled=!0;let t=this.querySelector(`dialog`);t&&t.close(),this.dispatchEvent(new CustomEvent(`resolve`,{detail:e}))}_onClose=()=>this._finish(!1);_onStay=()=>this._finish(!1);_onMigrate=()=>this._finish(!0);render(){let e=()=>z`<a class="om-link" href="${zr}" target="_blank" rel="noopener noreferrer">${zr}</a>`;return z`<dialog class="origin-migration-dialog" @close="${this._onClose}"><header class="om-head"><h3>This deepview build has moved</h3><p><code>${location.host}${location.pathname}</code> has moved to ${e()}.</p></header><section class="om-body"><p>Workspaces and reports don't migrate automatically — they live in this origin's browser storage (OPFS where available, localStorage as a fallback) and have to be re-imported on ${e()}.</p>${this.supportsSync?z`<p>For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}. Workspaces that had sync configured will pick their triage state back up from the sync server once you re-import them with the same key.</p><p>For triage attached to loose reports (or as a top-up after re-importing workspaces), call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces.</p>`:z`<p>This build has no sync layer. For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}.</p><p>For triage attached to loose reports, call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces. Reports themselves need to be re-dropped from their original JSON on the new origin.</p>`}</section><footer class="om-actions"><button type="button" class="om-stay" @click="${this._onStay}">Keep editing on ${location.host}</button> <button type="button" class="primary om-go" @click="${this._onMigrate}">Switch to triage.space</button></footer></dialog>`}};customElements.define(`origin-migration-dialog`,Kr);function qr(e){return new Promise(t=>{let n=document.createElement(`origin-migration-dialog`);n.supportsSync=e.supportsSync,n.addEventListener(`resolve`,e=>{n.remove(),t(!!e.detail)}),document.body.append(n)})}async function Jr(){let e=Vr();return e?await Gr()?await qr(e)?(location.assign(zr),!0):!1:(location.replace(zr),!0):!1}var H=null,Yr=!1,Xr=null;function Zr(e){if(!e)return`Could not unlock. Try again.`;switch(e.name??``){case`NotAllowedError`:case`AbortError`:return``;case`SecurityError`:return`The site identity does not match the one this passkey was registered for. If you opened DeepView through a different URL (different subdomain, different port), reload via the original URL.`;case`InvalidStateError`:return`The passkey state on this device is inconsistent. Try reloading the page or removing and re-creating the passkey.`;case`NotSupportedError`:return`This browser does not support the WebAuthn PRF extension this site needs. Try a recent Chrome, Safari, or Edge with a platform authenticator.`;case`NetworkError`:return`A network error prevented the passkey from completing. Check your connection and try again.`;case`UnknownError`:return`The authenticator returned an unknown error. Try again, or use a different passkey.`;default:{let t=e.message??String(e);return t.length>200?t.slice(0,197)+`…`:t}}}function Qr(){if(H)return H;H=document.createElement(`div`),H.id=`lock-overlay`,H.setAttribute(`role`,`dialog`),H.setAttribute(`aria-modal`,`true`),H.setAttribute(`aria-label`,`Unlock DeepView`),Nr(z`<div class="lock-overlay-card"><div class="lock-overlay-icon" aria-hidden="true"><svg viewBox="0 0 32 32" width="40" height="40" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="15" width="18" height="12" rx="1.5"/><path d="M11 15v-4a5 5 0 0 1 10 0v4"/></svg></div><h2 class="lock-overlay-title">DeepView is locked</h2><p class="lock-overlay-body">Your triage data and reports are encrypted with a passkey on this device. Unlock to continue.</p><p class="lock-overlay-error" hidden></p><button type="button" class="lock-overlay-button primary">Unlock with passkey</button><p class="lock-overlay-footer">Lost your passkey? <a href="#" class="lock-overlay-wipe">Wipe local data and start over</a></p></div>`,H);let e=H.querySelector(`button`),t=H.querySelector(`.lock-overlay-error`);return e.addEventListener(`click`,async()=>{if(!Yr&&$r()){Yr=!0,t.hidden=!0,t.textContent=``,e.disabled=!0,e.textContent=`Waiting…`,Xr=new AbortController;try{await Et({signal:Xr.signal})}catch(e){let n=Zr(e);t.textContent=n,t.hidden=!n}finally{Yr=!1,Xr=null,e.disabled=!1,e.textContent=`Unlock with passkey`}}}),H.querySelector(`.lock-overlay-wipe`).addEventListener(`click`,async e=>{if(e.preventDefault(),!Yr&&$r()&&confirm(`Wipe ALL local DeepView data and start over?
2
2
 
3
3
  This deletes your encrypted triage, all reports, and the passkey registration on this device. The data CANNOT be recovered after this — there is no backup.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.67",
3
+ "version": "1.0.0-alpha.68",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -1,6 +1,8 @@
1
1
  import { parentPort, workerData } from 'node:worker_threads'
2
2
  import { Buffer } from 'node:buffer'
3
- import { posix } from 'node:path'
3
+ import { createHash } from 'node:crypto'
4
+ import { mkdir, readFile, readdir, rename, rm, stat, statfs, writeFile } from 'node:fs/promises'
5
+ import { join, posix } from 'node:path'
4
6
  import { brotliCompressSync } from 'node:zlib'
5
7
  import { isEvidenceFile } from '@exodus/stasis/audit-corrections'
6
8
  import { buildGitHubBundle, setCacheDir } from '@exodus/stasis/vfs-bundle'
@@ -128,12 +130,13 @@ function buildClientOf(client, note) {
128
130
  // `note` is told what the build log keeps of a build beside its stages: the
129
131
  // directory Stasis builds from (`project`), and each tree it downloads of the
130
132
  // repo (`download`, buildClientOf).
131
- export async function buildStasisBundle({ input, github, token, maxBytes, scopes, cacheDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
133
+ export async function buildStasisBundle({ input, github, token, maxBytes, scopes, cacheDir = null, instanceDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
132
134
  const allowed = path => scopes.some(scope => !scope || path === scope || path.startsWith(scope + '/'))
133
135
  const buildClient = buildClientOf(client, note)
134
136
  // Upstream's disk cache keeps the npm tarballs and version documents, and
135
- // the repo's tree, in `cacheDir`; without one (Vercel), nothing is kept on
136
- // disk. This fresh worker inherits no application credentials but NPM_TOKEN.
137
+ // the repo's tree, in `cacheDir`; without one (Vercel), what it downloads
138
+ // of npm is kept in `instanceDir` (cacheOf), where one is given. This fresh
139
+ // worker inherits no application credentials but NPM_TOKEN.
137
140
  setCacheDir(cacheDir ?? false)
138
141
  progress('build')
139
142
  // Entries stasis.config.json lists are built from its directory, where
@@ -158,7 +161,7 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
158
161
  const { bundle } = await buildGitHubBundle({
159
162
  github, sha: input.commit, ...(input.branch !== undefined && { branch: input.branch }), directory: project || undefined,
160
163
  entries: input.entries.map(entry => posix.relative(project || '.', entry)),
161
- ...options, ...(named && { packageManager }), client: buildClient, ...(cacheDir === null && { cache: false }),
164
+ ...options, ...(named && { packageManager }), client: buildClient, ...await cacheOf(cacheDir, instanceDir),
162
165
  })
163
166
  const directory = bundle.repo?.directory ?? ''
164
167
  progress('scope')
@@ -200,12 +203,61 @@ export function lockfileDependencies(lockfile) {
200
203
  return [...found].toSorted(([a], [b]) => a < b ? -1 : 1).map(([, one]) => one)
201
204
  }
202
205
 
206
+ // The npm tarballs and version documents a build downloads, kept as files in
207
+ // `dir` for the builds after it in this instance, where no cache directory
208
+ // is set (serverless, whose temporary directory lasts as long as its
209
+ // instance): a store Stasis reads and writes in place of its cache, so a
210
+ // bundle's build, a pull request's head and merge base, and the commits
211
+ // after them download each version once. As much as `budget` bytes: found
212
+ // past it, or with less than `spare` bytes left on its disk (Vercel's holds
213
+ // 500 MB), the directory is emptied, and nothing is written past it. A file
214
+ // is written whole or not at all, as what is read is held to its integrity,
215
+ // a mismatch failing the build; one a stopped build left half-written is
216
+ // removed.
217
+ const INSTANCE_KEPT = new Set(['npm/tarballs', 'npm/versions'])
218
+ const INSTANCE_BUDGET = 512 * 1024 * 1024
219
+ const INSTANCE_SPARE = 64 * 1024 * 1024
220
+ export async function instanceCache(dir, budget = INSTANCE_BUDGET, spare = INSTANCE_SPARE) {
221
+ let used = 0, written = 0
222
+ for (const name of await readdir(dir).catch(() => [])) {
223
+ if (name.endsWith('.tmp')) await rm(join(dir, name), { force: true }).catch(() => {})
224
+ else used += (await stat(join(dir, name)).catch(() => null))?.size ?? 0
225
+ }
226
+ const free = await statfs(dir).then(disk => disk.bavail * disk.bsize, () => Infinity)
227
+ if (used > budget || (used > 0 && free < spare)) {
228
+ await rm(dir, { recursive: true, force: true }).catch(() => {})
229
+ used = 0
230
+ }
231
+ await mkdir(dir, { recursive: true }).catch(() => {})
232
+ const pathOf = (kind, name) => join(dir, createHash('sha256').update(`${kind}\0${name}`).digest('hex'))
233
+ return {
234
+ async read(kind, name) {
235
+ const bytes = INSTANCE_KEPT.has(kind) ? await readFile(pathOf(kind, name)).catch(() => null) : null
236
+ if (bytes === null || kind === 'npm/tarballs') return bytes
237
+ try { return JSON.parse(bytes.toString()) } catch { return null }
238
+ },
239
+ async write(kind, name, value) {
240
+ if (!INSTANCE_KEPT.has(kind)) return
241
+ const bytes = value instanceof Uint8Array ? value : Buffer.from(JSON.stringify(value))
242
+ if (used + bytes.length > budget) return
243
+ used += bytes.length
244
+ const path = pathOf(kind, name), tmp = `${path}.${++written}.tmp`
245
+ await writeFile(tmp, bytes).then(() => rename(tmp, path)).catch(() => rm(tmp, { force: true }).catch(() => {}))
246
+ },
247
+ }
248
+ }
249
+
250
+ // Stasis's `cache` option for a build: none with a cache directory set,
251
+ // which it reads and writes; else the instance's own (instanceCache), where
252
+ // it has a directory, and nothing kept where it has none.
253
+ const cacheOf = async (cacheDir, instanceDir) => cacheDir === null ? { cache: instanceDir === null ? false : await instanceCache(instanceDir) } : {}
254
+
203
255
  // What the stasis.config.json at `input.config` has Stasis reach at
204
256
  // `input.commit`, for the repository's dependency review
205
257
  // (stasis-dependencies.ts): the npm versions of the lockfile it builds in
206
258
  // its directory, as `stasis github-bundle --lockfile-only` does, no bundle
207
259
  // serialized; none of a commit with no file there.
208
- export async function buildStasisLockfile({ input, github, token, cacheDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
260
+ export async function buildStasisLockfile({ input, github, token, cacheDir = null, instanceDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
209
261
  const buildClient = buildClientOf(client, note)
210
262
  setCacheDir(cacheDir ?? false)
211
263
  progress('build')
@@ -216,7 +268,7 @@ export async function buildStasisLockfile({ input, github, token, cacheDir = nul
216
268
  await directoryConfig(configText, directory)
217
269
  note('project', { project: directory, configured: true })
218
270
  const { lockfile } = await buildGitHubBundle({ github, sha: input.commit, ...(input.branch !== undefined && { branch: input.branch }), directory: directory || undefined, lockfile: LOCK_FILE, client: buildClient,
219
- ...(cacheDir === null && { cache: false }) })
271
+ ...await cacheOf(cacheDir, instanceDir) })
220
272
  progress('lockfile')
221
273
  if (!lockfile) throw new Error('Stasis built no lockfile of these entries')
222
274
  return lockfileDependencies(lockfile)
@@ -1,7 +1,7 @@
1
1
  import { Buffer } from 'node:buffer'
2
2
  import { createHash, randomUUID } from 'node:crypto'
3
- import { totalmem } from 'node:os'
4
- import { posix } from 'node:path'
3
+ import { tmpdir, totalmem } from 'node:os'
4
+ import { join, posix } from 'node:path'
5
5
  import { Worker } from 'node:worker_threads'
6
6
  import { BUNDLE_BUILD_TIMEOUT_MS, type BundleBuildLeaseStore } from './bundle-build-leases.ts'
7
7
  import { type BundleBuildDiagnostic, type BundleBuildStage, bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
@@ -144,6 +144,10 @@ const MAX_ACTIVE_BUILDS = 1
144
144
  let behind: { yield: () => void; gone: Promise<void> } | null = null
145
145
  // Who builds behind no request, as `active` and the shared lease name it.
146
146
  const LOCKFILE_BUILDER = 'dependency-review'
147
+ // Where builds keep what they download of npm for those after them in this
148
+ // instance, where no cache directory is set, as on Vercel
149
+ // (bundle-build-worker.js instanceCache).
150
+ const INSTANCE_DIR = join(tmpdir(), 'triage-stasis-cache')
147
151
  async function yielded(): Promise<void> {
148
152
  const running = behind
149
153
  if (!running) return
@@ -203,7 +207,8 @@ export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId:
203
207
  // credentials or mutable Stasis state between requests.
204
208
  export function buildRepositoryBundle(userId: string, request: BuildRequest, signal: AbortSignal): Promise<BuiltBundle> {
205
209
  const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, directory: request.input.directory, entryCount: request.input.entries.length }
206
- return runBuild<BuiltBundle & { bytes: Uint8Array }, BuiltBundle>(userId, request, context, signal, message => {
210
+ const asked = { ...request, instanceDir: INSTANCE_DIR }
211
+ return runBuild<BuiltBundle & { bytes: Uint8Array }, BuiltBundle>(userId, asked, context, signal, message => {
207
212
  // A view of the bytes the worker handed over, not a copy of them.
208
213
  const { bytes } = message
209
214
  return { value: { bytes: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), directory: message.directory, filename: message.filename }, logged: { byteSize: bytes.length } }
@@ -218,7 +223,7 @@ export function buildRepositoryBundle(userId: string, request: BuildRequest, sig
218
223
  export async function buildRepositoryLockfile(db: BundleBuildLeaseStore, request: LockfileRequest, signal: AbortSignal): Promise<StasisDependency[]> {
219
224
  if (behind || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
220
225
  const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, config: request.input.config, branch: request.input.branch, lockfileOnly: true }
221
- const asked = { ...request, lockfileOnly: true }
226
+ const asked = { ...request, instanceDir: INSTANCE_DIR, lockfileOnly: true }
222
227
  const yielding = new AbortController()
223
228
  let gone = () => {}
224
229
  behind = { yield: () => yielding.abort(new BundleBuildError(429, 'build-yielded')), gone: new Promise(resolve => { gone = resolve }) }
@@ -40,7 +40,7 @@ const LOCK = 'SELECT pg_advisory_xact_lock(1937006964, 1835101793)'
40
40
  // Whether every version up to the latest is recorded, in one round trip at
41
41
  // a cold start: a database with no versions table yet (undefined_table) has
42
42
  // none. Outside a transaction, so the failed read aborts nothing.
43
- const SCHEMA_VERSIONS = 35
43
+ const SCHEMA_VERSIONS = 36
44
44
  async function currentSchema(db: PgConnection): Promise<boolean> {
45
45
  try {
46
46
  const { rows } = await db.query(`SELECT count(*) AS n FROM managed_schema_version WHERE version BETWEEN 1 AND ${SCHEMA_VERSIONS}`)
@@ -136,6 +136,9 @@ async function migrateFrom12(db: PgConnection): Promise<void> {
136
136
  // The issue a saved one was closed as a duplicate of, none known of those
137
137
  // checked before.
138
138
  await migration(db, 35, 'ALTER TABLE managed_finding_issue ADD COLUMN IF NOT EXISTS duplicate_of_url TEXT')
139
+ // The patch a dependency review's base is of, none of those written
140
+ // before; each author's one draft of a comparison held to it too.
141
+ await migration(db, 36, `ALTER TABLE managed_dependency_review ${addColumns(DEPENDENCY_REVIEW_COLUMNS)}`, DEPENDENCY_REVIEW_INDEXES)
139
142
  }
140
143
 
141
144
  async function initialize(db: PgConnection): Promise<void> {
@@ -24,11 +24,11 @@ const MAX_FORMATTED = 1_000_000
24
24
  const REVIEWS_AT_ONCE = 200
25
25
 
26
26
  // `review` as the hook is given it: each version with the integrity and
27
- // shasum the review keeps of the tarball it read, and the version it is of
28
- // with the patch it is of, where it is a patched one's.
27
+ // shasum the review keeps of the tarball it read, and the patch it is of,
28
+ // where it is a patched one's.
29
29
  function entryOf(review: DependencyReview): DependencyReviewEntry {
30
30
  return { ecosystem: 'npm', old: review.basePackage === null ? null : { name: review.basePackage, version: review.baseVersion ?? '', integrity: review.baseIntegrity ?? '',
31
- ...review.baseShasum ? { shasum: review.baseShasum } : {} },
31
+ ...review.baseShasum ? { shasum: review.baseShasum } : {}, ...review.basePatchHash ? { patchHash: review.basePatchHash } : {} },
32
32
  new: { name: review.package, version: review.version, integrity: review.integrity, ...review.shasum ? { shasum: review.shasum } : {},
33
33
  ...review.patchHash ? { patchHash: review.patchHash } : {} },
34
34
  status: review.status!, coverage: review.coverage === 'full' ? 'full' : 'partial', comment: review.comment,
@@ -68,18 +68,19 @@ export function withFormatted<T extends DependencyReview>(reviewed: ReviewedDepe
68
68
 
69
69
  // Those of `reviews` `user` published of the versions `told` adds, by their
70
70
  // ids, each with the versions it is of, as its lockfiles lock each: of its
71
- // version, of an integrity it is locked with and of its patch, whole or
72
- // compared with a version it was (pull-dependency-reviews.ts reviewsOf,
73
- // comparedWith).
71
+ // version, of an integrity it is locked with and of its patch, whole,
72
+ // compared with another package's version, or compared with a version it was
73
+ // (pull-dependency-reviews.ts reviewsOf, comparedWith), or, `any`, with any
74
+ // version of its package.
74
75
  interface Own { review: PublishedReview; pkgs: LockedPackage[] }
75
- function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string): Map<string, Own> {
76
+ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string, any: boolean): Map<string, Own> {
76
77
  // Theirs by the version they are of, each version probed once.
77
78
  const theirs = reviewsByVersion(reviews.filter(review => review.id !== undefined && review.reviewer === user))
78
79
  const mine = new Map<string, Own>()
79
80
  if (theirs.size === 0) return mine
80
81
  for (const pkg of told.lockfiles.flatMap(dir => 'added' in dir ? dir.added : [])) {
81
82
  for (const review of reviewsOf(pkg, theirs)) {
82
- if (comparedWith(review, pkg, pkg.was ?? [])) (mine.get(review.id!) ?? mine.set(review.id!, { review, pkgs: [] }).get(review.id!)!).pkgs.push(pkg)
83
+ if (comparedWith(review, pkg, any ? 'any' : pkg.was ?? [])) (mine.get(review.id!) ?? mine.set(review.id!, { review, pkgs: [] }).get(review.id!)!).pkgs.push(pkg)
83
84
  }
84
85
  }
85
86
  return mine
@@ -94,11 +95,13 @@ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: str
94
95
  // it with the same verdict, as copying it would but repeat them: by their
95
96
  // latest of it, which tells where they stand there (pull-dependency-
96
97
  // reviews.ts stancesOf), an older one of that verdict not counting. A
97
- // version `lookup` fails to answer of keeps its review.
98
+ // version `lookup` fails to answer of keeps its review. Where the host reads
99
+ // reviews of comments (`parseComments`), what a review was compared with is
100
+ // its to weigh, so one compared with any version is given.
98
101
  export async function formattedPull(reviewed: ReviewedDependencies | null, db: Pick<DependencyReviewStore, 'listOwnDependencyReviewsById'>, user: string,
99
102
  told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = []): Promise<string | null> {
100
103
  if (!reviewed?.formatDependencyReviews || !state) return null
101
- const mine = ownOfPull(told, state.reviews, user)
104
+ const mine = ownOfPull(told, state.reviews, user, reviewed.parseComments !== undefined)
102
105
  if (mine.size === 0) return null
103
106
  const { passed } = await askReviewed(reviewed.lookup, new Map([...mine.values()].flatMap(({ pkgs }) => pkgs.map(askedOf))))
104
107
  const there = reviewsByVersion(commented.filter(review => review.reviewer === user))
@@ -6,10 +6,11 @@ import { REVIEW_VERDICTS, type ReviewSummary, type ReviewVerdict, allowedReviewV
6
6
 
7
7
  // A review is of a version, as npm's registry has it, by its integrity; of
8
8
  // it as pnpm patches it (`patchHash`, the patch's hash as a lockfile names
9
- // it), where it is patched; and compared with a version (its base), or none.
9
+ // it), where it is patched; and compared with a version (its base), or none,
10
+ // that as a patch changes it too (`basePatchHash`), where named so.
10
11
  export interface ReviewContext {
11
12
  ecosystem: 'npm'; package: string; version: string; integrity: string; patchHash: string | null
12
- basePackage: string | null; baseVersion: string | null; baseIntegrity: string | null
13
+ basePackage: string | null; baseVersion: string | null; baseIntegrity: string | null; basePatchHash: string | null
13
14
  }
14
15
  // The shasums (sha1s, in hex) of the tarballs a review reads, its version's
15
16
  // and its base's, where npm tells them: each held, with its integrity, to the
@@ -67,7 +68,8 @@ CREATE TABLE IF NOT EXISTS managed_dependency_review (
67
68
  base_package TEXT NOT NULL, base_version TEXT NOT NULL, base_integrity TEXT NOT NULL,
68
69
  time INTEGER NOT NULL, revision INTEGER NOT NULL, published_at INTEGER, revoked_at INTEGER, files TEXT,
69
70
  status TEXT CHECK (status IN ('accept', 'accept-with-nits', 'request-changes', 'reject')), comment TEXT NOT NULL DEFAULT '',
70
- shasum TEXT NOT NULL DEFAULT '', base_shasum TEXT NOT NULL DEFAULT '', patch_hash TEXT NOT NULL DEFAULT '', patch_source TEXT
71
+ shasum TEXT NOT NULL DEFAULT '', base_shasum TEXT NOT NULL DEFAULT '', patch_hash TEXT NOT NULL DEFAULT '', patch_source TEXT,
72
+ base_patch_hash TEXT NOT NULL DEFAULT ''
71
73
  ) STRICT;
72
74
  CREATE INDEX IF NOT EXISTS managed_dependency_review_context_idx
73
75
  ON managed_dependency_review(ecosystem, package, version, integrity, base_package, base_version, base_integrity, time);
@@ -87,22 +89,23 @@ CREATE INDEX IF NOT EXISTS managed_dependency_review_team_idx ON managed_depende
87
89
  `
88
90
  // The columns added since the table was, for a database that has it already.
89
91
  export const DEPENDENCY_REVIEW_COLUMNS = [['shasum', "TEXT NOT NULL DEFAULT ''"], ['base_shasum', "TEXT NOT NULL DEFAULT ''"],
90
- ['patch_hash', "TEXT NOT NULL DEFAULT ''"], ['patch_source', 'TEXT']] as const
91
- // Each author's one draft of a comparison, its patch's too, made once those
92
- // columns are: the index held to it before patches were reviewed gone.
92
+ ['patch_hash', "TEXT NOT NULL DEFAULT ''"], ['patch_source', 'TEXT'], ['base_patch_hash', "TEXT NOT NULL DEFAULT ''"]] as const
93
+ // Each author's one draft of a comparison, its patches' too, made once those
94
+ // columns are: those held to it before patches, then its base's, were reviewed gone.
93
95
  export const DEPENDENCY_REVIEW_INDEXES = `
94
96
  DROP INDEX IF EXISTS managed_dependency_review_unpublished_idx;
95
- CREATE UNIQUE INDEX IF NOT EXISTS managed_dependency_review_draft_idx
96
- ON managed_dependency_review(user_id, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity)
97
+ DROP INDEX IF EXISTS managed_dependency_review_draft_idx;
98
+ CREATE UNIQUE INDEX IF NOT EXISTS managed_dependency_review_drafts_idx
99
+ ON managed_dependency_review(user_id, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity, base_patch_hash)
97
100
  WHERE published_at IS NULL;`
98
- const values = (c: ReviewContext) => [c.ecosystem, c.package, c.version, c.integrity, c.patchHash ?? '', c.basePackage ?? '', c.baseVersion ?? '', c.baseIntegrity ?? '']
101
+ const values = (c: ReviewContext) => [c.ecosystem, c.package, c.version, c.integrity, c.patchHash ?? '', c.basePackage ?? '', c.baseVersion ?? '', c.baseIntegrity ?? '', c.basePatchHash ?? '']
99
102
  const targetWhere = 'ecosystem = ? AND package = ? AND version = ? AND integrity = ? AND patch_hash = ?'
100
- const contextWhere = `${targetWhere} AND base_package = ? AND base_version = ? AND base_integrity = ?`
103
+ const contextWhere = `${targetWhere} AND base_package = ? AND base_version = ? AND base_integrity = ? AND base_patch_hash = ?`
101
104
  // Its author by the login they reviewed as, and by the name the app's user
102
105
  // has now (null once they are none, or have none), as the lists show them.
103
106
  const columns = `id, user_id AS user, user_login AS userLogin, (SELECT n.name FROM managed_user n WHERE n.id = user_id) AS userName, ecosystem, package, version, integrity,
104
107
  NULLIF(patch_hash, '') AS patchHash, NULLIF(base_package, '') AS basePackage, NULLIF(base_version, '') AS baseVersion, NULLIF(base_integrity, '') AS baseIntegrity,
105
- NULLIF(shasum, '') AS shasum, NULLIF(base_shasum, '') AS baseShasum, patch_source AS patchSource,
108
+ NULLIF(base_patch_hash, '') AS basePatchHash, NULLIF(shasum, '') AS shasum, NULLIF(base_shasum, '') AS baseShasum, patch_source AS patchSource,
106
109
  time, revision, published_at AS publishedAt, revoked_at AS revokedAt, files, status, comment`
107
110
  const conflict = () => { throw new ManagedMutationError(409, 'review-conflict') }
108
111
  // What a review keeps of the bytes it read: its tarballs' shasums, and where
@@ -225,7 +228,7 @@ async function listContext(db: ManagedSql, context: ReviewContext, user: string,
225
228
  AND (user_id = ? OR (published_at IS NOT NULL AND EXISTS (
226
229
  SELECT 1 FROM managed_dependency_review_team rt JOIN managed_team t ON t.id = rt.team_id JOIN managed_user u ON u.id = ?
227
230
  WHERE rt.review_id = r.id AND ${reviewsIn(false)})))
228
- ORDER BY time, id`).all(...values(context).slice(0, allBases ? 5 : 8), user, user)
231
+ ORDER BY time, id`).all(...values(context).slice(0, allBases ? 5 : 9), user, user)
229
232
  return expandReviews(db, rows, user)
230
233
  }
231
234
 
@@ -329,8 +332,8 @@ export function dependencyReviewMethods(db: ManagedSql): DependencyReviewStore {
329
332
  if (await unpublished()) return conflict()
330
333
  const next = randomUUID()
331
334
  await db.prepare(`INSERT INTO managed_dependency_review
332
- (id, user_id, user_login, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity, shasum, base_shasum, patch_source, time, revision)
333
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)`).run(next, user.id, user.login, ...values(context), ...shasums(tarballs), now)
335
+ (id, user_id, user_login, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity, base_patch_hash, shasum, base_shasum, patch_source, time, revision)
336
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)`).run(next, user.id, user.login, ...values(context), ...shasums(tarballs), now)
334
337
  return next
335
338
  }
336
339
  if (change.action === 'start') {
@@ -115,7 +115,7 @@
115
115
  // reads them there | 400/401/404
116
116
  // GET /api/npm/package?name=&version= → a published version's manifest and files | 400/401/404/413/429/502
117
117
  // GET /api/npm/package?name=&version=&patchHash=&patchRepoId=&patchCommit=&patchPath= → its files as a pnpm patch of a
118
- // repository the reader reads all of changes them | 400/401/403/404/409/413/422/429/502
118
+ // repository the reader reads all of changes them, its path looked for where left out, as kept where all three are | 400/401/403/404/409/413/422/429/502
119
119
  // GET /api/npm/versions?name= → its dist-tags, versions, when each was published and its first was, and whether a team lists its scope | 400/401/404/429/502
120
120
  // GET /api/npm/download?name=&version= → its tarball | 400/401/404/413/429/502
121
121
  // GET /api/npm/stats?name= → its downloads over the last year and its GitHub repository's figures | 400/401/404/429/502
@@ -229,7 +229,7 @@ import { ManagedMutationError, reportReferenceSnapshot } from './management.ts'
229
229
  import { BundleBuildError, buildRepositoryBundle, buildRepositoryLockfile, parseBundleBuild, withBundleBuildLease } from './bundle-build.ts'
230
230
  import { NpmPackageError, type NpmReader, type NpmVersionDocument, type NpmVersionStore, VERSION_KEPT_MS, canReadPrivateNpm, npmFileRows, npmPublishTime, npmScopesCount, npmTarballFilename, readNpmVersion, readNpmVersions, readTogether } from './npm-packages.ts'
231
231
  import { loadNpmFiles, loadNpmPackageBody, loadNpmTarball } from './npm-loads.ts'
232
- import { type ReadPatch, type RequestedPatch, patchedFiles, readPatch, requestedPatch, withPatchFiles } from './npm-patch.ts'
232
+ import { type ReadPatch, type RequestedPatch, foundPatch, keptPatch, patchedFiles, readPatch, requestedPatch, withPatchFiles } from './npm-patch.ts'
233
233
  import { type RepositoryCodeKept, loadRepositoryCodeBody, repositoryCodeFits, repositoryCodeKept } from './repository-code.ts'
234
234
  import { type ChangesStore, type CommitChanges, type CommitTree, TREES_READ, changesAsked, changesWithin, directoryFiles, repositoryChanges, repositoryTree } from './repository-changes.ts'
235
235
  import { COAUTHORS_READ, coauthorsOf } from './commit-coauthors.ts'
@@ -238,7 +238,8 @@ import { type AllHeads, type HistoryCommit, type HistoryPages, MAX_HISTORY_PAGE,
238
238
  import { type KnownMerges, type SquashedPull, type Squashes, squashedPulls } from './repository-squashes.ts'
239
239
  import { AGENTS_READ_VERSION, type AuthoredCommit, type BranchTip, type BranchTips, COMMITS_CURSOR, type CommitPulls, repositoryAgents } from './repository-agents.ts'
240
240
  import { DEPENDENCIES_LABEL, ISSUES_CURSOR, ISSUES_READ_VERSION, OPEN_PULLS_READ, OPEN_PULLS_SIZES, repositoryIssues, repositoryItem, repositoryLabel, repositoryOpenPulls } from './repository-issues.ts'
241
- import { type GithubAsked, type ListedLockfile, type LockfileRead, type LockfileStore, MAX_LOCKED, PULL_DEPENDENCIES_READ, type PullCommits, type PullDependencies,
241
+ import { type DirectoryDependencies, type GithubAsked, type ListedLockfile, type LockfileRead, type LockfileStore, MAX_LOCKED, PULL_DEPENDENCIES_READ, type PullCommits,
242
+ type PullDependencies,
242
243
  type PullDependencyStore, type PullRefs, lockfileFormat, pullDependenciesAt, pullRefs } from './pull-dependencies.ts'
243
244
  import { eachOf } from './queue.ts'
244
245
  import { lockedAt, lockedIn, lockfilesAt } from './commit-lockfiles.ts'
@@ -2438,18 +2439,42 @@ async function readWholeRepositoryOf<T>(deps: ManagedHttpDeps, access: WholeAcce
2438
2439
  // The patch `patch` names (npm-patch.ts), and where it was read (`source`),
2439
2440
  // read of the whole of its repository as readWholeRepositoryOf reads it,
2440
2441
  // with its reader's own GitHub access, and held to its hash: as kept, for
2441
- // good (patchStore), else with that access checked again after; else why it
2442
- // was refused. Its failing to read or to apply throws.
2442
+ // good (patchStore), else with that access checked again after; one named
2443
+ // without its path looked for among its commit's patches (foundPatch), of a
2444
+ // repository whose dependency review is on alone; one named by its hash
2445
+ // alone as kept alone (keptPatchOf); else why it was refused. Its failing to
2446
+ // read or to apply throws.
2443
2447
  async function npmPatchOf(deps: ManagedHttpDeps, cookie: string | undefined, patch: RequestedPatch): Promise<ReadPatch | Refusal> {
2448
+ if (!('repoId' in patch)) return keptPatchOf(deps, cookie, patch.hash)
2444
2449
  const access = await wholeRepositoryAccess(deps, cookie, patch.repoId)
2445
2450
  if ('error' in access) return access
2446
- const { repoId } = access.repo
2451
+ const { repoId } = access.repo, { hash, commit, path } = patch
2447
2452
  const read = await readWholeRepositoryOf(deps, access, async (fullName, token) => {
2448
- const asked: GithubAsked = { github: false }
2449
- return { value: await readPatch(fullName, token, { ...patch, repoId }, patchStore(deps.db, deps.config.debug), asked), kept: !asked.github }
2453
+ const asked: GithubAsked = { github: false }, kept = patchStore(deps.db, deps.config.debug)
2454
+ const listed = async () => (await deps.db.repoDependencyReview(repoId))?.enabled ? repositoryTree(fullName, token, commit, commitTreeKept(deps, repoId)) : null
2455
+ const value = path === undefined ? await foundPatch(fullName, token, { hash, repoId, commit }, kept, listed, asked)
2456
+ : await readPatch(fullName, token, { hash, repoId, commit, path }, kept, asked)
2457
+ return { value, kept: !asked.github }
2450
2458
  }, () => wholeRepositoryAccess(deps, cookie, repoId))
2451
2459
  return 'error' in read ? read : read.value
2452
2460
  }
2461
+ // The patch `hash` names as kept, of a connected repository its reader may
2462
+ // read all of, the first of theirs that keeps it (npm-patch.ts keptPatch), as
2463
+ // readWholeRepositoryOf reads what is kept, GitHub asked for none of it; else
2464
+ // `404 patch-not-kept`, as one never read here, or read only of a repository
2465
+ // they can't read all of, is none of theirs.
2466
+ async function keptPatchOf(deps: ManagedHttpDeps, cookie: string | undefined, hash: string): Promise<ReadPatch | Refusal> {
2467
+ const s = await readSession(deps.config, deps.db, cookie, Date.now())
2468
+ if (s == null) return refusal(401, 'unauthenticated')
2469
+ if (!roleAtLeast(s.user.role, 'view')) return refusal(403, 'forbidden')
2470
+ const grants = await repositoryGrants(deps, s.user)
2471
+ const readable = grants.repos.flatMap(repo => { const whole = wholeAccessIn(grants, s.user, repo.repoId); return 'error' in whole ? [] : [whole] })
2472
+ const held = await keptPatch(readable.map(one => one.repo.repoId), hash, patchStore(deps.db, deps.config.debug))
2473
+ const access = held && readable.find(one => one.repo.repoId === held.source.repoId)
2474
+ if (!access) return refusal(404, 'patch-not-kept')
2475
+ const read = await readWholeRepositoryOf(deps, access, () => Promise.resolve({ value: held, kept: true }), () => wholeRepositoryAccess(deps, cookie, access.repo.repoId))
2476
+ return 'error' in read ? read : read.value
2477
+ }
2453
2478
  // The patch a request's fields name, as npm-patch.ts requestedPatch takes them.
2454
2479
  const patchFields = (field: (key: string) => unknown) => requestedPatch({ hash: field('patchHash'), repoId: field('patchRepoId'), commit: field('patchCommit'), path: field('patchPath') })
2455
2480
 
@@ -2582,7 +2607,7 @@ async function pullDependencyAnswer(deps: ManagedHttpDeps, fullName: string, tok
2582
2607
  const kept = pullDependencyKept(deps, repoId)
2583
2608
  const reading: { told?: PullDependencies } = {}
2584
2609
  // With the branches they are of, where told, kept with them.
2585
- const answered = commits ? { value: { baseRef: commits.baseRef, headRef: commits.headRef, commits: `${commits.base}...${commits.head}` }, kept: true }
2610
+ const answered = commits ? { value: { baseRef: commits.baseRef, headRef: commits.headRef, fork: commits.fork, commits: `${commits.base}...${commits.head}` }, kept: true }
2586
2611
  : await keptAnswer(deps, `${repoId}\0pull-commits\0${PULL_DEPENDENCIES_READ}\0${number}`, async () => {
2587
2612
  const { told, ...read } = await pullDependenciesAt(fullName, token, number, kept)
2588
2613
  reading.told = told
@@ -2600,7 +2625,7 @@ async function pullDependencyAnswer(deps: ManagedHttpDeps, fullName: string, tok
2600
2625
  // not marked as its package manager's alone (withReach).
2601
2626
  const asked: GithubAsked = { github: false }
2602
2627
  const scoped = setting?.enabled ? withReach(heldDependencies({ ...pulled, lockfiles: [...pulled.lockfiles,
2603
- ...await stasisDirectories(deps, fullName, token, repoId, setting.lockfiles, pulled.base, pulled.head, asked, pullRefs(answered.value.baseRef, answered.value.headRef))] },
2628
+ ...await stasisDirectories(deps, fullName, token, repoId, setting.lockfiles, pulled.base, pulled.head, asked, pullRefs(answered.value.baseRef, answered.value.headRef, answered.value.fork))] },
2604
2629
  setting.lockfiles)) : pulled
2605
2630
  const now = review ? await deps.db.repoDependencyReviewState(repoId, user.id, reviewedPackages(scoped)) : null
2606
2631
  // Its review by the lockfiles they were told by, though they have changed
@@ -2635,9 +2660,12 @@ async function pullDependencyAnswer(deps: ManagedHttpDeps, fullName: string, tok
2635
2660
  // path (stasis-dependencies.ts stasisDirectory): at `head`, against `base`
2636
2661
  // where one is given. None is waited for: one not built yet is built behind
2637
2662
  // the answer (stasisReader), told the branch its commit is of where `refs`
2638
- // names it, a pull request's head's, or its base's, which holds `base`.
2663
+ // names it, a pull request's head's, or its base's, which holds `base`. An
2664
+ // open pull request's head that is a fork's (`refs.fork`) is no commit of
2665
+ // the repository's own, which Stasis refuses: nothing is built for it.
2639
2666
  function stasisDirectories(deps: ManagedHttpDeps, fullName: string, token: string, repoId: number, scope: LockfileScope, base: string | null, head: string,
2640
- asked: GithubAsked, refs: PullRefs = {}) {
2667
+ asked: GithubAsked, refs: PullRefs = {}): Promise<DirectoryDependencies[]> {
2668
+ if (refs.fork) return Promise.resolve(stasisConfigs(scope).map(config => ({ paths: [config], error: 'stasis-failed', detail: 'commit-not-own' })))
2641
2669
  const reader = stasisReader(deps), reads = lockfileKept(deps, repoId)
2642
2670
  return Promise.all(stasisConfigs(scope).map(config => stasisDirectory(config, base, head,
2643
2671
  commit => reader.read({ repoId, fullName }, token, commit, config, commit === head ? refs.headRef : refs.baseRef),
@@ -2701,7 +2729,8 @@ async function branchDependencyAnswer(deps: ManagedHttpDeps, fullName: string, t
2701
2729
  ...await stasisDirectories(deps, fullName, token, repoId, setting.lockfiles, null, head, asked)] }, read.lockfiles)
2702
2730
  const now = await deps.db.repoDependencyReviewState(repoId, user.id, reviewedPackages(locked))
2703
2731
  if (!now) return { value: { head, review: null }, kept: !asked.github }
2704
- const told = await withPatchFiles(locked, repoId, fullName, token, patchStore(deps.db, deps.config.debug), asked)
2732
+ // Every patch there kept, those its lockfiles name the files of too, for a link to find by its hash alone.
2733
+ const told = await withPatchFiles(locked, repoId, fullName, token, patchStore(deps.db, deps.config.debug), asked, { keepNamed: true })
2705
2734
  // Told by the lockfiles it held to as they were read, though they have
2706
2735
  // changed since.
2707
2736
  const state = { ...now, lockfiles: setting.lockfiles }
@@ -2894,10 +2923,10 @@ type OpenPullsPage = { items?: unknown; more?: unknown; after?: unknown; commits
2894
2923
  // Each open pull request's base's and head's commits a page of them names,
2895
2924
  // into `commits` by its number.
2896
2925
  function pageCommits(page: OpenPullsPage, commits: Map<number, PullCommits>) {
2897
- for (const pull of Array.isArray(page.commits) ? page.commits as { number?: unknown; base?: unknown; head?: unknown; baseRef?: unknown; headRef?: unknown }[] : []) {
2898
- const { number, base, head, baseRef, headRef } = pull ?? {}
2926
+ for (const pull of Array.isArray(page.commits) ? page.commits as { number?: unknown; base?: unknown; head?: unknown; baseRef?: unknown; headRef?: unknown; fork?: unknown }[] : []) {
2927
+ const { number, base, head, baseRef, headRef, fork } = pull ?? {}
2899
2928
  if (Number.isSafeInteger(number) && typeof base === 'string' && SHA.test(base) && typeof head === 'string' && SHA.test(head)) {
2900
- commits.set(number as number, { base, head, ...pullRefs(baseRef, headRef) })
2929
+ commits.set(number as number, { base, head, ...pullRefs(baseRef, headRef, fork) })
2901
2930
  }
2902
2931
  }
2903
2932
  }
@@ -4939,7 +4968,8 @@ function reviewChange(res: ServerResponse, body: Record<string, unknown>): Revie
4939
4968
  // its files as its patch changes them, the patch read as kept, else where the
4940
4969
  // request says (`patchRepoId`, `patchCommit`, `patchPath`), of the whole of a
4941
4970
  // repository its reader reads (npmPatchOf), the review keeping where it was
4942
- // read. Access to both versions is rechecked before returning or saving annotations.
4971
+ // read; and a patched base's (`basePatchHash`) as its patch, kept, changes
4972
+ // them. Access to both versions is rechecked before returning or saving annotations.
4943
4973
  async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, params: URLSearchParams): Promise<void> {
4944
4974
  const method = req.method ?? 'GET'
4945
4975
  if (!['GET', 'POST'].includes(method)) { send405(res, 'GET, POST'); return }
@@ -4957,17 +4987,19 @@ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps:
4957
4987
  const baseVersion = field('baseVersion') ?? null
4958
4988
  const baseIntegrity = field('baseIntegrity') ?? null
4959
4989
  const patchHash = field('patchHash') ?? null
4990
+ const basePatchHash = field('basePatchHash') ?? null
4960
4991
  // Where its patch is, where it names that: its hash alone where only listed.
4961
4992
  const patch = patchFields(field)
4962
4993
  const validIntegrity = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && value.length <= 1024
4963
4994
  if (field('ecosystem') !== 'npm' || !isNpmPackageName(name) || !isNpmPackageSpec(version) || !validIntegrity(integrity)
4964
4995
  || (basePackage !== null || baseVersion !== null || baseIntegrity !== null)
4965
4996
  && (!isNpmPackageName(basePackage) || !isNpmPackageSpec(baseVersion) || !validIntegrity(baseIntegrity))
4966
- || (patchHash !== null && !isPatchHash(patchHash)) || patch === 'invalid') {
4997
+ || (patchHash !== null && !isPatchHash(patchHash)) || patch === 'invalid' || (basePatchHash !== null && (!isPatchHash(basePatchHash) || basePackage === null))) {
4967
4998
  sendJson(res, 400, { error: 'bad-review-context' }); return
4968
4999
  }
4969
5000
  const context: ReviewContext = { ecosystem: 'npm', package: name, version, integrity, patchHash: patchHash as string | null,
4970
- basePackage: basePackage as string | null, baseVersion: baseVersion as string | null, baseIntegrity: baseIntegrity as string | null }
5001
+ basePackage: basePackage as string | null, baseVersion: baseVersion as string | null, baseIntegrity: baseIntegrity as string | null,
5002
+ basePatchHash: basePatchHash as string | null }
4971
5003
  let change: ReviewChange | null = null
4972
5004
  if (mutation) {
4973
5005
  change = reviewChange(res, body)
@@ -4994,6 +5026,8 @@ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps:
4994
5026
  const reading = change && change.action !== 'revoke'
4995
5027
  const patchRead = reading && patch ? await npmPatchOf(deps, cookie, patch) : null
4996
5028
  if (patchRead && 'error' in patchRead) { sendRefusal(res, patchRead); return }
5029
+ const basePatchRead = reading && basePatchHash ? await npmPatchOf(deps, cookie, { hash: basePatchHash as string }) : null
5030
+ if (basePatchRead && 'error' in basePatchRead) { sendRefusal(res, basePatchRead); return }
4997
5031
  const loads = reading ? [doc, ...base ? [base] : []].map(loadNpmFiles) : []
4998
5032
  let tarballs: ReviewedTarballs | undefined
4999
5033
  try {
@@ -5002,7 +5036,8 @@ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps:
5002
5036
  tarballs = { shasum: doc.dist.shasum, baseShasum: base?.dist.shasum ?? null, ...patchRead ? { patch: patchRead.source } : {} }
5003
5037
  }
5004
5038
  if (change?.action === 'publish' || change?.action === 'save') {
5005
- const maps = files.map((list, at) => new Map<string, unknown>(npmFileRows(at === 0 && patchRead ? patchedFiles(list, patchRead.files) : list)
5039
+ const patchOf = [patchRead, basePatchRead]
5040
+ const maps = files.map((list, at) => new Map<string, unknown>(npmFileRows(patchOf[at] ? patchedFiles(list, patchOf[at].files) : list)
5006
5041
  .map(([path, size, text, digest]) => [path, text ?? { format: 'digest', size, digest }])))
5007
5042
  const after = maps[0]!, before = maps[1] ?? new Map<string, unknown>()
5008
5043
  const diff = computeBundleDiff(before, after, () => '.')
@@ -5126,9 +5161,12 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
5126
5161
  const diffed = path === NPM_RENAME_DIFF_PATH && params.has('path') ? renameDiffRequest(params) : null
5127
5162
  if (path === NPM_RENAME_DIFF_PATH && params.has('path') && !diffed) { sendJson(res, 400, { error: 'bad-file' }); return }
5128
5163
  // The patch a patched version's files and comparison are of, where named
5129
- // (`patchHash`, `patchRepoId`, `patchCommit`, `patchPath`), as Review reads them.
5164
+ // (`patchHash`, `patchRepoId`, `patchCommit`, `patchPath`), as Review reads them;
5165
+ // and the one a comparison's other version is of, by its hash alone, as kept (`otherPatchHash`).
5130
5166
  const patch = patchFields(key => params.get(key))
5131
- if (patch === 'invalid' || (params.has('patchHash') && !patch) || (patch && path !== NPM_PACKAGE_PATH && path !== NPM_COMPARISON_PATH)) {
5167
+ const otherPatch = params.has('otherPatchHash') ? requestedPatch({ hash: params.get('otherPatchHash') }) : null
5168
+ if (patch === 'invalid' || (patch && path !== NPM_PACKAGE_PATH && path !== NPM_COMPARISON_PATH)
5169
+ || otherPatch === 'invalid' || (otherPatch && (path !== NPM_COMPARISON_PATH || otherSpec === '(empty)'))) {
5132
5170
  sendJson(res, 400, { error: 'bad-patch' }); return
5133
5171
  }
5134
5172
  const reader = await npmReader(deps, cookie, otherName === name ? [name] : [name, otherName], { handed: true })
@@ -5255,18 +5293,20 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
5255
5293
  // Overview reads beside them (comparison.ts): the version shown against
5256
5294
  // the one compared with, or `(empty)`, none, as Review reads a first
5257
5295
  // version; as `patch` changes its files, where named, the patch read
5258
- // first (npmPatchOf). Read of both, each package's access checked again
5259
- // once worked out.
5296
+ // first (npmPatchOf), and `otherPatch` the other's. Read of both, each
5297
+ // package's access checked again once worked out.
5260
5298
  if (path === NPM_COMPARISON_PATH) {
5261
5299
  const old = otherSpec === '(empty)' ? null : await otherDoc()
5262
5300
  const patched = patch ? await npmPatchOf(deps, cookie, patch) : null
5263
5301
  if (patched && 'error' in patched) { sendRefusal(res, patched); return }
5302
+ const oldPatched = otherPatch ? await npmPatchOf(deps, cookie, otherPatch) : null
5303
+ if (oldPatched && 'error' in oldPatched) { sendRefusal(res, oldPatched); return }
5264
5304
  dropIdle(res)
5265
5305
  const loads = [doc, ...old ? [old] : []].map(loadNpmFiles)
5266
5306
  let body
5267
5307
  try {
5268
5308
  const [files, oldFiles] = await Promise.all(loads.map(load => load.result))
5269
- body = await comparisonBody(old ? npmComparedSide(old.dist.integrity, oldFiles!) : emptySide(),
5309
+ body = await comparisonBody(old ? npmComparedSide(old.dist.integrity, oldPatched ? patchedFiles(oldFiles!, oldPatched.files) : oldFiles!) : emptySide(),
5270
5310
  npmComparedSide(doc.dist.integrity, patched ? patchedFiles(files!, patched.files) : files!))
5271
5311
  } finally { for (const load of loads) load.release() }
5272
5312
  const current = await npmReader(deps, cookie, otherName === name ? [name] : [name, otherName])