@preventive/triage 1.0.0-alpha.83 → 1.0.0-alpha.85

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 (37) hide show
  1. package/common/npm-token.d.ts +2 -0
  2. package/common/npm-token.js +14 -0
  3. package/out/activity.js +2 -2
  4. package/out/{chunk-PXHEOOK4.js → chunk-7I6SZIJU.js} +1 -1
  5. package/out/{chunk-L5BLCHQD.js → chunk-EZ62FJ5T.js} +44 -44
  6. package/out/{chunk-LVVIDDT6.js → chunk-YU3IUQY6.js} +1 -1
  7. package/out/{chunk-C27LVCIE.js → chunk-ZJDDTEL2.js} +1 -1
  8. package/out/client-managed.js +28 -30
  9. package/out/compare.js +1 -1
  10. package/out/dialogs.js +1 -1
  11. package/out/graph.js +1 -1
  12. package/out/index.html +3 -3
  13. package/out/scan.js +1 -1
  14. package/out/view.css +1 -1
  15. package/out/view.js +1 -1
  16. package/package.json +6 -2
  17. package/risk/npm/registry.js +4 -5
  18. package/server-managed/bundle-build-worker.js +1 -1
  19. package/server-managed/bundle-build.ts +10 -10
  20. package/server-managed/db-methods.ts +6 -1
  21. package/server-managed/http.ts +62 -16
  22. package/server-managed/npm-kept.ts +9 -0
  23. package/server-managed/npm-loads.ts +6 -6
  24. package/server-managed/npm-packages.ts +6 -6
  25. package/server-managed/pulse-walk.ts +164 -0
  26. package/server-managed/repository-history.ts +18 -2
  27. package/server-managed/repository-pulse.ts +5 -73
  28. package/server-managed/repository-risk-assess.ts +63 -2
  29. package/server-managed/repository-risk-caches.ts +19 -0
  30. package/server-managed/repository-risk-kept.ts +86 -0
  31. package/server-managed/repository-risk-read.ts +45 -9
  32. package/server-managed/repository-risk.ts +59 -68
  33. package/server-managed/stasis-dependencies.ts +66 -16
  34. package/server-managed/team-app-summaries.ts +2 -1
  35. package/server-managed/team-app.ts +12 -6
  36. package/server-managed/team-reports.ts +4 -3
  37. /package/out/{chunk-LFPRRRJE.js → chunk-ULI2BIWN.js} +0 -0
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-C27LVCIE.js";import{$a as s,$b as c,$c as l,A as u,Ab as d,Ac as f,B as p,Bb as m,Bc as h,Cb as g,Cc as ee,Db as te,Dc as ne,E as re,Eb as ie,Eg as ae,F as oe,Fb as se,Ff as ce,Fg as le,G as ue,Gb as de,Ge as fe,Gf as pe,Gg as me,Hg as he,I as ge,Ib as _e,Ig as ve,J as ye,Jb as be,Jg as xe,Kb as Se,Kg as Ce,L as we,La as Te,Lb as Ee,Lg as De,Ma as Oe,Mb as ke,Mg as _,N as Ae,Na as je,Nb as Me,Ng as Ne,O as Pe,Oa as Fe,Ob as Ie,Oc as Le,Og as Re,P as ze,Pa as Be,Pb as Ve,Pc as He,Q as Ue,R as v,Rb as We,Rg as Ge,Sb as Ke,Sg as qe,T as Je,Tb as Ye,Tg as Xe,Ub as Ze,Uc as Qe,Ug as $e,Vb as et,Vc as tt,Vf as y,Vg as nt,Wb as rt,Wc as it,Xa as at,Xb as ot,Xc as st,Yb as b,Yc as ct,Zb as lt,Zc as ut,_a as dt,_b as ft,_c as pt,a as mt,ab as ht,ac as gt,ad as _t,af as vt,b as x,bb as yt,bc as bt,bf as xt,c as St,cb as Ct,cc as wt,cf as Tt,d as Et,db as Dt,dc as Ot,de as kt,eb as At,ec as jt,ed as Mt,ef as Nt,f as Pt,fc as Ft,fd as It,fe as Lt,ff as Rt,g as zt,ga as Bt,gc as Vt,gd as Ht,ge as Ut,gf as Wt,ha as Gt,hc as Kt,he as qt,hf as S,i as Jt,ia as Yt,ic as Xt,ie as Zt,if as Qt,j as $t,ja as en,jb as tn,jc as nn,jf as rn,k as an,ka as on,kc as sn,kf as cn,lb as ln,lc as un,lf as dn,m as fn,mc as C,mf as pn,n as mn,na as hn,nb as gn,ne as _n,nf as vn,o as yn,ob as bn,of as xn,p as Sn,pb as Cn,pf as wn,q as Tn,qb as En,qe as Dn,qf as On,r as kn,rb as An,rc as jn,rf as Mn,sb as Nn,sc as Pn,sf as Fn,t as In,tb as Ln,td as Rn,u as w,ud as zn,uf as Bn,v as T,vc as Vn,vf as Hn,w as Un,wa as Wn,wc as E,wf as Gn,xc as Kn,yc as qn,zc as Jn}from"./chunk-L5BLCHQD.js";import"./chunk-A4BBBHQU.js";import"./chunk-6WMQVUT2.js";import"./chunk-VYYUMYVW.js";import"./chunk-7HP2VYIC.js";import"./chunk-N57OWFKY.js";import"./chunk-7YFJUT2P.js";import"./chunk-PXK7EU4V.js";import{d as Yn}from"./chunk-XHYX3Q34.js";import{$ as Xn,A as Zn,B as Qn,G as $n,O as er,Q as tr,W as nr,d as rr,ga as D,ja as ir,la as ar,q as or,w as sr,x as cr,y as lr}from"./chunk-V4U7URJF.js";import{f as ur,g as dr}from"./chunk-KP2XM324.js";import"./chunk-DUASGS2O.js";import"./chunk-NRPC74AM.js";import"./chunk-7BKKYVWR.js";import{f as O}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import{$ as fr,G as pr,H as mr,P as hr,Q as gr,S as _r,a as k,ca as vr,e as yr,g as A,ga as br,h as j,ha as xr,i as Sr,n as Cr,na as wr,pa as Tr,sa as Er,w as Dr,z as Or}from"./chunk-LFPRRRJE.js";import{g as kr}from"./chunk-CE2FMDK3.js";import"./chunk-74JZTGTO.js";import"./chunk-IYPY47MC.js";import{d as Ar,i as jr,k as Mr,l as Nr,t as Pr,z as Fr}from"./chunk-G5JKKNZF.js";import{a as Ir,d as Lr}from"./chunk-PWFUOLZK.js";import"./chunk-C4Z6ZBXV.js";import{a as Rr,e as zr,f as Br,p as Vr,q as Hr,v as Ur,x as Wr,z as Gr}from"./chunk-ZQQALNFP.js";import{B as Kr,I as qr,h as Jr,l as Yr}from"./chunk-QRKFPLA4.js";import{a as M,b as Xr,c as N,g as P,i as Zr,j as F}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var Qr={importedSideLabel:`Apply from chain`,applyButton:`Apply`},$r={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.`,...Qr},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.`,...Qr}};function ei(){Ln(async(e,t,n)=>{let r=Ae(e);try{return await gn(e,r,$r[n]??$r.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 ti=class extends Dt{static properties={_value:{state:!0}};static secrets={_value:``};constructor(){super(),this._value=``}_onInput=e=>{this._value=e.target.value};_onSubmit=()=>{this._value&&this._finish(this._value)};_onKeydown=tn(this._onSubmit);render(){return N`<dialog @close="${this._onClose}"><header><h3>Sync server password</h3></header><p class="nwd-intro">${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.`}</p>${ln({name:`dv-sync-auth`,maxlength:4096,placeholder:`Password`,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="${!this._value}" @click="${this._onSubmit}">${this.retry?`Retry`:`Authenticate`}</button></footer></dialog>`}};customElements.define(`sync-auth-dialog`,ti);function ni({retry:e=!1}={}){return At(`sync-auth-dialog`,{retry:!!e})}function ri(){Nn(async({retry:e})=>{try{return await ni({retry:e})}catch(e){return console.warn(`Sync auth dialog failed to open:`,e),null}})}var ii=`https://triage.space/`,ai=[{hostname:`deepaudit.dev`,pathPrefix:`/`,supportsSync:!0},{hostname:`chalker.github.io`,pathPrefix:`/deepview/`,supportsSync:!1}];function oi(){return ai.find(e=>location.hostname===e.hostname&&location.pathname.startsWith(e.pathPrefix))??null}var si=[`deepview.triage`,`deepview.triage.pending`],ci=`deepview.repoUrls`;function li(){try{if(si.some(e=>localStorage.getItem(e)))return!0;let e=localStorage.getItem(ci);if(!e)return!1;let t=JSON.parse(e);return!!(t&&typeof t==`object`&&Object.keys(t).length>0)}catch{return!0}}async function ui(){if(li())return!0;let e=[];try{e=await Un()}catch{return!0}if(e.length>0)return!0;try{if(ye().length>0)return!0}catch{return!0}try{return await u()}catch{return!0}}var di=class extends F{static properties={supportsSync:{attribute:!1}};createRenderRoot(){return this}constructor(){super(),this.supportsSync=!1}firstUpdated(){this.querySelector(`dialog`)?.showModal(),this.querySelector(`button.om-stay`)?.focus()}_finish(e){this._settled||(this._settled=!0,this.querySelector(`dialog`)?.close(),this.dispatchEvent(new CustomEvent(`resolve`,{detail:e})))}_onStay=()=>this._finish(!1);_onMigrate=()=>this._finish(!0);render(){let e=()=>N`<a class="om-link" href="${ii}" target="_blank" rel="noopener noreferrer">${ii}</a>`;return N`<dialog class="origin-migration-dialog" @close="${this._onStay}"><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?N`<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>`:N`<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`,di);function fi(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 pi(){let e=oi();return e?await ui()?await fi(e)?(location.assign(ii),!0):!1:(location.replace(ii),!0):!1}var I=null,mi=!1,hi=null,gi={NotAllowedError:``,AbortError:``,SecurityError:`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.`,InvalidStateError:`The passkey state on this device is inconsistent. Try reloading the page or removing and re-creating the passkey.`,NotSupportedError:`This browser does not support the WebAuthn PRF extension this site needs. Try a recent Chrome, Safari, or Edge with a platform authenticator.`,NetworkError:`A network error prevented the passkey from completing. Check your connection and try again.`,UnknownError:`The authenticator returned an unknown error. Try again, or use a different passkey.`};function _i(e){if(!e)return`Could not unlock. Try again.`;let t=e.name??``;if(Object.hasOwn(gi,t))return gi[t];let n=e.message??String(e);return n.length>200?n.slice(0,197)+`…`:n}function vi(){if(I)return I;I=document.createElement(`div`),I.id=`lock-overlay`,I.setAttribute(`role`,`dialog`),I.setAttribute(`aria-modal`,`true`),I.setAttribute(`aria-label`,`Unlock DeepView`),Zr(N`<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>`,I);let e=I.querySelector(`button`),t=I.querySelector(`.lock-overlay-error`);return e.addEventListener(`click`,async()=>{if(!mi&&yi()){mi=!0,t.hidden=!0,t.textContent=``,e.disabled=!0,e.textContent=`Waiting…`,hi=new AbortController;try{await zt({signal:hi.signal})}catch(e){let n=_i(e);t.textContent=n,t.hidden=!n}finally{mi=!1,hi=null,e.disabled=!1,e.textContent=`Unlock with passkey`}}}),I.querySelector(`.lock-overlay-wipe`).addEventListener(`click`,async e=>{if(e.preventDefault(),!mi&&yi()&&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-ZJDDTEL2.js";import{$a as s,$b as c,$c as l,A as u,Ab as d,Ac as f,B as p,Bb as m,Bc as h,Cb as g,Cc as ee,Db as te,Dc as ne,E as re,Eb as ie,Eg as ae,F as oe,Fb as se,Ff as ce,Fg as le,G as ue,Gb as de,Ge as fe,Gf as pe,Gg as me,Hg as he,I as ge,Ib as _e,Ig as ve,J as ye,Jb as be,Jg as xe,Kb as Se,Kg as Ce,L as we,La as Te,Lb as Ee,Lg as De,Ma as Oe,Mb as ke,Mg as _,N as Ae,Na as je,Nb as Me,Ng as Ne,O as Pe,Oa as Fe,Ob as Ie,Oc as Le,Og as Re,P as ze,Pa as Be,Pb as Ve,Pc as He,Q as Ue,R as v,Rb as We,Rg as Ge,Sb as Ke,Sg as qe,T as Je,Tb as Ye,Tg as Xe,Ub as Ze,Uc as Qe,Ug as $e,Vb as et,Vc as tt,Vf as y,Vg as nt,Wb as rt,Wc as it,Xa as at,Xb as ot,Xc as st,Yb as b,Yc as ct,Zb as lt,Zc as ut,_a as dt,_b as ft,_c as pt,a as mt,ab as ht,ac as gt,ad as _t,af as vt,b as x,bb as yt,bc as bt,bf as xt,c as St,cb as Ct,cc as wt,cf as Tt,d as Et,db as Dt,dc as Ot,de as kt,eb as At,ec as jt,ed as Mt,ef as Nt,f as Pt,fc as Ft,fd as It,fe as Lt,ff as Rt,g as zt,ga as Bt,gc as Vt,gd as Ht,ge as Ut,gf as Wt,ha as Gt,hc as Kt,he as qt,hf as S,i as Jt,ia as Yt,ic as Xt,ie as Zt,if as Qt,j as $t,ja as en,jb as tn,jc as nn,jf as rn,k as an,ka as on,kc as sn,kf as cn,lb as ln,lc as un,lf as dn,m as fn,mc as C,mf as pn,n as mn,na as hn,nb as gn,ne as _n,nf as vn,o as yn,ob as bn,of as xn,p as Sn,pb as Cn,pf as wn,q as Tn,qb as En,qe as Dn,qf as On,r as kn,rb as An,rc as jn,rf as Mn,sb as Nn,sc as Pn,sf as Fn,t as In,tb as Ln,td as Rn,u as w,ud as zn,uf as Bn,v as T,vc as Vn,vf as Hn,w as Un,wa as Wn,wc as E,wf as Gn,xc as Kn,yc as qn,zc as Jn}from"./chunk-EZ62FJ5T.js";import"./chunk-A4BBBHQU.js";import"./chunk-6WMQVUT2.js";import"./chunk-VYYUMYVW.js";import"./chunk-7HP2VYIC.js";import"./chunk-N57OWFKY.js";import"./chunk-7YFJUT2P.js";import"./chunk-PXK7EU4V.js";import{d as Yn}from"./chunk-XHYX3Q34.js";import{$ as Xn,A as Zn,B as Qn,G as $n,O as er,Q as tr,W as nr,d as rr,ga as D,ja as ir,la as ar,q as or,w as sr,x as cr,y as lr}from"./chunk-V4U7URJF.js";import{f as ur,g as dr}from"./chunk-KP2XM324.js";import"./chunk-DUASGS2O.js";import"./chunk-NRPC74AM.js";import"./chunk-7BKKYVWR.js";import{f as O}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import{$ as fr,G as pr,H as mr,P as hr,Q as gr,S as _r,a as k,ca as vr,e as yr,g as A,ga as br,h as j,ha as xr,i as Sr,n as Cr,na as wr,pa as Tr,sa as Er,w as Dr,z as Or}from"./chunk-ULI2BIWN.js";import{g as kr}from"./chunk-CE2FMDK3.js";import"./chunk-74JZTGTO.js";import"./chunk-IYPY47MC.js";import{d as Ar,i as jr,k as Mr,l as Nr,t as Pr,z as Fr}from"./chunk-G5JKKNZF.js";import{a as Ir,d as Lr}from"./chunk-PWFUOLZK.js";import"./chunk-C4Z6ZBXV.js";import{a as Rr,e as zr,f as Br,p as Vr,q as Hr,v as Ur,x as Wr,z as Gr}from"./chunk-ZQQALNFP.js";import{B as Kr,I as qr,h as Jr,l as Yr}from"./chunk-QRKFPLA4.js";import{a as M,b as Xr,c as N,g as P,i as Zr,j as F}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var Qr={importedSideLabel:`Apply from chain`,applyButton:`Apply`},$r={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.`,...Qr},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.`,...Qr}};function ei(){Ln(async(e,t,n)=>{let r=Ae(e);try{return await gn(e,r,$r[n]??$r.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 ti=class extends Dt{static properties={_value:{state:!0}};static secrets={_value:``};constructor(){super(),this._value=``}_onInput=e=>{this._value=e.target.value};_onSubmit=()=>{this._value&&this._finish(this._value)};_onKeydown=tn(this._onSubmit);render(){return N`<dialog @close="${this._onClose}"><header><h3>Sync server password</h3></header><p class="nwd-intro">${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.`}</p>${ln({name:`dv-sync-auth`,maxlength:4096,placeholder:`Password`,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="${!this._value}" @click="${this._onSubmit}">${this.retry?`Retry`:`Authenticate`}</button></footer></dialog>`}};customElements.define(`sync-auth-dialog`,ti);function ni({retry:e=!1}={}){return At(`sync-auth-dialog`,{retry:!!e})}function ri(){Nn(async({retry:e})=>{try{return await ni({retry:e})}catch(e){return console.warn(`Sync auth dialog failed to open:`,e),null}})}var ii=`https://triage.space/`,ai=[{hostname:`deepaudit.dev`,pathPrefix:`/`,supportsSync:!0},{hostname:`chalker.github.io`,pathPrefix:`/deepview/`,supportsSync:!1}];function oi(){return ai.find(e=>location.hostname===e.hostname&&location.pathname.startsWith(e.pathPrefix))??null}var si=[`deepview.triage`,`deepview.triage.pending`],ci=`deepview.repoUrls`;function li(){try{if(si.some(e=>localStorage.getItem(e)))return!0;let e=localStorage.getItem(ci);if(!e)return!1;let t=JSON.parse(e);return!!(t&&typeof t==`object`&&Object.keys(t).length>0)}catch{return!0}}async function ui(){if(li())return!0;let e=[];try{e=await Un()}catch{return!0}if(e.length>0)return!0;try{if(ye().length>0)return!0}catch{return!0}try{return await u()}catch{return!0}}var di=class extends F{static properties={supportsSync:{attribute:!1}};createRenderRoot(){return this}constructor(){super(),this.supportsSync=!1}firstUpdated(){this.querySelector(`dialog`)?.showModal(),this.querySelector(`button.om-stay`)?.focus()}_finish(e){this._settled||(this._settled=!0,this.querySelector(`dialog`)?.close(),this.dispatchEvent(new CustomEvent(`resolve`,{detail:e})))}_onStay=()=>this._finish(!1);_onMigrate=()=>this._finish(!0);render(){let e=()=>N`<a class="om-link" href="${ii}" target="_blank" rel="noopener noreferrer">${ii}</a>`;return N`<dialog class="origin-migration-dialog" @close="${this._onStay}"><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?N`<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>`:N`<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`,di);function fi(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 pi(){let e=oi();return e?await ui()?await fi(e)?(location.assign(ii),!0):!1:(location.replace(ii),!0):!1}var I=null,mi=!1,hi=null,gi={NotAllowedError:``,AbortError:``,SecurityError:`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.`,InvalidStateError:`The passkey state on this device is inconsistent. Try reloading the page or removing and re-creating the passkey.`,NotSupportedError:`This browser does not support the WebAuthn PRF extension this site needs. Try a recent Chrome, Safari, or Edge with a platform authenticator.`,NetworkError:`A network error prevented the passkey from completing. Check your connection and try again.`,UnknownError:`The authenticator returned an unknown error. Try again, or use a different passkey.`};function _i(e){if(!e)return`Could not unlock. Try again.`;let t=e.name??``;if(Object.hasOwn(gi,t))return gi[t];let n=e.message??String(e);return n.length>200?n.slice(0,197)+`…`:n}function vi(){if(I)return I;I=document.createElement(`div`),I.id=`lock-overlay`,I.setAttribute(`role`,`dialog`),I.setAttribute(`aria-modal`,`true`),I.setAttribute(`aria-label`,`Unlock DeepView`),Zr(N`<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>`,I);let e=I.querySelector(`button`),t=I.querySelector(`.lock-overlay-error`);return e.addEventListener(`click`,async()=>{if(!mi&&yi()){mi=!0,t.hidden=!0,t.textContent=``,e.disabled=!0,e.textContent=`Waiting…`,hi=new AbortController;try{await zt({signal:hi.signal})}catch(e){let n=_i(e);t.textContent=n,t.hidden=!n}finally{mi=!1,hi=null,e.disabled=!1,e.textContent=`Unlock with passkey`}}}),I.querySelector(`.lock-overlay-wipe`).addEventListener(`click`,async e=>{if(e.preventDefault(),!mi&&yi()&&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.83",
3
+ "version": "1.0.0-alpha.85",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -205,6 +205,7 @@
205
205
  "server-managed/repository-squashes.ts",
206
206
  "server-managed/repository-issues.ts",
207
207
  "server-managed/repository-pulse.ts",
208
+ "server-managed/pulse-walk.ts",
208
209
  "server-managed/repository-pulls.ts",
209
210
  "server-managed/listed-activity.ts",
210
211
  "server-managed/repository-stamp.ts",
@@ -215,6 +216,7 @@
215
216
  "server-managed/repository-risk.ts",
216
217
  "server-managed/repository-risk-assess.ts",
217
218
  "server-managed/repository-risk-caches.ts",
219
+ "server-managed/repository-risk-kept.ts",
218
220
  "server-managed/repository-risk-audit.ts",
219
221
  "server-managed/repository-risk-read.ts",
220
222
  "server-managed/repository-risk-stasis.ts",
@@ -298,6 +300,8 @@
298
300
  "common/github-issue-labels.js",
299
301
  "common/github-issue-labels.d.ts",
300
302
  "common/gzip.js",
303
+ "common/npm-token.d.ts",
304
+ "common/npm-token.js",
301
305
  "common/pretty-json.js",
302
306
  "common/pretty-kinds.js",
303
307
  "common/pretty-print.d.ts",
@@ -464,7 +468,7 @@
464
468
  "@preventive/publishers": "^1.1.0",
465
469
  "@preventive/report": "^1.0.1",
466
470
  "@preventive/sourcemap": "1.0.0-alpha.1",
467
- "@preventive/upstream": "^1.12.0",
471
+ "@preventive/upstream": "^1.13.1",
468
472
  "css-tree": "^3.2.1",
469
473
  "oxc-minify": "^0.159.0",
470
474
  "oxc-parser": "^0.152.0",
@@ -22,8 +22,8 @@
22
22
  // days, `{ start, end, days }`, or `{ none: true }` where npm counts none.
23
23
  //
24
24
  // The package assessed is asked for as upstream asks, with the npm token the
25
- // environment has for a scoped one (PREVENTIVE_MEASURES_NPM_TOKEN,
26
- // STASIS_NPM_TOKEN or NPM_TOKEN), so a private one can be read; its
25
+ // environment has for a scoped one (npm-token.js npmTokenFor), so a private
26
+ // one can be read; its
27
27
  // dependencies' public facts and downloads with none. A caller may ask for
28
28
  // packages' documents (`packument`) and versions' tarballs (`tarball`)
29
29
  // itself, as the managed server does, within the bounds it holds every read
@@ -36,6 +36,7 @@
36
36
  import { advisories } from '@preventive/upstream/advisories.js'
37
37
  import { getTarball } from '@preventive/upstream/npm.js'
38
38
  import { compareVersions, satisfies, validRange } from '@preventive/upstream/semver.js'
39
+ import { npmTokenFor } from '../../common/npm-token.js'
39
40
  import { npmVersionManifest } from './manifest.js'
40
41
  import { npmAlias } from './specs.js'
41
42
  import { npmPlaceholder } from './malware.js'
@@ -76,8 +77,6 @@ const plainObject = value => Boolean(value) && typeof value === 'object' && !Arr
76
77
 
77
78
  // A scoped name in a downloads API path, its slash escaped.
78
79
  const encoded = name => name.replace('/', '%2f')
79
- const token = () => typeof process === 'undefined' ? null
80
- : ['PREVENTIVE_MEASURES_NPM_TOKEN', 'STASIS_NPM_TOKEN', 'NPM_TOKEN'].map(key => process.env[key]).find(Boolean) ?? null
81
80
 
82
81
  // A value kept under `type` and `key`, else `ask`ed and kept; one `fresh`
83
82
  // says is stale asked again.
@@ -129,7 +128,7 @@ async function askNpm(url, headers, limit, what, { signal }) {
129
128
  // caller's (`packument`) where it gives one, else risk's own.
130
129
  function packageDocument(name, context, authorized) {
131
130
  if (context.packument) return context.packument(name, { authorized, signal: context.signal })
132
- const secret = authorized && name.startsWith('@') ? token() : null
131
+ const secret = authorized && name.startsWith('@') ? npmTokenFor(name) : null
133
132
  return askNpm(`${REGISTRY}/${name}`, secret ? { authorization: `Bearer ${secret}` } : {}, PACKUMENT_BYTES, name, context)
134
133
  }
135
134
 
@@ -147,7 +147,7 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
147
147
  // Upstream's disk cache keeps the npm tarballs and version documents, and
148
148
  // the repo's tree, in `cacheDir`; without one (Vercel), what it downloads
149
149
  // of npm is kept in `instanceDir` (cacheOf), where one is given. This fresh
150
- // worker inherits no application credentials but NPM_TOKEN.
150
+ // worker inherits no application credentials but the npm tokens (workerEnv).
151
151
  setCacheDir(cacheDir ?? false)
152
152
  progress('build')
153
153
  // Entries stasis.config.json lists are built from its directory, where
@@ -3,6 +3,7 @@ import { createHash, randomUUID } from 'node:crypto'
3
3
  import { tmpdir, totalmem } from 'node:os'
4
4
  import { join, posix } from 'node:path'
5
5
  import { Worker } from 'node:worker_threads'
6
+ import { isNpmTokenName } from '../common/npm-token.js'
6
7
  import { BUNDLE_BUILD_TIMEOUT_MS, type BundleBuildLeaseStore } from './bundle-build-leases.ts'
7
8
  import { type BundleBuildDiagnostic, type BundleBuildStage, bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
8
9
  import type { BundleBuildConditions } from './db-methods.ts'
@@ -124,8 +125,7 @@ interface BuiltBundle { bytes: Buffer; directory: string; filename: string }
124
125
  interface BuildRequest {
125
126
  input: BundleBuildInput; github: string; token: string | null; maxBytes: number; scopes: (string | null)[]
126
127
  // Upstream's disk cache for what a build fetches (setCacheDir), or null for
127
- // none, as on Vercel. Resolved here: the worker's env holds NPM_TOKEN and
128
- // VERCEL_ENV alone.
128
+ // none, as on Vercel. Resolved here, as the worker's env is workerEnv's.
129
129
  cacheDir: string | null
130
130
  }
131
131
  // A version a Stasis lockfile holds, as the worker tells it in place of a
@@ -203,6 +203,13 @@ export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId:
203
203
  }
204
204
  }
205
205
 
206
+ // The npm tokens, for private scoped packages, and VERCEL_ENV, by which Stasis
207
+ // skips oxc-parser's raw transfer on Vercel; no other credential.
208
+ export function workerEnv(env: NodeJS.ProcessEnv = process.env): Record<string, string> {
209
+ const passed = Object.entries(env).filter((entry): entry is [string, string] => isNpmTokenName(entry[0]) && Boolean(entry[1]))
210
+ return Object.fromEntries(env['VERCEL_ENV'] === undefined ? passed : [...passed, ['VERCEL_ENV', env['VERCEL_ENV']]])
211
+ }
212
+
206
213
  // Parsing repositories and compressing bundles stays off the HTTP event loop.
207
214
  // Cap concurrent builds, terminate disconnected/timed-out work, and share no
208
215
  // credentials or mutable Stasis state between requests.
@@ -269,15 +276,8 @@ async function runBuild<M, T>(owner: string, request: { token: string | null },
269
276
  try {
270
277
  workerUrl = new URL('./bundle-build-worker.js', import.meta.url)
271
278
  log('started')
272
- // Upstream reads NPM_TOKEN from the env for scoped packages, which npm
273
- // answers with 404 when private and asked without it. Stasis reads
274
- // VERCEL_ENV, set or not as here, to parse without oxc-parser's raw
275
- // transfer on Vercel, whose functions can't reserve its 6 GiB buffer.
276
- // Nothing else passes.
277
- const npmToken = process.env['NPM_TOKEN'], vercelEnv = process.env['VERCEL_ENV']
278
- const env = { ...(npmToken ? { NPM_TOKEN: npmToken } : {}), ...(vercelEnv === undefined ? {} : { VERCEL_ENV: vercelEnv }) }
279
279
  worker = new Worker(workerUrl, {
280
- workerData: { ...request, type: 'managed-bundle-build' }, env, execArgv: [], resourceLimits: { maxOldGenerationSizeMb: heapLimitMib },
280
+ workerData: { ...request, type: 'managed-bundle-build' }, env: workerEnv(), execArgv: [], resourceLimits: { maxOldGenerationSizeMb: heapLimitMib },
281
281
  })
282
282
  const running = worker
283
283
  return await new Promise((resolve, reject) => {
@@ -368,6 +368,8 @@ export interface UserTeamReport {
368
368
  repoFullName: string | null
369
369
  repoDirectory: string
370
370
  cacheKey: string
371
+ // The bundle it is linked to, where that is one of the team's.
372
+ bundleId?: string
371
373
  }
372
374
  export interface UserTeamBundle {
373
375
  visible: boolean
@@ -702,6 +704,8 @@ function userTeams(teams: UserTeamRows['teams'], scopes: UserTeamRows['scopes'],
702
704
  const bundlesByTeam = Map.groupBy(bundles, b => b.teamId)
703
705
  return teams.map((t) => {
704
706
  const teamScopes = scopes.filter(scope => scope.teamId === t.id)
707
+ // A report's bundle, named where it is one of the team's own.
708
+ const teamBundles = new Set((bundlesByTeam.get(t.id) ?? []).map(b => b.id))
705
709
  return {
706
710
  id: t.id, slug: t.slug, name: t.name,
707
711
  ...teamIcon(t),
@@ -711,7 +715,8 @@ function userTeams(teams: UserTeamRows['teams'], scopes: UserTeamRows['scopes'],
711
715
  repos: teamScopes.map(scope => ({ repoId: scope.repoId, fullName: scope.fullName, path: scope.path || null }))
712
716
  .toSorted((a, b) => a.fullName.localeCompare(b.fullName) || (a.path ?? '').localeCompare(b.path ?? '')),
713
717
  reports: (reportsByTeam.get(t.id) ?? []).map(r => ({ id: r.id, slug: r.slug, filename: r.filename, visible: r.visible === 1,
714
- analyzer: r.analyzer, repoFullName: r.repoFullName, repoDirectory: r.repoDirectory, cacheKey: reportCatalogKey(r, r.role, links) })),
718
+ analyzer: r.analyzer, repoFullName: r.repoFullName, repoDirectory: r.repoDirectory, cacheKey: reportCatalogKey(r, r.role, links),
719
+ ...r.bundleId !== null && teamBundles.has(r.bundleId) ? { bundleId: r.bundleId } : {} })),
715
720
  bundles: (bundlesByTeam.get(t.id) ?? []).map(b => ({ id: b.id, slug: b.slug, integrity: b.integrity, filename: b.filename, visible: b.visible === 1,
716
721
  kind: b.kind, byteSize: b.byteSize, repoId: b.repoId, repoDirectory: b.repoDirectory, repoFullName: b.repoFullName, provenance: b.provenance })),
717
722
  }
@@ -162,8 +162,8 @@ import { pipeline } from 'node:stream/promises'
162
162
  import { setTimeout as delay } from 'node:timers/promises'
163
163
  import { type KeptStore, REPOSITORY_READ_KEPT_MS, authoredCommitStore, branchTipStore, bundleValidationStore, codeHeadStore, codeTreeStore, commitPullStore, githubTagStore, historyChangeStore, historyPageStore, historySquashStore, historyTreeStore,
164
164
  issueListStore, lockfileReadStore,
165
- npmDeltaStore, npmPublishTimeStore, npmVersionDeltaStore, npmVersionStore, ownKeptPrunes, patchStore, privateVersionDeltaStore, pullDependencyStore, pullListStore, repositoryReadStore,
166
- reviewBaselineStore, riskLineStore,
165
+ npmDeltaStore, npmPublishTimeStore, npmVersionDeltaStore, npmVersionStore, ownKeptPrunes, patchStore, privateVersionDeltaStore, pullDependencyStore, pullListStore, pulseWalkStore, repositoryReadStore,
166
+ reviewBaselineStore, riskKeptStore, riskLineStore,
167
167
  scanReadStore, stasisDependencyStore, teamDependencyStore } from './npm-kept.ts'
168
168
  import { plainObject } from './npm-manifest.ts'
169
169
  import { type NpmDelta, countedDeltas, npmDelta, versionDeltaKey } from './npm-delta.ts'
@@ -214,9 +214,11 @@ import type { ConnectedRepo } from './github-app.ts'
214
214
  import { canAddAnyPublicRepository, canAddRepositories, passesPublicRepositorySafeguard } from './repository-policy.ts'
215
215
  import { RepositoryDiscovery } from './repository-discovery.ts'
216
216
  import { RISK_KEPT_MS, SCAN_READ_KEPT_MS, type ScanProgress, repositoryRiskLines } from './repository-risk.ts'
217
- import { lockfileOf, stasisConfigRow } from './repository-risk-read.ts'
217
+ import { keptRepositories } from './repository-risk-kept.ts'
218
+ import { type RiskStasisRead, lockfileOf, stasisConfigRow } from './repository-risk-read.ts'
218
219
  import { WORKFLOWS_DIR } from './repository-actions.ts'
219
220
  import { githubActionsSource } from './github-actions.ts'
221
+ import { type KeptWalk, keptWalk } from './pulse-walk.ts'
220
222
  import { type RepositoryEntry, createRepositoryBrowser, repositoryTreeFiles, scopedDirectory } from './repository-browser.ts'
221
223
  import { type Lru, lru } from './lru.ts'
222
224
  import { CALLBACK_PATH, LOGIN_PATH, OAuthError, buildLoginRedirect, cacheAvatar, ensureUserAccessToken, handleCallback } from './github-oauth.ts'
@@ -264,7 +266,7 @@ import { eachOf } from './queue.ts'
264
266
  import { lockedAt, lockedIn, lockfilesAt } from './commit-lockfiles.ts'
265
267
  import { MAX_REQUIRED_REVIEWS, type PublishedReview, type RepoDependencyReview } from './repository-dependency-reviews.ts'
266
268
  import { EVERY_LOCKFILE, type LockfileScope, heldTo, isStasisConfig, reviewedIn, scopeOf, stasisConfigs } from './lockfile-scope.ts'
267
- import { type StasisDependencyReader, type StasisRead, type StasisWant, stasisDependencyReader, stasisDirectory, wantingBeside, withReach } from './stasis-dependencies.ts'
269
+ import { type StasisDependencyReader, type StasisWant, stasisDependencyReader, stasisDirectory, wantingBeside, withReach } from './stasis-dependencies.ts'
268
270
  import { type BundledVersion, bundleDependencies, installsBundle } from './bundle-dependency-reviews.ts'
269
271
  import { type CommentReviews, type ReviewBaselineStore, baselineFor, heldDependencies, reviewedDependencies, reviewedPackages } from './pull-dependency-reviews.ts'
270
272
  import { formattedPull, withFormatted } from './dependency-review-comments.ts'
@@ -3323,10 +3325,14 @@ async function handleRepositoryPulse(res: ServerResponse, deps: ManagedHttpDeps,
3323
3325
  // counted), the year read on behind it (`behind`, for the client to ask
3324
3326
  // again till it is, however long a page of it takes to read); those
3325
3327
  // asking meanwhile, by the database, the repository and the period, waiting
3326
- // on that read, not one of their own, unless it began PULSE_YEAR_HELD_MS ago
3327
- // or longer.
3328
+ // on that read, not one of their own, unless its last part began
3329
+ // PULSE_YEAR_HELD_MS ago or longer. Off serverless, read on part after part
3330
+ // behind its answers till the year is read whole, as long as each part reads
3331
+ // more, as many as PULSE_YEAR_PARTS; on serverless, a part an answer, each
3332
+ // going on from the last (keptWalk).
3328
3333
  const PULSE_YEAR_WAIT_MS = 1500
3329
3334
  const PULSE_YEAR_HELD_MS = 60_000
3335
+ const PULSE_YEAR_PARTS = 200
3330
3336
  type PulseYear = Awaited<ReturnType<typeof pulseCommits>>
3331
3337
  type PulseYearRead = { reading: Promise<PulseYear>; progress: { commits: number }; began: number }
3332
3338
  const pulseYearReads = new WeakMap<ManagedDb, Map<string, PulseYearRead>>()
@@ -3337,7 +3343,20 @@ function pulseYearRead(deps: ManagedHttpDeps, repoId: number, fullName: string,
3337
3343
  const held = reads.get(key)
3338
3344
  if (held && Date.now() - held.began < PULSE_YEAR_HELD_MS) return held
3339
3345
  const progress = { commits: 0 }
3340
- const year = { reading: pulseCommits(deps, repoId, fullName, token, weeks, progress), progress, began: Date.now() }
3346
+ // How far a part read: its commits, else the pull requests merged; null, whole.
3347
+ const reached = (part: PulseYear) => part.reading ?? part.pulls
3348
+ const readOn = async () => {
3349
+ let part = await pulseCommits(deps, repoId, fullName, token, weeks, progress)
3350
+ for (let parts = 1; !deps.config.serverless && reached(part) !== null && parts < PULSE_YEAR_PARTS; parts++) {
3351
+ year.began = Date.now()
3352
+ const next = await pulseCommits(deps, repoId, fullName, token, weeks, progress)
3353
+ const further = reached(next) === null || reached(next)! > reached(part)! || (part.reading === null) !== (next.reading === null)
3354
+ part = next
3355
+ if (!further) break
3356
+ }
3357
+ return part
3358
+ }
3359
+ const year: PulseYearRead = { reading: readOn(), progress, began: Date.now() }
3341
3360
  reads.set(key, year)
3342
3361
  const settled = year.reading.catch((err: unknown) => { console.warn('managed: pulse year read failed:', err) })
3343
3362
  .finally(() => { if (reads.get(key) === year) reads.delete(key) })
@@ -3439,6 +3458,18 @@ async function pulseCommits(deps: ManagedHttpDeps, repoId: number, fullName: str
3439
3458
  const mergesKey = pulseMergesKey(repoId)
3440
3459
  const last = () => lastPulseYear(deps, repoId, first)
3441
3460
  const sha = head.sha
3461
+ // What walks of its year found, from this head or one before, gone on from
3462
+ // (pulse-walk.ts keptWalk), as the pages of its history every tab reads
3463
+ // hold them: a walk cut short not begun again, a head moved on read only as
3464
+ // far as what is new.
3465
+ const walk = keptWalk(pulseWalkStore<KeptWalk>(deps.db, deps.config.debug), `${repoId}\0${COAUTHORS_READ}\0${PULSE_YEAR_VERSION}`,
3466
+ historyPages(deps, repoId, true))
3467
+ const walkTo = async (back: number, progressed: (read: number) => void = () => {}) => {
3468
+ const known = await walk.read()
3469
+ const year = await yearCommits(fullName, token, sha, first, walk.pages, globalThis.fetch, back, progressed, known)
3470
+ await walk.write(known, year.walked, first)
3471
+ return year
3472
+ }
3442
3473
  // What tells whose the year's commits are, kept as read: the agents' pull
3443
3474
  // requests merged (agentMerges), as the pull requests kept tell, read as
3444
3475
  // far back as `whole` (keptPulls), and the commits that release the
@@ -3483,7 +3514,7 @@ async function pulseCommits(deps: ManagedHttpDeps, repoId: number, fullName: str
3483
3514
  const read = await attribution(whole)
3484
3515
  const same = kept && sameMerges(read, kept) && read.releases!.join() === (kept.releases ?? []).join() && readTo(kept) <= readTo(read)
3485
3516
  if (readTo(read) >= whole || same) return read
3486
- const year = await yearCommits(fullName, token, sha, first, historyPages(deps, repoId, true), globalThis.fetch, whole)
3517
+ const year = await walkTo(whole)
3487
3518
  if (year.complete) recounted.stats = await count(year, read, whole)
3488
3519
  return read
3489
3520
  }, () => true, false, stampOf(deps, repoId, fullName, token, today())).catch((err: unknown) => { console.warn('managed: pulse attribution read failed:', err) })
@@ -3507,8 +3538,7 @@ async function pulseCommits(deps: ManagedHttpDeps, repoId: number, fullName: str
3507
3538
  // period's count takes its place.
3508
3539
  if (!tooMany && held && 'tooMany' in held) await store.write(tooManyKey, { within: first }, Date.now())
3509
3540
  if (need > tooManyWithin) {
3510
- const [year, read] = await Promise.all([yearCommits(fullName, token, sha, first, historyPages(deps, repoId, true), globalThis.fetch, need,
3511
- commits => { progress.commits = commits }), attribution(need)])
3541
+ const [year, read] = await Promise.all([walkTo(need, commits => { progress.commits = commits }), attribution(need)])
3512
3542
  await store.write(mergesKey, read, Date.now())
3513
3543
  if (year.complete) {
3514
3544
  if (readTo(read) >= need) return { stats: await last(), reading: null, pulls: read.next?.read ?? 0, pending: false, kept: false }
@@ -3631,13 +3661,20 @@ async function riskRepository(db: ManagedDb, query: URLSearchParams, repoId: num
3631
3661
  // commit; none is waited for. One with no token to build it with fails, as
3632
3662
  // a review refuses it (readWholeRepositoryOf).
3633
3663
  async function riskStasis(deps: ManagedHttpDeps, repo: { repoId: number; fullName: string }, token: string | null, commit: string, branch: string,
3634
- config: string): Promise<StasisRead> {
3664
+ config: string, headAt?: number): Promise<RiskStasisRead> {
3635
3665
  const reader = stasisReader(deps)
3636
3666
  const read = await reader.read(repo.repoId, commit, config)
3667
+ // Read as its branch's head at `headAt`, as a scan reads it, not as its
3668
+ // page asks of what the scan read: built already, as a dependency review
3669
+ // may have it, the last built there; else the last once made.
3670
+ const head = headAt !== undefined && branch !== ''
3671
+ if (read.status === 'ready' && head) trackBehind(deps, reader.atTip({ repoId: repo.repoId, commit, config, branch }, headAt).catch(() => {}))
3637
3672
  if (read.status !== 'pending') return read
3638
3673
  if (!token) return { status: 'failed', error: 'github-token-required', transient: false }
3639
- reader.build([{ repo: { repoId: repo.repoId, fullName: repo.fullName }, token, commit, config, ...branch ? { branch } : {}, priority: 0 }])
3640
- return read
3674
+ reader.build([{ repo: { repoId: repo.repoId, fullName: repo.fullName }, token, commit, config, ...branch ? { branch } : {}, ...head ? { headAt } : {}, priority: 0 }])
3675
+ // Meanwhile, what the last built of it at its branch's head reached, where one was.
3676
+ const last = branch ? await reader.last(repo.repoId, branch, config) : null
3677
+ return last && last.commit !== commit ? { status: 'pending', last } : read
3641
3678
  }
3642
3679
 
3643
3680
  // GET /api/admin/repositories/risk/stasis?repoId=&commit=&path=…: what
@@ -3731,8 +3768,10 @@ function scanProgress(deps: ManagedHttpDeps, key: string, scan: string | null) {
3731
3768
  // looked at again as the scan goes on. Read by an admin, or by a
3732
3769
  // manager of the team it names (readRiskSession), each alike, with their
3733
3770
  // own access. The reader leaving, losing what let them read it or the
3734
- // server shutting down stops it.
3771
+ // server shutting down stops it. With `kept=1`, as a scan's first part asks,
3772
+ // what is kept of its last for the reader is told first (keptRepositories).
3735
3773
  async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
3774
+ if (!['1', null].includes(query.get('kept'))) { sendJson(res, 400, { error: 'bad-request' }); return }
3736
3775
  const s = await readRiskSession(res, deps, cookie, query, { handed: true })
3737
3776
  if (!s) return
3738
3777
  const repos = await riskRepositories(deps.db, query)
@@ -3766,6 +3805,8 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3766
3805
  // One GitHub has archived is read no further, as nothing installs from it anew.
3767
3806
  if (reader.archived) return { archived: true as const }
3768
3807
  const commit = await reader.commit('')
3808
+ // When its branch's head was read, for the last Stasis build there (riskStasis).
3809
+ const headAt = Date.now()
3769
3810
  const token = reader.readToken()
3770
3811
  const client = createClient({ token })
3771
3812
  return {
@@ -3780,13 +3821,18 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3780
3821
  // Its files as its tree lists them at the commit, kept by it, as its
3781
3822
  // dependency review's settings read them (handleRepositoryLockfiles).
3782
3823
  files: async () => (await repositoryTree(repo.fullName, token, commit, commitTreeKept(deps, repo.repoId)))?.files ?? [],
3783
- stasis: config => riskStasis(deps, repo, token, commit, reader.defaultBranch, config),
3824
+ stasis: config => riskStasis(deps, repo, token, commit, reader.defaultBranch, config, headAt),
3784
3825
  }
3785
3826
  },
3786
3827
  // What Stasis has made of a build still to be made as the scan read its
3787
3828
  // repository, as its dependency review's reader has it: the page asks
3788
3829
  // for the build again (handleRepositoryRiskStasis), the scan only looks.
3789
3830
  stasisBuilt: ({ repoId, commit, config }) => stasisReader(deps).read(repoId, commit, config),
3831
+ kept: keptRepositories(riskKeptStore<string>(deps.db, deps.config.debug), s.user),
3832
+ // As opening it checks the reader's GitHub access (kept a while, for the read after), not archived.
3833
+ async readable(repo) {
3834
+ try { return !(await browser.reader(repo)).archived } catch { return false }
3835
+ },
3790
3836
  // References resolved with the admin's token, and each one's advisories
3791
3837
  // asked as a bundle's `github` package's are (bundle-advisories.ts), one
3792
3838
  // `internal` of its repository alone, each bounded on its own.
@@ -3838,7 +3884,7 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3838
3884
  if (audited.status !== 200) throw new NpmPackageError(502, audited.body.error)
3839
3885
  return audited.body
3840
3886
  },
3841
- }, controller.signal, undefined, { partMs: deps.config.serverless ? REPO_RISK_PART_MS : null })
3887
+ }, controller.signal, undefined, { partMs: deps.config.serverless ? REPO_RISK_PART_MS : null, kept: query.get('kept') === '1' })
3842
3888
  let checked = Date.now()
3843
3889
  await sendLines(res, lines, async () => {
3844
3890
  if (deps.isShuttingDown()) return false
@@ -166,6 +166,9 @@ export const githubTagStore = <T>(db: UpstreamCacheStore, debug = false): KeptSt
166
166
  // they were last read from GitHub.
167
167
  const HISTORY_PAGE_KEPT_MS = 30 * 24 * 60 * 60_000
168
168
  export const historyPageStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/history', HISTORY_PAGE_KEPT_MS, debug)
169
+ // What the Pulse's walks of a repository's year found (pulse-walk.ts
170
+ // keptWalk), as the history pages holding it, kept as those pages are.
171
+ export const pulseWalkStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/pulse-walk', HISTORY_PAGE_KEPT_MS, debug)
169
172
  // The pull requests squashed into a repository's commits, by the commit
170
173
  // (repository-squashes.ts squashedPulls): kept as its history's pages are.
171
174
  export const historySquashStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/squashes', HISTORY_PAGE_KEPT_MS, debug)
@@ -258,6 +261,12 @@ export const bundleValidationStore = <T>(db: UpstreamCacheStore, debug = false):
258
261
  // shows a reader more than nothing while it is read.
259
262
  export const TEAM_DEPENDENCIES_KEPT_MS = 7 * 24 * 60 * 60_000
260
263
  export const teamDependencyStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'teams/dependencies', TEAM_DEPENDENCIES_KEPT_MS, debug)
264
+ // What a risk scan told whole of a repository (repository-risk.ts
265
+ // KeptRepository), but its Dependabot alerts, by its reader, the repository
266
+ // and a team's directories in it, compressed: told first as a scan of it
267
+ // opens, while it is read again (http.ts handleRepositoryRisk). Kept as a
268
+ // team's Dependencies are.
269
+ export const riskKeptStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository-risk/kept', TEAM_DEPENDENCIES_KEPT_MS, debug)
261
270
  // What a repository's stasis.config.json has Stasis reach at a commit
262
271
  // (stasis-dependencies.ts): the versions, never the lockfile, by the
263
272
  // repository, the commit and the file's path, kept as its history's pages are.
@@ -7,10 +7,11 @@ import { Buffer } from 'node:buffer'
7
7
  import { homedir } from 'node:os'
8
8
  import { join, resolve } from 'node:path'
9
9
  import { CompressionError, decompress } from '@preventive/archive/compression.js'
10
+ import { npmTokenFor } from '../common/npm-token.js'
10
11
  import { encodeBrotli } from './brotli.ts'
11
12
  import { keptBriefly } from './kept-briefly.ts'
12
13
  import { MAX_NPM_PACKAGE_BYTES, MAX_NPM_PACKAGE_FILES, NPM_REGISTRY, NpmPackageError, type NpmPackageFile, type NpmVersionDocument, type TarReading,
13
- askUpstream, npmExecutablePaths, npmFileRows, npmPublishTime, npmToken, readNpmTar } from './npm-packages.ts'
14
+ askUpstream, npmExecutablePaths, npmFileRows, npmPublishTime, readNpmTar } from './npm-packages.ts'
14
15
  import { keepFile, readKeptFile, upstreamCachePath } from './upstream-cache.ts'
15
16
 
16
17
  // The tar stream a package's files may come in, headers and padding included.
@@ -142,10 +143,9 @@ function npmCachePath(hash: string): string | null {
142
143
  return join(root, '_cacache', 'content-v2', 'sha512', hex.slice(0, 2), hex.slice(2, 4), hex.slice(4))
143
144
  }
144
145
 
145
- // The version's tarball from the registry, at the package's own path: with
146
- // the token only for a private version, and its size bounded as it arrives.
147
- async function downloadTarball(url: string, isPrivate: boolean): Promise<Buffer> {
148
- const token = isPrivate ? npmToken() : null
146
+ // The version's tarball from the registry, at the package's own path, its
147
+ // size bounded as it arrives.
148
+ async function downloadTarball(url: string, token: string | null): Promise<Buffer> {
149
149
  const bytes = await askUpstream(url, { headers: token ? { authorization: `Bearer ${token}` } : {}, limit: MAX_TAR_BYTES, ms: TARBALL_TIMEOUT_MS, absent: [401, 403, 404] })
150
150
  .catch((err: unknown) => { throw err instanceof NpmPackageError && err.message === 'upstream-too-large' ? new NpmPackageError(413, 'package-too-large') : err })
151
151
  if (bytes === null) throw new NpmPackageError(404, 'package-not-found')
@@ -169,7 +169,7 @@ async function readTarball(doc: NpmVersionDocument): Promise<Uint8Array> {
169
169
  if (bytes && await hashedAs(bytes, expected, shasum)) return bytes
170
170
  }
171
171
  }
172
- const bytes = await downloadTarball(url, doc.private)
172
+ const bytes = await downloadTarball(url, doc.private ? npmTokenFor(doc.name) : null)
173
173
  if (!await hashedAs(bytes, expected, shasum)) throw new NpmPackageError(502, 'upstream-invalid')
174
174
  if (kept !== null) await keepFile(kept, bytes)
175
175
  return bytes
@@ -2,8 +2,9 @@
2
2
  // registry's tarball, for the Overview and Code tabs the bundle view shows.
3
3
  //
4
4
  // Anyone with workspace access may read a public package. A private one also
5
- // needs NPM_TOKEN on the server, and a reader with access to it: an admin or
6
- // manager, or a member of a visible team listing its scope (team-npm-scopes.ts).
5
+ // needs an npm token for its scope on the server (npm-token.js), and a reader
6
+ // with access to it: an admin or manager, or a member of a visible team
7
+ // listing its scope (team-npm-scopes.ts).
7
8
  // For everyone else, a version is public only when the registry answers for
8
9
  // it without credentials, asked on every request and never from a cache:
9
10
  // upstream's caches, which bundle builds fill using the token, hold no
@@ -17,6 +18,7 @@ import { resolve } from 'node:path'
17
18
  import { ArchiveError, type Entry, unpack } from '@preventive/archive/tar.js'
18
19
  import { isExactVersion } from '@preventive/upstream/semver.js'
19
20
  import { isNpmPackageName, isNpmPackageSpec, npmPackageScope } from '../common/managed/npm-packages.js'
21
+ import { npmTokenFor } from '../common/npm-token.js'
20
22
  import { NPM_SYMLINKS_ABOVE, npmTarLayout } from '../risk/index.js'
21
23
  import type { Role } from '../common/managed/roles.ts'
22
24
  import { npmManifest, npmVersionFields, plainObject, stringRecord } from './npm-manifest.ts'
@@ -62,13 +64,11 @@ export function canReadPrivateNpm(reader: NpmReader, name: string): boolean {
62
64
  export const npmScopesCount = (role: Role, names: readonly string[]): boolean =>
63
65
  role !== 'admin' && role !== 'manage' && names.some(name => npmPackageScope(name) !== null)
64
66
 
65
- export const npmToken = () => process.env['NPM_TOKEN'] || null
66
-
67
67
  // Whether a read of `name` that npm answers none anonymously is asked again
68
68
  // with the server's token: by a reader with private access (`privileged`),
69
69
  // where there is a token and the package is scoped, as npm's private packages
70
70
  // always are. Else the anonymous answer is the reader's.
71
- export const npmTokenReads = (name: string, privileged: boolean): boolean => privileged && npmToken() !== null && npmPackageScope(name) !== null
71
+ export const npmTokenReads = (name: string, privileged: boolean): boolean => privileged && npmPackageScope(name) !== null && npmTokenFor(name) !== null
72
72
 
73
73
  function registryUrl(name: string, spec?: string): string {
74
74
  return `${NPM_REGISTRY}/${name}${spec === undefined ? '' : `/${encodeURIComponent(spec)}`}`
@@ -215,7 +215,7 @@ async function readDocument(name: string, url: string, privileged: boolean,
215
215
  const open = anonymous ? whole ? await sharedWholeDocument(name, url, options) : await registryDocument(url, { ...options, token: null }) : null
216
216
  if (open) return { json: open, private: false }
217
217
  if (!npmTokenReads(name, privileged)) return null
218
- const json = await registryDocument(url, { ...options, token: npmToken() })
218
+ const json = await registryDocument(url, { ...options, token: npmTokenFor(name) })
219
219
  return json ? { json, private: true } : null
220
220
  }
221
221