@preventive/triage 1.0.0-alpha.82 → 1.0.0-alpha.84

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.
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-W2H4DBZW.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-Z7KOFS2V.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-UP3ADVQN.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-EIEUTJM4.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,s as Pr,y as Fr}from"./chunk-WOLGZ2PE.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-K4D3BWQA.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-7BLPGSCC.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?
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.82",
3
+ "version": "1.0.0-alpha.84",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -215,6 +215,7 @@
215
215
  "server-managed/repository-risk.ts",
216
216
  "server-managed/repository-risk-assess.ts",
217
217
  "server-managed/repository-risk-caches.ts",
218
+ "server-managed/repository-risk-kept.ts",
218
219
  "server-managed/repository-risk-audit.ts",
219
220
  "server-managed/repository-risk-read.ts",
220
221
  "server-managed/repository-risk-stasis.ts",
@@ -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
  }
@@ -163,7 +163,7 @@ 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
165
  npmDeltaStore, npmPublishTimeStore, npmVersionDeltaStore, npmVersionStore, ownKeptPrunes, patchStore, privateVersionDeltaStore, pullDependencyStore, pullListStore, repositoryReadStore,
166
- reviewBaselineStore, riskLineStore,
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,7 +214,8 @@ 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'
220
221
  import { type RepositoryEntry, createRepositoryBrowser, repositoryTreeFiles, scopedDirectory } from './repository-browser.ts'
@@ -264,7 +265,7 @@ import { eachOf } from './queue.ts'
264
265
  import { lockedAt, lockedIn, lockfilesAt } from './commit-lockfiles.ts'
265
266
  import { MAX_REQUIRED_REVIEWS, type PublishedReview, type RepoDependencyReview } from './repository-dependency-reviews.ts'
266
267
  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'
268
+ import { type StasisDependencyReader, type StasisWant, stasisDependencyReader, stasisDirectory, wantingBeside, withReach } from './stasis-dependencies.ts'
268
269
  import { type BundledVersion, bundleDependencies, installsBundle } from './bundle-dependency-reviews.ts'
269
270
  import { type CommentReviews, type ReviewBaselineStore, baselineFor, heldDependencies, reviewedDependencies, reviewedPackages } from './pull-dependency-reviews.ts'
270
271
  import { formattedPull, withFormatted } from './dependency-review-comments.ts'
@@ -3631,13 +3632,20 @@ async function riskRepository(db: ManagedDb, query: URLSearchParams, repoId: num
3631
3632
  // commit; none is waited for. One with no token to build it with fails, as
3632
3633
  // a review refuses it (readWholeRepositoryOf).
3633
3634
  async function riskStasis(deps: ManagedHttpDeps, repo: { repoId: number; fullName: string }, token: string | null, commit: string, branch: string,
3634
- config: string): Promise<StasisRead> {
3635
+ config: string, headAt?: number): Promise<RiskStasisRead> {
3635
3636
  const reader = stasisReader(deps)
3636
3637
  const read = await reader.read(repo.repoId, commit, config)
3638
+ // Read as its branch's head at `headAt`, as a scan reads it, not as its
3639
+ // page asks of what the scan read: built already, as a dependency review
3640
+ // may have it, the last built there; else the last once made.
3641
+ const head = headAt !== undefined && branch !== ''
3642
+ if (read.status === 'ready' && head) trackBehind(deps, reader.atTip({ repoId: repo.repoId, commit, config, branch }, headAt).catch(() => {}))
3637
3643
  if (read.status !== 'pending') return read
3638
3644
  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
3645
+ reader.build([{ repo: { repoId: repo.repoId, fullName: repo.fullName }, token, commit, config, ...branch ? { branch } : {}, ...head ? { headAt } : {}, priority: 0 }])
3646
+ // Meanwhile, what the last built of it at its branch's head reached, where one was.
3647
+ const last = branch ? await reader.last(repo.repoId, branch, config) : null
3648
+ return last && last.commit !== commit ? { status: 'pending', last } : read
3641
3649
  }
3642
3650
 
3643
3651
  // GET /api/admin/repositories/risk/stasis?repoId=&commit=&path=…: what
@@ -3731,8 +3739,10 @@ function scanProgress(deps: ManagedHttpDeps, key: string, scan: string | null) {
3731
3739
  // looked at again as the scan goes on. Read by an admin, or by a
3732
3740
  // manager of the team it names (readRiskSession), each alike, with their
3733
3741
  // own access. The reader leaving, losing what let them read it or the
3734
- // server shutting down stops it.
3742
+ // server shutting down stops it. With `kept=1`, as a scan's first part asks,
3743
+ // what is kept of its last for the reader is told first (keptRepositories).
3735
3744
  async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
3745
+ if (!['1', null].includes(query.get('kept'))) { sendJson(res, 400, { error: 'bad-request' }); return }
3736
3746
  const s = await readRiskSession(res, deps, cookie, query, { handed: true })
3737
3747
  if (!s) return
3738
3748
  const repos = await riskRepositories(deps.db, query)
@@ -3766,6 +3776,8 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3766
3776
  // One GitHub has archived is read no further, as nothing installs from it anew.
3767
3777
  if (reader.archived) return { archived: true as const }
3768
3778
  const commit = await reader.commit('')
3779
+ // When its branch's head was read, for the last Stasis build there (riskStasis).
3780
+ const headAt = Date.now()
3769
3781
  const token = reader.readToken()
3770
3782
  const client = createClient({ token })
3771
3783
  return {
@@ -3780,13 +3792,18 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3780
3792
  // Its files as its tree lists them at the commit, kept by it, as its
3781
3793
  // dependency review's settings read them (handleRepositoryLockfiles).
3782
3794
  files: async () => (await repositoryTree(repo.fullName, token, commit, commitTreeKept(deps, repo.repoId)))?.files ?? [],
3783
- stasis: config => riskStasis(deps, repo, token, commit, reader.defaultBranch, config),
3795
+ stasis: config => riskStasis(deps, repo, token, commit, reader.defaultBranch, config, headAt),
3784
3796
  }
3785
3797
  },
3786
3798
  // What Stasis has made of a build still to be made as the scan read its
3787
3799
  // repository, as its dependency review's reader has it: the page asks
3788
3800
  // for the build again (handleRepositoryRiskStasis), the scan only looks.
3789
3801
  stasisBuilt: ({ repoId, commit, config }) => stasisReader(deps).read(repoId, commit, config),
3802
+ kept: keptRepositories(riskKeptStore<string>(deps.db, deps.config.debug), s.user),
3803
+ // As opening it checks the reader's GitHub access (kept a while, for the read after), not archived.
3804
+ async readable(repo) {
3805
+ try { return !(await browser.reader(repo)).archived } catch { return false }
3806
+ },
3790
3807
  // References resolved with the admin's token, and each one's advisories
3791
3808
  // asked as a bundle's `github` package's are (bundle-advisories.ts), one
3792
3809
  // `internal` of its repository alone, each bounded on its own.
@@ -3838,7 +3855,7 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3838
3855
  if (audited.status !== 200) throw new NpmPackageError(502, audited.body.error)
3839
3856
  return audited.body
3840
3857
  },
3841
- }, controller.signal, undefined, { partMs: deps.config.serverless ? REPO_RISK_PART_MS : null })
3858
+ }, controller.signal, undefined, { partMs: deps.config.serverless ? REPO_RISK_PART_MS : null, kept: query.get('kept') === '1' })
3842
3859
  let checked = Date.now()
3843
3860
  await sendLines(res, lines, async () => {
3844
3861
  if (deps.isShuttingDown()) return false
@@ -258,6 +258,12 @@ export const bundleValidationStore = <T>(db: UpstreamCacheStore, debug = false):
258
258
  // shows a reader more than nothing while it is read.
259
259
  export const TEAM_DEPENDENCIES_KEPT_MS = 7 * 24 * 60 * 60_000
260
260
  export const teamDependencyStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'teams/dependencies', TEAM_DEPENDENCIES_KEPT_MS, debug)
261
+ // What a risk scan told whole of a repository (repository-risk.ts
262
+ // KeptRepository), but its Dependabot alerts, by its reader, the repository
263
+ // and a team's directories in it, compressed: told first as a scan of it
264
+ // opens, while it is read again (http.ts handleRepositoryRisk). Kept as a
265
+ // team's Dependencies are.
266
+ export const riskKeptStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository-risk/kept', TEAM_DEPENDENCIES_KEPT_MS, debug)
261
267
  // What a repository's stasis.config.json has Stasis reach at a commit
262
268
  // (stasis-dependencies.ts): the versions, never the lockfile, by the
263
269
  // repository, the commit and the file's path, kept as its history's pages are.
@@ -46,7 +46,66 @@ export const isBusy = (error: unknown) => (error instanceof NpmPackageError && e
46
46
  // `integrity`, a mirror's held to it.
47
47
  export interface AssessedPackage { name: string; version: string; integrity?: string }
48
48
 
49
- export type Assessment = { published: string | null; findings: { id: string; severity: Severity; takenDown?: unknown }[]; score: { score: number } }
49
+ export type Assessment = { published: string | null; findings: ({ id: string; severity: Severity } & Record<string, unknown>)[]; score: { score: number } }
50
+
51
+ // How many of what a finding found a risk line keeps, the first (its files,
52
+ // hosts, dependencies or scripts), with how many there are (`count`), for the
53
+ // Packages tab's tooltips (repository-risk.js); and how long a text of it
54
+ // (npm's deprecation message, a script's command) may be.
55
+ export const TOLD_ROWS = 5
56
+ const TOLD_TEXT = 300
57
+
58
+ // What a risk line tells of a finding: its id and severity, whether npm took
59
+ // its package down, and of what it found (assessNpm's, risk/npm/held.js,
60
+ // combined.js), what its tooltip says, bounded (TOLD_ROWS, TOLD_TEXT): npm's
61
+ // deprecation message; its package's tier by downloads, and the known
62
+ // account or scope that lowers it; the accounts that published it and the
63
+ // one before; the scripts npm runs installing it; its files, each with what
64
+ // it runs or reaches for (their kinds), the services it names, how it is
65
+ // obfuscated, where it links, its size, or its longest line before and now;
66
+ // the dependencies it takes from elsewhere than npm or imports none of, by
67
+ // their specs; and the hosts it names anew, each where first.
68
+ export type ToldFinding = { id: string; severity: Severity; takenDown?: true } & Record<string, unknown>
69
+ type Row = Record<string, unknown>
70
+ const cut = (text: unknown) => typeof text === 'string' && text.length > TOLD_TEXT ? `${text.slice(0, TOLD_TEXT - 1)}…` : typeof text === 'string' ? text : undefined
71
+ const keysOf = (found: unknown) => found && typeof found === 'object' ? Object.keys(found) : []
72
+ const first = (key: string, rows: unknown, pick: (row: Row) => Row) => Array.isArray(rows)
73
+ ? { [key]: (rows as Row[]).slice(0, TOLD_ROWS).map(pick), count: rows.length } : {}
74
+ const FILES: Partial<Record<string, (row: Row) => Row>> = {
75
+ 'held-runs-code': row => ({ path: row['path'], kinds: keysOf(row['found']) }),
76
+ 'held-credentials': row => ({ path: row['path'], kinds: keysOf(row['found']) }),
77
+ 'held-exfiltration': row => ({ path: row['path'], services: keysOf(row['found']) }),
78
+ 'held-remote': row => ({ path: row['path'], services: keysOf(row['found']) }),
79
+ 'held-ip-lookup': row => ({ path: row['path'], services: keysOf(row['found']) }),
80
+ 'held-obfuscated': row => ({ path: row['path'], ...row['found'] as Row }),
81
+ 'held-symlinks': row => ({ path: row['path'], link: row['link'], ...row['outside'] === true ? { outside: true } : {} }),
82
+ 'large-code': row => ({ path: row['path'], bytes: row['bytes'] }),
83
+ 'binary-code': row => ({ path: row['path'], bytes: row['bytes'] }),
84
+ 'now-unreadable': row => ({ path: row['path'], was: row['was'], now: row['now'] }),
85
+ }
86
+ export function toldFinding({ id, severity, ...found }: { id: string; severity: Severity } & Record<string, unknown>): ToldFinding {
87
+ const told: ToldFinding = { id, severity, ...found['takenDown'] === true ? { takenDown: true as const } : {} }
88
+ const files = FILES[id]
89
+ if (files) return { ...told, ...first('files', found['files'], files) }
90
+ switch (id) {
91
+ case 'deprecated': return { ...told, message: cut(found['message']) }
92
+ case 'popularity': return { ...told, tier: typeof found['tier'] === 'number' && Number.isFinite(found['tier']) ? found['tier'] : null,
93
+ ...found['known'] ? { known: true } : {}, ...typeof found['scope'] === 'string' ? { scope: found['scope'] } : {}, ...typeof found['account'] === 'string' ? { account: found['account'] } : {} }
94
+ case 'publisher': return { ...told, was: found['was'], now: found['now'], wasStanding: found['wasStanding'] ?? (found['wasKnown'] ? 'known' : 'unknown'),
95
+ nowStanding: found['nowStanding'] ?? (found['nowKnown'] ? 'known' : 'unknown'), ...found['major'] ? { major: true } : {} }
96
+ case 'held-install-scripts': {
97
+ const scripts = Array.isArray(found['scripts']) ? found['scripts'] as [string, unknown][] : []
98
+ return { ...told, scripts: scripts.slice(0, TOLD_ROWS).map(([script, command]) => [script, cut(command) ?? '']), count: scripts.length }
99
+ }
100
+ case 'held-non-registry-deps': return { ...told, ...first('dependencies', found['dependencies'], row => ({ name: row['name'], spec: row['now'] })) }
101
+ case 'held-unused-deps': return { ...told, ...first('dependencies', found['dependencies'], row => ({ name: row['name'], spec: row['range'] })) }
102
+ case 'new-hosts': return { ...told, ...first('hosts', found['hosts'], row => {
103
+ const [place] = Array.isArray(row['places']) ? row['places'] as Row[] : []
104
+ return { host: row['host'], ...place ? { path: place['path'], line: place['line'] } : {} }
105
+ }) }
106
+ default: return told
107
+ }
108
+ }
50
109
 
51
110
  // What of a scan's source assessing a package asks (RepositoryRiskSource).
52
111
  export interface AssessingSource {
@@ -71,7 +130,7 @@ export async function assessPackage(source: AssessingSource, signal: AbortSignal
71
130
  const read = doc ??= await documentOf(source, pkg, signal)
72
131
  if (!(read instanceof NpmPackageError) && pkg.integrity !== undefined && !pkg.integrity.split(/\s+/u).includes(read.dist.integrity)) return { ...at, error: 'integrity-mismatch' }
73
132
  const { published, findings, score } = read instanceof NpmPackageError ? await removedOf(source, pkg, teamScoped, signal, read) : await assessedOf(source, pkg, teamScoped, signal, read)
74
- const told = findings.map(({ id, severity, takenDown }) => ({ id, severity, ...takenDown === true ? { takenDown: true as const } : {} }))
133
+ const told = findings.map(toldFinding)
75
134
  return { ...at, published, severity: highestSeverity(told), score: score.score, findings: told }
76
135
  } catch (error) {
77
136
  if (signal.aborted) return null
@@ -1,6 +1,7 @@
1
1
  // What repository risk scans keep between them (repository-risk.ts), in this
2
2
  // instance's memory.
3
3
  import { type Lru, lru } from './lru.ts'
4
+ import type { KeptStore } from './npm-kept.ts'
4
5
  import { type ActionAnswers, type ActionLine, type WorkflowsRead, answerWeight } from './repository-actions.ts'
5
6
  import type { Audit } from './repository-risk-audit.ts'
6
7
  import type { ListedLockfile, LockfileRead } from './repository-risk-read.ts'
@@ -35,3 +36,21 @@ export const riskCaches = (): RiskCaches => ({
35
36
  // What GitHub answered of public repositories' actions, by answerWeight.
36
37
  actionAnswers: lru(200_000, answerWeight),
37
38
  })
39
+
40
+ // How many kept risk lines are read of a source's `risks` at once.
41
+ const KEPT_READ = 500
42
+
43
+ // Risk lines kept of `keys`, by key: in this instance's memory (`caches`),
44
+ // else a source's `risks`, KEPT_READ at a time, held in memory then.
45
+ export async function keptRiskLines(caches: RiskCaches, risks: KeptStore<RiskLine> | undefined, keys: string[]) {
46
+ const kept = new Map<string, { at: number; line: RiskLine }>()
47
+ const left = keys.filter(key => { const hit = caches.risks.get(key); if (hit) kept.set(key, hit); return !hit })
48
+ if (!risks) return kept
49
+ for (let from = 0; from < left.length; from += KEPT_READ) {
50
+ for (const [key, { at, value }] of await risks.readMany(left.slice(from, from + KEPT_READ))) {
51
+ caches.risks.set(key, { at, line: value })
52
+ kept.set(key, { at, line: value })
53
+ }
54
+ }
55
+ return kept
56
+ }
@@ -0,0 +1,86 @@
1
+ // What a repository risk scan (repository-risk.ts) told of each repository,
2
+ // but its Dependabot alerts, kept gzipped for its reader (riskKeptStore), for
3
+ // a scan to tell first as it opens; one failing, or archived, kept no more.
4
+ import { gunzipBytes, gzipText } from '../common/gzip.js'
5
+ import { decodeUtf8 } from '../common/utf8.js'
6
+ import type { LockedPackage } from './locked-packages.ts'
7
+ import type { KeptStore } from './npm-kept.ts'
8
+ import type { ActionRef } from './repository-actions.ts'
9
+ import { inTurns } from './queue.ts'
10
+ import { stasisVersions } from './repository-risk-read.ts'
11
+ import type { RepositoryRiskLine, RepositoryRiskRepo } from './repository-risk.ts'
12
+
13
+ // What a scan told of a repository: its name then, its lines, and its Actions' references.
14
+ export interface KeptRepository { name: string; lines: RepositoryRiskLine[]; refs: ActionRef[] }
15
+ // A line of what was kept of a repository, told first, as of when it was read.
16
+ export type KeptLine = RepositoryRiskLine & { kept: number }
17
+
18
+ // Where it is kept, for one reader: read of many repositories at once, kept
19
+ // as each is told whole, and no longer.
20
+ export interface KeptRepositories {
21
+ read(repos: RepositoryRiskRepo[]): Promise<Map<number, { at: number; value: KeptRepository }>>
22
+ write(repo: RepositoryRiskRepo, value: KeptRepository, at: number): Promise<void>
23
+ remove(repo: RepositoryRiskRepo): Promise<void>
24
+ }
25
+
26
+ // None kept whose gzipped text, in base64, is longer, as a scan of a
27
+ // monorepo of many lockfiles may be; none unpacked past KEPT_TEXT_BYTES.
28
+ const KEPT_BYTES = 8 * 1024 * 1024
29
+ const KEPT_TEXT_BYTES = 128 * 1024 * 1024
30
+ const VERSION = 1
31
+
32
+ // What is kept in `store` for reader `user` (their id and role).
33
+ export function keptRepositories(store: KeptStore<string>, user: { id: string; role: string }): KeptRepositories {
34
+ const keyOf = (repo: RepositoryRiskRepo) => JSON.stringify([VERSION, user.id, user.role, repo.repoId, repo.paths ?? null])
35
+ const valueOf = async (packed: unknown): Promise<KeptRepository | null> => {
36
+ if (typeof packed !== 'string') return null
37
+ try {
38
+ const value = JSON.parse(decodeUtf8(await gunzipBytes(Buffer.from(packed, 'base64'), { maxBytes: KEPT_TEXT_BYTES }))) as Partial<KeptRepository> | null
39
+ return typeof value?.name === 'string' && Array.isArray(value.lines) && Array.isArray(value.refs) ? value as KeptRepository : null
40
+ } catch { return null }
41
+ }
42
+ return {
43
+ async read(repos) {
44
+ const keys = repos.map(keyOf)
45
+ const hits = await store.readMany(keys)
46
+ const kept = new Map<number, { at: number; value: KeptRepository }>()
47
+ await Promise.all(repos.map(async (repo, at) => {
48
+ const hit = hits.get(keys[at]!)
49
+ const value = hit && await valueOf(hit.value)
50
+ if (value) kept.set(repo.repoId, { at: hit.at, value })
51
+ }))
52
+ return kept
53
+ },
54
+ async write(repo, value, at) {
55
+ const packed = Buffer.from(await gzipText(JSON.stringify(value))).toString('base64')
56
+ await (packed.length > KEPT_BYTES ? store.remove(keyOf(repo)) : store.write(keyOf(repo), packed, at))
57
+ },
58
+ remove: repo => store.remove(keyOf(repo)),
59
+ }
60
+ }
61
+
62
+ // Whether its reader may read a repository now, as opening it asks GitHub;
63
+ // each line to tell; and what the scan is given again (repository-risk.ts reseed).
64
+ interface Telling { signal: AbortSignal; readable(repo: RepositoryRiskRepo): Promise<boolean>; tell(line: KeptLine): void
65
+ reseed(told: { stasis: string[]; packages: LockedPackage[][]; refs: ActionRef[] }): void }
66
+
67
+ // What is kept of `repos` told, each line marked when it was read (`kept`),
68
+ // of each with the name it had then that its reader may still read.
69
+ const READ_AT_ONCE = 20
70
+ const READABLE_AT_ONCE = 6
71
+ export async function tellKept(kept: KeptRepositories, repos: RepositoryRiskRepo[], to: Telling) {
72
+ const asking = inTurns(READABLE_AT_ONCE)
73
+ for (let from = 0; from < repos.length && !to.signal.aborted; from += READ_AT_ONCE) {
74
+ const some = repos.slice(from, from + READ_AT_ONCE)
75
+ const read = await kept.read(some)
76
+ const told = some.map(repo => read.get(repo.repoId)?.value.name === repo.fullName && asking(() => to.readable(repo).catch(() => false)))
77
+ for (const [at, repo] of some.entries()) {
78
+ const hit = read.get(repo.repoId)
79
+ if (!hit || !await told[at] || to.signal.aborted) continue
80
+ const { lines, refs } = hit.value
81
+ for (const line of lines) to.tell({ ...line, kept: hit.at })
82
+ to.reseed({ stasis: stasisVersions(lines.find(line => line.type === 'stasis') ?? null), refs,
83
+ packages: lines.flatMap(line => line.type === 'lockfile' && 'packages' in line ? [line.packages] : []) })
84
+ }
85
+ }
86
+ }
@@ -15,7 +15,8 @@
15
15
  import { createHash } from 'node:crypto'
16
16
  import type { LockfileFormat, RepoLockfile } from '@preventive/upstream/github.js'
17
17
  import type { AlertsRead } from './dependabot-access.ts'
18
- import type { DependabotAlert } from './dependabot-alerts.ts'
18
+ import { type DependabotAlert, alertVersions } from './dependabot-alerts.ts'
19
+ import { npmMalwareAdvisory } from '../risk/index.js'
19
20
  import { type LockedPackage, isTestFixture, lockedPackages, yarnManifests } from './locked-packages.ts'
20
21
  import type { Lru } from './lru.ts'
21
22
  import type { KeptStore } from './npm-kept.ts'
@@ -25,7 +26,7 @@ import { type RiskFailure, failureOf } from './repository-risk-assess.ts'
25
26
  import type { LockfileLine, RepositoryRiskLine, RepositoryRiskRepo } from './repository-risk.ts'
26
27
  import type { StasisDependency } from './bundle-build.ts'
27
28
  import { isStasisConfig } from './lockfile-scope.ts'
28
- import type { StasisRead } from './stasis-dependencies.ts'
29
+ import type { StasisBuilt, StasisRead } from './stasis-dependencies.ts'
29
30
 
30
31
  // The formats of npm's ecosystem, as findRepoLockfiles names them, and those
31
32
  // of them read here.
@@ -54,26 +55,34 @@ export type RepositoryArchived = Extract<RepositoryRiskLine, { type: 'repo'; arc
54
55
  // (`dependencies`), that its build is still to be made (`pending`), or why it
55
56
  // failed.
56
57
  // `lockfiles`, those its `lockfiles` names, from the repository's root,
57
- // where it names some: those its builds install from (namedLockfiles).
58
- export type StasisConfigRow = { path: string; lockfiles?: string[] } & ({ dependencies: StasisDependency[] } | { pending: true } | RiskFailure)
58
+ // where it names some: those its builds install from (namedLockfiles). One
59
+ // still to be made with what the last built of it on its branch installs
60
+ // meanwhile (`dependencies`, of `lastBuilt`, its commit), where one was.
61
+ export type StasisConfigRow = { path: string; lockfiles?: string[] } & ({ dependencies: StasisDependency[] } | { pending: true }
62
+ | { pending: true; dependencies: StasisDependency[]; lastBuilt: string } | RiskFailure)
59
63
  // A repository's stasis.config.json files, those of its `paths` alone, each
60
64
  // what Stasis reaches of it, or why they couldn't be listed.
61
65
  export type StasisConfigsRead = { configs: StasisConfigRow[] } | RiskFailure
62
66
 
63
67
  // A version, as Stasis tells those it installs, whatever its integrity.
64
68
  export const versionKey = ({ name, version }: { name: string; version: string }) => `${name}@${version}`
65
- // The versions a repository's Stasis builds made install (versionKey); none
66
- // of those still to be made, which aren't waited for.
69
+ // The versions a repository's Stasis builds made install (versionKey): of
70
+ // those still to be made, which aren't waited for, what the last built on
71
+ // its branch installs, where one was.
67
72
  export const stasisVersions = (read: StasisConfigsRead | null): string[] => [...new Set(read && 'configs' in read
68
73
  ? read.configs.flatMap(config => 'dependencies' in config ? config.dependencies.map(versionKey) : []) : [])]
69
74
  // The paths of a repository's stasis.config.json files whose builds are still
70
75
  // to be made.
71
76
  export const stasisBuilding = (read: StasisConfigsRead | null): string[] => read && 'configs' in read ? read.configs.flatMap(config => 'pending' in config ? [config.path] : []) : []
72
77
 
78
+ // A config's read, a build still to be made with the last built at its branch's head (`last`), where one was.
79
+ export type RiskStasisRead = StasisRead | { status: 'pending'; last: StasisBuilt }
80
+
73
81
  // A config's row of its read: a failed build told by its code (`detail`).
74
- export function stasisConfigRow(path: string, read: StasisRead): StasisConfigRow {
82
+ export function stasisConfigRow(path: string, read: RiskStasisRead): StasisConfigRow {
75
83
  if (read.status === 'ready') return { path, dependencies: read.dependencies }
76
- return read.status === 'pending' ? { path, pending: true } : { path, error: 'stasis-failed', detail: read.error }
84
+ if (read.status === 'pending') return 'last' in read ? { path, pending: true, dependencies: read.last.dependencies, lastBuilt: read.last.commit } : { path, pending: true }
85
+ return { path, error: 'stasis-failed', detail: read.error }
77
86
  }
78
87
 
79
88
  // A repository opened at its default branch's head (`commit`): its lockfiles,
@@ -94,7 +103,7 @@ export interface OpenedRepository {
94
103
  // as a dependency review's reader has it (stasis-dependencies.ts), its
95
104
  // build asked for where none is kept yet, never waited for.
96
105
  files?(): Promise<string[]>
97
- stasis?(config: string): Promise<StasisRead>
106
+ stasis?(config: string): Promise<RiskStasisRead>
98
107
  }
99
108
 
100
109
  // What a repository is read with: the scan's source and caches, and its
@@ -258,3 +267,30 @@ export async function readRepository<R extends RepositoryRiskRepo>(reading: Repo
258
267
  const stasis = await reaching
259
268
  return reading.signal.aborted ? null : { commit: opened.commit, lockfiles, dependabot, actions, stasis, recheck: () => opened.recheck() }
260
269
  }
270
+
271
+ // A Dependabot alert as a scan tells it: with the versions of its package
272
+ // the lockfile it is of locks that it covers, none where it is of none read
273
+ // (a package.json, bun's lockfile), and whether it is of malware, by the rule
274
+ // upstream tells an advisory's by (risk's npmMalwareAdvisory).
275
+ export type DependabotAlertRow = DependabotAlert & { versions: string[]; malware: boolean }
276
+
277
+ type DependabotLine = Extract<RepositoryRiskLine, { type: 'dependabot' }>
278
+
279
+ // A repository's Dependabot alerts' line, each alert with the versions the
280
+ // lockfile it is of locks that it covers (`lockfiles`, a repository read's),
281
+ // or why they couldn't be had.
282
+ export function dependabotLine(repo: number, read: DependabotRead, lockfiles: RepositoryRead['lockfiles']): DependabotLine {
283
+ if ('error' in read) return { type: 'dependabot', repo, ...read }
284
+ const locked = new Map(lockfiles.flatMap(({ line }) => 'packages' in line ? [[line.path, line.packages] as const] : []))
285
+ return { type: 'dependabot', repo, alerts: read.alerts.map(alert => ({ ...alert, versions: alertVersions(alert, locked.get(alert.manifest)),
286
+ malware: npmMalwareAdvisory({ id: alert.ghsa, aliases: alert.aliases, cwe: alert.cwe, title: alert.title }) })) }
287
+ }
288
+
289
+ // A repository's alerts checked again just before they are told, as access to
290
+ // the repository is (DependabotRead `recheck`): why not, where the user's
291
+ // access to them is withdrawn since they were read.
292
+ export async function rechecked(read: DependabotRead): Promise<DependabotRead> {
293
+ if (!('alerts' in read) || !read.recheck) return read
294
+ try { await read.recheck() } catch (error) { return failureOf(error, 'checking access to its Dependabot alerts again') }
295
+ return read
296
+ }