@preventive/triage 1.0.0-alpha.25 → 1.0.0-alpha.26
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/common/server-info.ts +1 -0
- package/out/client-managed-import.js +2 -2
- package/out/client-managed.js +65 -64
- package/out/prism.js +2 -2
- package/out/view.js +162 -162
- package/package.json +1 -1
- package/server-e2e/config.ts +4 -0
- package/server-managed/blob-vercel.ts +6 -4
- package/server-managed/config.ts +2 -1
- package/server-managed/db-methods.ts +15 -5
- package/server-managed/http.ts +56 -23
- package/server-managed/import-triage.ts +6 -3
- package/server-managed/index.ts +30 -8
- package/server-managed/report-query.ts +6 -0
- package/server-managed/uploads.ts +28 -10
package/common/server-info.ts
CHANGED
|
@@ -49,9 +49,9 @@ ${i}`:i)}return e}function Zi(t){let e=new Map;for(let n of re(t)){let i=Ce(n);i
|
|
|
49
49
|
`||a==="\r"?(n.push(i),e.push(n),n=[],i="",a==="\r"&&t[s+1]===`
|
|
50
50
|
`&&s++):i+=a}for((i!==""||n.length>0)&&(n.push(i),e.push(n));e.length>0&&e.at(-1).length===1&&e.at(-1)[0]==="";)e.pop();return e}function ro(t,e){return e.map(n=>{let i=Object.create(null);return t.forEach((r,o)=>{i[r]=n[o]??""}),i})}function mt(t){let e=no(t);if(e.length<2)throw new Error("Codex CSV: empty or missing header row");let[n,...i]=e;for(let s of to)if(!n.includes(s))throw new Error(`Codex CSV: missing required column "${s}"`);let r=new Map;for(let s of ro(n,i)){let a=s.configured_scan_id;a&&(r.has(a)||r.set(a,[]),r.get(a).push(s))}if(r.size===0)throw new Error("Codex CSV: no rows with a configured_scan_id");let o=[];for(let[s,a]of r){let c=new Set(a.map(u=>u.repository).filter(Boolean));if(c.size>1)throw new Error(`Codex CSV: scan ${s} contains multiple repositories: ${[...c].join(", ")}`);let d=`${[...c][0]||"unknown-repo"}:${s.replace(/^[^:]+:/u,"")}`;o.push({displayName:d,data:{type:"security",source:"codex-security",findings:a.map(io)}})}return o}function io(t){let e=t.relevant_paths.split(" | ").map(r=>r.trim()).find(Boolean)||"unknown",n=[t.title,t.description].filter(Boolean).join(`
|
|
51
51
|
|
|
52
|
-
`),i={id:t.finding_url,file:e,line:"?",severity:(t.severity||"medium").toLowerCase(),description:n,repo:{github:t.repository}};return t.commit_hash&&(i.commitHash=t.commit_hash),t.detected_at&&(i.detectedAt=t.detected_at),t.committed_at&&(i.committedAt=t.committed_at),_(i)}var oo=[["deepview-md",Ln],["deepsec",hn],["piolium",Pn],["claude-security",Bn]];function gt(t){return Array.isArray(t?.findings)?t.findings:Array.isArray(t?.groups)?t.groups:null}function jn(t,e){return typeof e=="string"&&/\.csv$/iu.test(e)?"codex":Re(t).format}function Re(t){let e;try{let n=JSON.parse(t);if(gt(n)){for(let i of Vn(gt(n)))_(i);return{data:n,format:"json",reason:null}}return{data:null,format:null,reason:"JSON, but not a report: no findings array"}}catch(n){e=n}for(let[n,i]of oo){let r=i(t);if(r)return{data:r,format:n,reason:null}}return{data:null,format:null,reason:`Not JSON, and not a recognized markdown format. (JSON error: ${e.message})`}}function Vn(t){return t.flat().filter(e=>e&&typeof e=="object")}async function so(t){for(let i of t)_(i);let e=t.filter(i=>!i.id);if(e.length===0)return;let n=await Promise.all(e.map(un));e.forEach((i,r)=>{n[r]&&(i.id=n[r])})}async function Gn(t){let{data:e,format:n}=Re(t);if(!e)return null;let i=Vn(gt(e));return await so(i),{format:n,data:e,findings:i}}function yt(t,e){let n=t.trimStart().startsWith("[")?rn(t):null;if(n)return{data:{source:"links",findings:[],links:n.groups},format:"links",reason:null};let i=Re(t);if(i.data!=null||jn(t,e)!=="codex")return i;try{return{data:{type:"security",source:"codex-security",findings:mt(t).flatMap(o=>o.data.findings)},format:"codex",reason:null}}catch(r){return{data:null,format:null,reason:r instanceof Error?r.message:"Invalid Codex CSV"}}}function Wn(t,e){let n=yt(t,e);return n.data==null?Promise.resolve(null):Gn(JSON.stringify(n.data))}function Kn(t){return t==="inprogress"||t==="fixed"||t==="invalid"||t==="deleted"?t:void 0}function ao(t){if(t)return Kn(t.triage)??(t.deleted?"deleted":void 0)}function co(t){return t?!t.color&&!ao(t)&&!t.comment&&!t.fix&&!(t.ignoredReports&&t.ignoredReports.length>0)&&t.flagged===void 0:!0}function Le(t){if(!t||typeof t!="object")return;let e=t,n={};typeof e.color=="string"&&e.color&&(n.color=e.color);let i=Kn(e.triage)??(e.deleted?"deleted":void 0);if(i&&(n.triage=i),typeof e.comment=="string"&&e.comment&&(n.comment=e.comment),typeof e.fix=="string"&&e.fix&&(n.fix=e.fix),typeof e.flagged=="boolean"&&(n.flagged=e.flagged),Array.isArray(e.ignoredReports)){let r=e.ignoredReports.filter(o=>typeof o=="string"&&o.length>0);r.length>0&&(n.ignoredReports=r)}return co(n)?void 0:n}var lo=["inprogress","fixed","invalid","deleted"];function uo(t){return typeof t=="string"&&lo.includes(t)}function Me(t){if(t===null)return null;if(typeof t!="object"||Array.isArray(t))return"invalid";let e=t,n={},i=e.color;if(i!=null){if(typeof i!="string"||i.length>50)return"invalid";i!==""&&(n.color=i)}let r=e.triage;if(r!=null){if(!uo(r))return"invalid";n.triage=r}for(let s of["comment","fix"]){let a=e[s];if(a!=null){if(typeof a!="string"||a.length>1e4)return"invalid";a!==""&&(n[s]=a)}}let o=e.flagged;if(o!=null){if(typeof o!="boolean")return"invalid";n.flagged=o}return n}async function qn(t,{session:e,...n}){if(e?.role!=="admin"||!e.csrfToken)throw new Error("An administrator session is required.");if(t!=null&&(typeof t!="object"||Array.isArray(t)))throw new Error("Invalid local triage.");let i=Object.create(null);for(let[
|
|
52
|
+
`),i={id:t.finding_url,file:e,line:"?",severity:(t.severity||"medium").toLowerCase(),description:n,repo:{github:t.repository}};return t.commit_hash&&(i.commitHash=t.commit_hash),t.detected_at&&(i.detectedAt=t.detected_at),t.committed_at&&(i.committedAt=t.committed_at),_(i)}var oo=[["deepview-md",Ln],["deepsec",hn],["piolium",Pn],["claude-security",Bn]];function gt(t){return Array.isArray(t?.findings)?t.findings:Array.isArray(t?.groups)?t.groups:null}function jn(t,e){return typeof e=="string"&&/\.csv$/iu.test(e)?"codex":Re(t).format}function Re(t){let e;try{let n=JSON.parse(t);if(gt(n)){for(let i of Vn(gt(n)))_(i);return{data:n,format:"json",reason:null}}return{data:null,format:null,reason:"JSON, but not a report: no findings array"}}catch(n){e=n}for(let[n,i]of oo){let r=i(t);if(r)return{data:r,format:n,reason:null}}return{data:null,format:null,reason:`Not JSON, and not a recognized markdown format. (JSON error: ${e.message})`}}function Vn(t){return t.flat().filter(e=>e&&typeof e=="object")}async function so(t){for(let i of t)_(i);let e=t.filter(i=>!i.id);if(e.length===0)return;let n=await Promise.all(e.map(un));e.forEach((i,r)=>{n[r]&&(i.id=n[r])})}async function Gn(t){let{data:e,format:n}=Re(t);if(!e)return null;let i=Vn(gt(e));return await so(i),{format:n,data:e,findings:i}}function yt(t,e){let n=t.trimStart().startsWith("[")?rn(t):null;if(n)return{data:{source:"links",findings:[],links:n.groups},format:"links",reason:null};let i=Re(t);if(i.data!=null||jn(t,e)!=="codex")return i;try{return{data:{type:"security",source:"codex-security",findings:mt(t).flatMap(o=>o.data.findings)},format:"codex",reason:null}}catch(r){return{data:null,format:null,reason:r instanceof Error?r.message:"Invalid Codex CSV"}}}function Wn(t,e){let n=yt(t,e);return n.data==null?Promise.resolve(null):Gn(JSON.stringify(n.data))}function Kn(t){return t==="inprogress"||t==="fixed"||t==="invalid"||t==="deleted"?t:void 0}function ao(t){if(t)return Kn(t.triage)??(t.deleted?"deleted":void 0)}function co(t){return t?!t.color&&!ao(t)&&!t.comment&&!t.fix&&!(t.ignoredReports&&t.ignoredReports.length>0)&&t.flagged===void 0:!0}function Le(t){if(!t||typeof t!="object")return;let e=t,n={};typeof e.color=="string"&&e.color&&(n.color=e.color);let i=Kn(e.triage)??(e.deleted?"deleted":void 0);if(i&&(n.triage=i),typeof e.comment=="string"&&e.comment&&(n.comment=e.comment),typeof e.fix=="string"&&e.fix&&(n.fix=e.fix),typeof e.flagged=="boolean"&&(n.flagged=e.flagged),Array.isArray(e.ignoredReports)){let r=e.ignoredReports.filter(o=>typeof o=="string"&&o.length>0);r.length>0&&(n.ignoredReports=r)}return co(n)?void 0:n}var lo=["inprogress","fixed","invalid","deleted"];function uo(t){return typeof t=="string"&&lo.includes(t)}function Me(t){if(t===null)return null;if(typeof t!="object"||Array.isArray(t))return"invalid";let e=t,n={},i=e.color;if(i!=null){if(typeof i!="string"||i.length>50)return"invalid";i!==""&&(n.color=i)}let r=e.triage;if(r!=null){if(!uo(r))return"invalid";n.triage=r}for(let s of["comment","fix"]){let a=e[s];if(a!=null){if(typeof a!="string"||a.length>1e4)return"invalid";a!==""&&(n[s]=a)}}let o=e.flagged;if(o!=null){if(typeof o!="boolean")return"invalid";n.flagged=o}return n}async function qn(t,{session:e,...n}){if(e?.role!=="admin"||!e.csrfToken)throw new Error("An administrator session is required.");if(t!=null&&(typeof t!="object"||Array.isArray(t)))throw new Error("Invalid local triage.");let i=Object.create(null);for(let[c,l]of Object.entries(t??{})){let{ignoredReports:d,...u}=Le(l)??{};Object.keys(u).length!==0&&(i[c]=u)}if(Object.keys(i).length===0)return 0;let r=new Set,o=[],s;do{n.signal?.throwIfAborted();let c="/api/admin/reports/finding-ids"+(s?`?after=${encodeURIComponent(s)}`:""),{reports:l,nextCursor:d}=await n.api.send(c);n.signal?.throwIfAborted();for(let u of l){let p=u.findingIds.filter(h=>Object.hasOwn(i,h)&&!r.has(h));p.length>0&&o.push({id:u.id,ids:p});for(let h of p)r.add(h)}s=d}while(s);for(let c of r){if(!c||c.length>100)throw new Error(`Triage finding IDs must be between 1 and ${100} characters.`);if(Me(i[c])==="invalid")throw new Error(`Triage for ${c} exceeds the managed server limits.`)}let a=n.importedIds??new Set;for(let c of o)await bt(i,{...n,importedIds:a,ids:c.ids,path:`/api/admin/reports/${encodeURIComponent(c.id)}/import-triage`});return r.size}function fo(t,e){let n=[],i=Object.create(null);for(let[r,o]of Object.entries(t)){let s=e[r];if(!s)throw new Error("The server did not return the requested triage snapshot.");let a=s.entry??{},c=i[r]={...a};delete c.comment;for(let[l,d]of Object.entries(o))if(l==="comment"){if(s.comments.some(u=>u.body===d))continue;s.comments.length>0?n.push({id:r,property:l,local:s.comments.map(u=>u.body).join(`
|
|
53
53
|
|
|
54
|
-
`),imported:d}):c.comment=d}else if(a[l]!==void 0&&a[l]!==d){let u=p=>l==="flagged"?p?"flagged":"not flagged":p;n.push({id:r,property:l,local:u(a[l]),imported:u(d)})}else c[l]=d}return{entries:i,conflicts:n}}async function ho(t,e,n,i,r){r?.throwIfAborted();let{entries:o,conflicts:s}=fo(t,e);if(s.length===0)return o;let a=await i(s,n,{title:"Triage conflicts on import",intro:"disagree with stored triage on",trailingNote:"Imported comments are added alongside existing comments. Other choices apply to these finding IDs across all teams.",importedSideLabel:"Apply imported"});if(r?.throwIfAborted(),!a)throw new Error("Triage conflict resolution was cancelled.");for(let c of s){let l=a[`${c.id}:${c.property}`];if(!["local","imported"].includes(l))throw new Error("Resolve every triage conflict before importing.");l==="imported"&&(o[c.id][c.property]=t[c.id][c.property])}return o}function mo(t,e){let n=[],i={entries:{},expected:{}};for(let[r,o]of Object.entries(t)){let s={entries:{...i.entries,[r]:o},expected:{...i.expected,[r]:e[r].version}};if(new TextEncoder().encode(JSON.stringify(s)).length<=262144){i=s;continue}if(Object.keys(i.entries).length===0)throw new Error("This triage entry is too large to import.");n.push(i),i={entries:{[r]:o},expected:{[r]:e[r].version}}}return Object.keys(i.entries).length>0&&n.push(i),n}async function bt(t,{api:e,path:n,ids:i=Object.keys(t),importedIds:r=new Set,lookup:o=new Map,resolveConflicts:s,signal:a}){i=i.filter(c=>Object.hasOwn(t,c)&&!r.has(c));for(let c=0;c<i.length;c+=200){let l=i.slice(c,c+200);for(let d=0;d<5&&l.length>0;d++){a?.throwIfAborted();let{snapshots:u}=await e.send(n,{findingIds:l}),p=Object.fromEntries(l.map(f=>[f,t[f]])),h=await ho(p,u,o,s,a);for(let f of mo(h,u)){if(a?.throwIfAborted(),(await e.send(n,f)).conflict)break;Object.keys(f.entries).forEach(g=>r.add(g))}l=l.filter(f=>!r.has(f))}if(l.length>0)throw new Error("Stored triage keeps changing. Retry to resolve it against the latest values.")}}function Jn(t){if(typeof t!="string")return{ok:!0,path:null};if(/\p{Cc}/u.test(t)||t.includes("\\")||t!==t.trim())return{ok:!1};let e=[];for(let i of t.split("/"))if(!(i===""||i===".")){if(i===".."||i!==i.trim())return{ok:!1};e.push(i)}let n=e.join("/");return n.length>500?{ok:!1}:{ok:!0,path:n===""?null:n}}async function Yn(t,e){let n=new Uint8Array(await t.arrayBuffer());return be(n)?e({tryPassword:i=>Je(n,i)}):n[0]===31&&n[1]===139?Je(n):_e(new TextDecoder("utf-8",{fatal:!0}).decode(n))}async function Zn(t,e){let n=new Map,i=[];for(let s of t.reports){if(typeof s?.name!="string"||!s.name||typeof s.content!="string")throw new Error("Every report must have a name and content.");let a=yt(s.content,s.name);if(!a.data)throw new Error(`${s.name}: ${a.reason??"Unsupported report"}`);let c=ie(a.data),l=c??ie(s)??ie({repo:{github:t.repoUrls?.[s.name]}}),d=e.find(h=>h.fullName.toLowerCase()===l?.toLowerCase())?.repoId??null,u=Jn(a.data.repo?.directory);if(!u.ok)throw new Error(`${s.name}: invalid repository directory`);let p=a.format==="links"?[]:(await Wn(s.content,s.name))?.findings??[];for(let h of p)h.id&&n.set(h.id,h);i.push({...s,repoId:d,directory:u.path??"",github:l,embedded:c,ids:[...new Set(p.map(h=>h.id).filter(Boolean))],uploaded:null})}let r=Object.create(null);if(t.triage!=null&&(typeof t.triage!="object"||Array.isArray(t.triage)))throw new Error("Invalid workspace triage.");for(let[s,a]of Object.entries(t.triage??{})){if(!n.has(s))continue;let c=Le(a);if(!c)continue;let{ignoredReports:l,...d}=c;Object.keys(d).length!==0&&(r[s]=d)}let o=[];for(let s of t.bundleBlobs??[]){let a=Uint8Array.fromBase64(s.data),c=`sha512-${new Uint8Array(await crypto.subtle.digest("SHA-512",a)).toBase64()}`;if(c!==s.integrity)throw new Error(`${s.name}: bundle integrity mismatch`);o.push({name:s.name,integrity:c,bytes:a,uploaded:null})}return{name:t.workspace.name.slice(0,100),reports:i,bundles:o,triage:r,lookup:n,references:t.bundles??[],team:null,completed:new Set,importedIds:new Set}}function Oe(t,e,n){async function i(r,o,s={}){n?.throwIfAborted();let a=await t(r,{credentials:"same-origin",signal:n,...o===void 0?{}:{method:"POST",body:o instanceof File?o:JSON.stringify(o)},headers:{...o instanceof File?{}:{"content-type":"application/json"},"x-csrf-token":e.csrfToken,...s}});if(n?.throwIfAborted(),a.status===409)return{conflict:!0};if(!a.ok)throw new Error(`Import request failed (HTTP ${a.status}). You can retry the remaining steps.`);let c=await a.json();return n?.throwIfAborted(),c}return{send:i}}async function go(t,e,n,i,r,o){if(t.bundles.length===0&&t.references.length===0)return;let s=r??(await n.send("/api/admin/bundles")).bundles,a=new Set(t.bundles.map(l=>l.uploaded.id));if([...a].some(l=>!s.some(d=>d.id===l)))throw new Error("Could not verify the uploaded source bundles. Retry the import.");let c=new Set(t.references);for(let l of s){if(!a.has(l.id)&&!c.has(l.integrity))continue;let d=!o.has(l.repoId),u=d?e:l.repoId;d&&await i(`bundle-repo:${l.id}:${u}`,()=>n.send("/api/admin/bundles/set-repo",{bundleId:l.id,repoId:u}));let p=d?"":l.repoDirectory??"";await i(`repo:${u}:${p}`,()=>n.send("/api/admin/teams/set-repo",{teamId:t.team.id,repoId:u,path:p}))}}async function Qn(t,{api:e,session:n,defaultRepo:i,includeTriage:r,resolveConflicts:o,signal:s,progress:a=()=>{}}){if(n?.role!=="admin"||!n.csrfToken)throw new Error("An administrator session is required.");if(!t.name.trim()||t.name.trim().length>100)throw new Error("Enter a team name of up to 100 characters.");if(r)for(let[p,h]of Object.entries(t.triage)){if(!p||p.length>100)throw new Error(`Triage finding IDs must be between 1 and ${100} characters. Choose Skip triage to import the files without it.`);if(Me(h)==="invalid")throw new Error(`Triage for ${p} exceeds the managed server limits. Choose Skip triage to import the files without it.`)}s?.throwIfAborted();let c=null;if(t.bundles.length===0){let p=new Set(t.references);c=p.size>0?(await e.send("/api/admin/bundles")).bundles.filter(h=>p.has(h.integrity)):[]}if(t.reports.length===0&&t.bundles.length===0&&c.length===0)throw new Error(t.references.length>0?"None of the referenced source bundles are available on the server. Export with bundle bytes included and try again.":"This workspace contains no report or bundle files.");let l=new Set((await e.send("/api/admin/repositories/browsable")).repos.map(p=>p.repoId));for(let p of t.reports){if(p.embedded&&!l.has(p.repoId))throw new Error(`Connect ${p.embedded} in Repositories before importing ${p.name}.`);if(!l.has(p.repoId)&&!l.has(i))throw new Error(`Choose an active repository for ${p.name}.`)}if((t.bundles.length>0||c.some(p=>!l.has(p.repoId)))&&!l.has(i))throw new Error("Choose an active repository for the source bundles.");let d=()=>s?.throwIfAborted(),u=async(p,h)=>{d(),t.completed.has(p)||(await h(),t.completed.add(p))};if(d(),!t.team){let p=await e.send("/api/admin/teams",{name:t.name.trim()});if(p.conflict)throw new Error("A team already has this name. Choose another name.");t.team=p}await u("member",()=>e.send("/api/admin/teams/set-member",{teamId:t.team.id,userId:n.id,security:!0,dependencies:!0}));for(let p of t.bundles)d(),a(`Importing ${p.name}\u2026`),p.uploaded||(p.uploaded=await e.send("/api/admin/bundles",new File([p.bytes],p.name),{"x-bundle-filename":encodeURIComponent(p.name),"x-repo-id":String(i)}));await go(t,i,e,u,c,l);for(let p of t.reports){d(),a(`Importing ${p.name}\u2026`);let h=l.has(p.repoId)?p.repoId:i;if(!p.uploaded){let y=await e.send("/api/admin/reports",new File([p.content],p.name),{"x-report-filename":encodeURIComponent(p.name),"x-repo-id":String(h),"x-repo-directory":encodeURIComponent(p.directory)});if(y.conflict)throw new Error(`Could not reuse the stored report ${p.name}. Retry the import.`);p.uploaded=y}let f=p.uploaded;l.has(f.repoId)||await u(`report-repo:${f.id}:${h}:${p.directory}`,async()=>{if((await e.send("/api/admin/reports/set-repo",{reportId:f.id,repoId:h,directory:p.directory})).conflict)throw new Error(`Could not assign the stored report ${p.name} to its repository.`);f.repoId=h,f.repoDirectory=p.directory});let g=f.repoDirectory??"";await u(`repo:${f.repoId}:${g}`,()=>e.send("/api/admin/teams/set-repo",{teamId:t.team.id,repoId:f.repoId,path:g})),r&&await bt(t.triage,{api:e,resolveConflicts:o,signal:s,ids:p.ids,importedIds:t.importedIds,lookup:t.lookup,path:`/api/admin/reports/${encodeURIComponent(p.uploaded.id)}/import-triage`}),await u(`publish:${p.uploaded.id}`,()=>e.send("/api/admin/reports/set-visible",{reportId:p.uploaded.id,visible:!0}))}return t.team}function er(t){let e=()=>t.isEncryptionEnabled()&&!t.isUnlocked();return{get locked(){return e()},unlock:n=>t.unlockEncryption(n),async read({signal:n}={}){let i=!1,r=t.onVaultStateChange(()=>{i=!0}),o=()=>{if(n?.throwIfAborted(),e()||i)throw new Error("Local data was locked or changed. Unlock it and import triage again.")};try{o();let s=await t.readTriageBlob();return o(),s}finally{r()}}}}function Ne(t){let e=()=>t.isEncryptionEnabled()&&!t.isUnlocked();async function n(){let r=JSON.parse(await t.hydrateKey("deepview.workspaces")||"[]");return(Array.isArray(r)?r:r.workspaces??[]).filter(o=>typeof o.id=="string"&&typeof o.name=="string")}async function i(r,o){let s=!1,a=[t.onVaultStateChange,t.onFileMutated,t.onBundleMutated].map(l=>l(()=>{s=!0})),c=()=>{if(o?.throwIfAborted(),e()||s)throw new Error("Local data was locked or changed. Unlock it and select the workspace again.")};try{c();let l=await r(c);return c(),l}finally{a.forEach(l=>l())}}return{get locked(){return e()},unlock:r=>t.unlockEncryption(r),list:({signal:r}={})=>i(async()=>(await n()).map(o=>({id:o.id,name:o.name})),r),read:(r,{signal:o}={})=>i(async s=>{let a=(await n()).find(f=>f.id===r);if(!a)throw new Error("This local workspace no longer exists.");let c=JSON.stringify(a),l=JSON.parse(await t.hydrateKey("deepview.repoUrls")||"{}"),d=[];for(let f of a.reports??[]){s();let g=await t.withStoredItem("report",f,()=>t.readFile(f));s(),d.push({name:f,content:g,...l[f]?{repo:{github:l[f]}}:{}})}let u=await t.listBundles(),p=[];for(let f of a.bundles??[]){s();let g=u.find(x=>x.integrity===f);if(!g)continue;let y=await t.withStoredItem("bundle",f,()=>t.readBundle(f));s(),p.push({integrity:f,name:g.name,data:y.toBase64()})}let h=await t.readTriageBlob()??{};if(JSON.stringify((await n()).find(f=>f.id===r))!==c)throw new Error("The local workspace changed. Select it again.");return{version:1,workspace:{id:r,name:a.name,privateKey:""},reports:d,bundles:a.bundles??[],bundleBlobs:p,triage:h,repoUrls:l}},o)}}function yo(t,e){if(customElements.get("managed-admin-import"))return;class n extends t{static styles=[G(jt),G(Vt)];static properties={localDeps:{attribute:!1},_busy:{state:!0},_error:{state:!0},_message:{state:!0},_plan:{state:!0},_catalog:{state:!0},_localOpen:{state:!0},_workspaces:{state:!0},_localId:{state:!0},_triage:{state:!0},_repo:{state:!0},_drag:{state:!0}};constructor(){super(),this._busy=!1,this._error="",this._message="",this._plan=null,this._catalog=null,this._workspaces=[],this._localOpen=!1,this._localId="",this._triage="",this._repo=null,this._files=[],this._drag=!1,this._local=!1,this._over=r=>{r.dataTransfer?.types?.includes("Files")&&(r.preventDefault(),this._drag=!0)},this._drop=r=>{r.dataTransfer?.types?.includes("Files")&&(r.preventDefault(),r.stopPropagation(),this._drag=!1,this._busy||(this._files.push(...r.dataTransfer.files),this._nextFile()))},this._localChanged=()=>{this._workspaces=[],this._localId="",!this._unlocking&&(this._local&&(this._plan=null),(this._local||this._importingTriage)&&(this._operation?.abort(),this._message="",this._error=this._importingTriage?"Local data changed or was locked. Import triage again to continue.":"Local data changed or was locked. Choose the workspace again."))},this._blur=()=>{this._readingLocal&&this._localChanged()}}connectedCallback(){super.connectedCallback(),this.addEventListener("dragover",this._over),this.addEventListener("drop",this._drop),globalThis.addEventListener("blur",this._blur),globalThis.addEventListener("storage",this._localChanged),this._offVault=this.localDeps?.onVaultStateChange(this._localChanged),this._loadCatalog()}disconnectedCallback(){this._operation?.abort(),this._offVault?.(),this._plan=null,this._files=[],this.removeEventListener("dragover",this._over),this.removeEventListener("drop",this._drop),globalThis.removeEventListener("blur",this._blur),globalThis.removeEventListener("storage",this._localChanged),super.disconnectedCallback()}updated(r){r.has("session")&&(this._role!=="admin"||r.get("session")?.id!==this.session?.id)&&(this._operation?.abort(),this._plan=null,this._files=[])}async _action(r){if(this._busy||this._role!=="admin")return;let o=this._operation=new AbortController,s=AbortSignal.any([o.signal,this.appState.sessionController.signal]);this._busy=!0,this._error="";try{await r(s),s.throwIfAborted()}catch(a){s.aborted||(this._error=String(a?.message??a))}finally{this._operation===o&&(this._busy=!1)}}async _loadCatalog(){if(this._role==="admin")try{await this._loadCollection("workspace-import:catalog","import options",async r=>{let o=Oe(e,this.session,r),[s,a,c]=await Promise.all([o.send("/api/admin/reports"),o.send("/api/admin/teams"),o.send("/api/admin/bundles")]);return{repos:s.repos,teams:a.teams,bundles:c.bundles}},r=>{this._catalog=r})}catch(r){this._error=String(r?.message??r)}}_browse(){let r=document.createElement("input");r.type="file",r.multiple=!0,r.accept=".enc,.gz,.json",r.addEventListener("change",()=>{this._files.push(...r.files),this._nextFile()},{once:!0}),r.click()}async _prepare(r,o){if(!r)return;if(this._catalog||await this._loadCatalog(),o.throwIfAborted(),!this._catalog)throw new Error("Could not load repositories. Try again.");let s=await Zn(r,this._catalog.repos);o.throwIfAborted();let a=new Set(this._catalog.teams.map(u=>u.name)),c=s.name||"Imported workspace",l=2;for(;a.has(s.name);){let u=` (${l++})`;s.name=c.slice(0,100-u.length)+u}let d=new Set(s.reports.map(u=>u.repoId).filter(u=>u!=null));this._repo=d.size===1?[...d][0]:null,this._triage=Object.keys(s.triage).length>0?"":"skip",this._plan=s,this._message=""}async _nextFile(){if(this._files.length===0||this._busy)return;let r=this._files.shift();this._local=!1,this._plan=null,await this._action(async o=>{let s=await Yn(r,this.promptPassword);o.throwIfAborted(),await this._prepare(s,o)})}async _unlock(r,o){this._unlocking=!0;try{return!r.locked||await r.unlock({signal:o})}finally{this._unlocking=!1}}async _chooseLocal(){this._localOpen=!0,await this._action(async r=>{let o=Ne(this.localDeps);await this._unlock(o,r)&&(r.throwIfAborted(),this._workspaces=await o.list({signal:r}))})}async _readLocal(){if(!this._localId)return;let r=this._localId;this._local=!0,this._plan=null,await this._action(async o=>{let s=Ne(this.localDeps);if(await this._unlock(s,o)){this._readingLocal=!0;try{await this._prepare(await s.read(r,{signal:o}),o)}finally{this._readingLocal=!1}}})}async _import(){!this._plan||!this._triage||!this._csrf||(await this._action(async r=>{if(this._local&&Ne(this.localDeps).locked)throw new Error("Unlock local data and choose the workspace again.");let o=this._plan,s=["teams","reports","bundles","history","workspace-import","scan-sources","repo-impact"];try{let a=await this.appState.mutate(()=>Qn(o,{api:Oe(e,this.session,r),session:this.session,defaultRepo:this._repo,includeTriage:this._triage==="include",resolveConflicts:this.resolveConflicts,signal:r,progress:c=>{this._message=c}}),s);this._catalog.teams.push(a),this._message=`Imported into ${a.name}.`,this._plan=null}finally{this.appState.invalidate(s),o.team&&this.dispatchEvent(new CustomEvent("managed-import-complete",{bubbles:!0,composed:!0}))}}),!this._plan&&!this._error&&await this._nextFile())}async _importLocalTriage(){this._csrf&&await this._action(async r=>{this._importingTriage=!0,this._message="";let o=new Set,s=["reports","history"];try{let a=er(this.localDeps);if(!await this._unlock(a,r))return;this._readingLocal=!0;let c;try{c=await a.read({signal:r})}finally{this._readingLocal=!1}let l=await qn(c,{api:Oe(e,this.session,r),session:this.session,resolveConflicts:this.resolveConflicts,signal:r,importedIds:o});r.throwIfAborted(),this._message=l?`Imported triage for ${l} finding${l===1?"":"s"}.`:"No local triage to import."}finally{this._importingTriage=!1,this.appState.invalidate(s),o.size>0&&this.dispatchEvent(new CustomEvent("managed-import-complete",{bubbles:!0,composed:!0}))}})}render(){if(this._role!=="admin")return m;let r=this._plan,o=r?Object.keys(r.triage).length:0,s=new Set([...r?.references??[],...r?.bundles.map(l=>l.integrity)??[]]),a=(this._catalog?.bundles??[]).filter(l=>s.has(l.integrity)),c=r?.references.filter(l=>!r.bundles.some(d=>d.integrity===l)).length??0;return b`<div class="wrap" @dragleave="${()=>{this._drag=!1}}">${zt("manage-import",this._role,this.allowShare)}<h1>Import</h1><section class="triage-import" aria-label="Local triage"><button type="button" class="btn" ?disabled="${this._busy||!this._csrf}" @click="${()=>this._importLocalTriage()}">Import triage</button><p>Import saved triage and comments from this browser by finding ID. Conflicting values prompt for resolution. Per-report ignores are skipped.</p></section><h2>Import workspace</h2><p class="intro">Create a new team from a workspace export or a workspace stored in this browser.</p><section class="${`workspace-drop ${this._drag?"dragging":""}`}" aria-label="Workspace files"><strong>Drop workspace files here</strong><span>Encrypted exports, JSON, or compressed JSON. Encrypted files prompt for a password.</span><div class="actions"><button type="button" class="btn" ?disabled="${this._busy||!this._catalog}" @click="${()=>this._browse()}">Choose files</button> <button type="button" class="btn" ?disabled="${this._busy}" @click="${()=>this._chooseLocal()}">Choose local workspace</button></div></section>${this._localOpen?b`<section class="local-choice"><label for="local-workspace">Local workspace</label> <select id="local-workspace" .value="${this._localId}" ?disabled="${this._busy}" @change="${l=>{this._localId=l.target.value}}"><option value="">Choose a workspace…</option>${this._workspaces.map(l=>b`<option value="${l.id}">${l.name}</option>`)}</select> <button type="button" class="btn" ?disabled="${this._busy||!this._localId}" @click="${()=>this._readLocal()}">Select workspace</button> ${!this._busy&&this._workspaces.length===0?b`<p>No unlocked local workspaces. Choose local workspace to unlock or refresh.</p>`:m}</section>`:m} ${r?b`<section class="import-preview" aria-label="Import options">${r.team?b`<p>Team ${r.team.name} has been created. Retry continues its remaining import steps.</p>`:m} <label for="import-team">New team name</label><input id="import-team" maxlength="100" .value="${r.name}" ?disabled="${this._busy||!!r.team}" @input="${l=>{r.name=l.target.value,this.requestUpdate()}}"><p>${r.reports.length} reports / links · ${s.size} source bundles · ${o} triaged findings</p><label for="import-repo">Repository for files and source bundles without an active repository</label> <select id="import-repo" .value="${String(this._repo??"")}" ?disabled="${this._busy||!!r.team}" @change="${l=>{this._repo=l.target.value?Number(l.target.value):null}}"><option value="" ?selected="${this._repo==null}">Choose a repository…</option>${(this._catalog?.repos??[]).map(l=>b`<option value="${String(l.repoId)}" ?selected="${this._repo===l.repoId}">${l.fullName}</option>`)}</select><p>Declared report repositories and directories are preserved. Stored reports without an active repository use the selected repository. The new team receives those repository paths; other published reports in the same paths are also visible to that team.</p><ul>${r.reports.map(l=>b`<li>${l.name}<span>${l.github??"Uses selected repository"}${l.embedded&&l.repoId==null?" \u2014 connect this repository first":""}</span></li>`)}</ul>${a.length>0?b`<p>Existing source bundles in active repositories keep their locations. The new team also receives access to those directories. Unassigned bundles and bundles in inactive repositories use the selected repository.</p><ul>${a.map(l=>b`<li>${l.filename}<span>${l.repoFullName?`${l.repoFullName}${l.repoDirectory?`/${l.repoDirectory}`:""}`:"Uses selected repository"}</span></li>`)}</ul>`:m} ${c?b`<p>${c} referenced source bundles have no bytes in this export. Reports can use matching bundles already on the server.</p>`:m} ${o?b`<fieldset ?disabled="${this._busy||!!r.team}"><legend>Import triage?</legend><label><input type="radio" name="import-triage" value="include" ?checked="${this._triage==="include"}" @change="${()=>{this._triage="include"}}"> Include triage and comments</label> <label><input type="radio" name="import-triage" value="skip" ?checked="${this._triage==="skip"}" @change="${()=>{this._triage="skip"}}"> Skip triage</label><p>Conflicting values prompt for resolution. Triage stays shared by finding ID across teams. Per-report local ignores are not imported.</p></fieldset>`:m} <button type="button" class="btn primary" ?disabled="${this._busy||!this._triage||!this._csrf}" @click="${()=>this._import()}">${this._busy?"Importing\u2026":r.team?"Retry remaining import":"Import workspace"}</button></section>`:m} ${this._message?b`<p role="status">${this._message}</p>`:m} ${this._error?b`<p class="error" role="alert">${this._error}${this._catalog?m:b`<button class="btn" @click="${()=>this._loadCatalog()}">Retry</button>`}</p>`:m} ${this._files.length>0&&!this._busy?b`<button class="btn" @click="${()=>this._nextFile()}">Next workspace file (${this._files.length} waiting)</button>`:m}</div>`}}customElements.define("managed-admin-import",n)}export{yo as registerWorkspaceImport};
|
|
54
|
+
`),imported:d}):c.comment=d}else if(a[l]!==void 0&&a[l]!==d){let u=p=>l==="flagged"?p?"flagged":"not flagged":p;n.push({id:r,property:l,local:u(a[l]),imported:u(d)})}else c[l]=d}return{entries:i,conflicts:n}}async function ho(t,e,n,i,r){r?.throwIfAborted();let{entries:o,conflicts:s}=fo(t,e);if(s.length===0)return o;let a=await i(s,n,{title:"Triage conflicts on import",intro:"disagree with stored triage on",trailingNote:"Imported comments are added alongside existing comments. Other choices apply to these finding IDs across all teams.",importedSideLabel:"Apply imported"});if(r?.throwIfAborted(),!a)throw new Error("Triage conflict resolution was cancelled.");for(let c of s){let l=a[`${c.id}:${c.property}`];if(!["local","imported"].includes(l))throw new Error("Resolve every triage conflict before importing.");l==="imported"&&(o[c.id][c.property]=t[c.id][c.property])}return o}function mo(t,e){let n=[],i={entries:{},expected:{}};for(let[r,o]of Object.entries(t)){let s={entries:{...i.entries,[r]:o},expected:{...i.expected,[r]:e[r].version}};if(new TextEncoder().encode(JSON.stringify(s)).length<=262144){i=s;continue}if(Object.keys(i.entries).length===0)throw new Error("This triage entry is too large to import.");n.push(i),i={entries:{[r]:o},expected:{[r]:e[r].version}}}return Object.keys(i.entries).length>0&&n.push(i),n}async function bt(t,{api:e,path:n,ids:i=Object.keys(t),importedIds:r=new Set,lookup:o=new Map,resolveConflicts:s,signal:a}){i=i.filter(c=>Object.hasOwn(t,c)&&!r.has(c));for(let c=0;c<i.length;c+=200){let l=i.slice(c,c+200);for(let d=0;d<5&&l.length>0;d++){a?.throwIfAborted();let{snapshots:u}=await e.send(n,{findingIds:l}),p=Object.fromEntries(l.map(f=>[f,t[f]])),h=await ho(p,u,o,s,a);for(let f of mo(h,u)){if(a?.throwIfAborted(),(await e.send(n,f)).conflict)break;Object.keys(f.entries).forEach(g=>r.add(g))}l=l.filter(f=>!r.has(f))}if(l.length>0)throw new Error("Stored triage keeps changing. Retry to resolve it against the latest values.")}}function Jn(t){if(typeof t!="string")return{ok:!0,path:null};if(/\p{Cc}/u.test(t)||t.includes("\\")||t!==t.trim())return{ok:!1};let e=[];for(let i of t.split("/"))if(!(i===""||i===".")){if(i===".."||i!==i.trim())return{ok:!1};e.push(i)}let n=e.join("/");return n.length>500?{ok:!1}:{ok:!0,path:n===""?null:n}}async function Yn(t,e){let n=new Uint8Array(await t.arrayBuffer());return be(n)?e({tryPassword:i=>Je(n,i)}):n[0]===31&&n[1]===139?Je(n):_e(new TextDecoder("utf-8",{fatal:!0}).decode(n))}async function Zn(t,e){let n=new Map,i=[];for(let s of t.reports){if(typeof s?.name!="string"||!s.name||typeof s.content!="string")throw new Error("Every report must have a name and content.");let a=yt(s.content,s.name);if(!a.data)throw new Error(`${s.name}: ${a.reason??"Unsupported report"}`);let c=ie(a.data),l=c??ie(s)??ie({repo:{github:t.repoUrls?.[s.name]}}),d=e.find(h=>h.fullName.toLowerCase()===l?.toLowerCase())?.repoId??null,u=Jn(a.data.repo?.directory);if(!u.ok)throw new Error(`${s.name}: invalid repository directory`);let p=a.format==="links"?[]:(await Wn(s.content,s.name))?.findings??[];for(let h of p)h.id&&n.set(h.id,h);i.push({...s,repoId:d,directory:u.path??"",github:l,embedded:c,ids:[...new Set(p.map(h=>h.id).filter(Boolean))],uploaded:null})}let r=Object.create(null);if(t.triage!=null&&(typeof t.triage!="object"||Array.isArray(t.triage)))throw new Error("Invalid workspace triage.");for(let[s,a]of Object.entries(t.triage??{})){if(!n.has(s))continue;let c=Le(a);if(!c)continue;let{ignoredReports:l,...d}=c;Object.keys(d).length!==0&&(r[s]=d)}let o=[];for(let s of t.bundleBlobs??[]){let a=Uint8Array.fromBase64(s.data),c=`sha512-${new Uint8Array(await crypto.subtle.digest("SHA-512",a)).toBase64()}`;if(c!==s.integrity)throw new Error(`${s.name}: bundle integrity mismatch`);o.push({name:s.name,integrity:c,bytes:a,uploaded:null})}return{name:t.workspace.name.slice(0,100),reports:i,bundles:o,triage:r,lookup:n,references:t.bundles??[],team:null,completed:new Set,importedIds:new Set}}function Oe(t,e,n){async function i(r,o,s={}){n?.throwIfAborted();let a=await t(r,{credentials:"same-origin",signal:n,...o===void 0?{}:{method:"POST",body:o instanceof File?o:JSON.stringify(o)},headers:{...o instanceof File?{}:{"content-type":"application/json"},"x-csrf-token":e.csrfToken,...s}});if(n?.throwIfAborted(),a.status===409)return{conflict:!0};if(!a.ok)throw new Error(`Import request failed (HTTP ${a.status}). You can retry the remaining steps.`);let c=await a.json();return n?.throwIfAborted(),c}return{send:i}}async function go(t,e,n,i,r,o){if(t.bundles.length===0&&t.references.length===0)return;let s=r??(await n.send("/api/admin/bundles")).bundles,a=new Set(t.bundles.map(l=>l.uploaded.id));if([...a].some(l=>!s.some(d=>d.id===l)))throw new Error("Could not verify the uploaded source bundles. Retry the import.");let c=new Set(t.references);for(let l of s){if(!a.has(l.id)&&!c.has(l.integrity))continue;let d=!o.has(l.repoId),u=d?e:l.repoId;d&&await i(`bundle-repo:${l.id}:${u}`,()=>n.send("/api/admin/bundles/set-repo",{bundleId:l.id,repoId:u}));let p=d?"":l.repoDirectory??"";await i(`repo:${u}:${p}`,()=>n.send("/api/admin/teams/set-repo",{teamId:t.team.id,repoId:u,path:p}))}}async function Qn(t,{api:e,session:n,defaultRepo:i,includeTriage:r,resolveConflicts:o,signal:s,progress:a=()=>{}}){if(n?.role!=="admin"||!n.csrfToken)throw new Error("An administrator session is required.");if(!t.name.trim()||t.name.trim().length>100)throw new Error("Enter a team name of up to 100 characters.");if(r)for(let[p,h]of Object.entries(t.triage)){if(!p||p.length>100)throw new Error(`Triage finding IDs must be between 1 and ${100} characters. Choose Skip triage to import the files without it.`);if(Me(h)==="invalid")throw new Error(`Triage for ${p} exceeds the managed server limits. Choose Skip triage to import the files without it.`)}s?.throwIfAborted();let c=null;if(t.bundles.length===0){let p=new Set(t.references);c=p.size>0?(await e.send("/api/admin/bundles")).bundles.filter(h=>p.has(h.integrity)):[]}if(t.reports.length===0&&t.bundles.length===0&&c.length===0)throw new Error(t.references.length>0?"None of the referenced source bundles are available on the server. Export with bundle bytes included and try again.":"This workspace contains no report or bundle files.");let l=new Set((await e.send("/api/admin/repositories/browsable")).repos.map(p=>p.repoId));for(let p of t.reports){if(p.embedded&&!l.has(p.repoId))throw new Error(`Connect ${p.embedded} in Repositories before importing ${p.name}.`);if(!l.has(p.repoId)&&!l.has(i))throw new Error(`Choose an active repository for ${p.name}.`)}if((t.bundles.length>0||c.some(p=>!l.has(p.repoId)))&&!l.has(i))throw new Error("Choose an active repository for the source bundles.");let d=()=>s?.throwIfAborted(),u=async(p,h)=>{d(),t.completed.has(p)||(await h(),t.completed.add(p))};if(d(),!t.team){let p=await e.send("/api/admin/teams",{name:t.name.trim()});if(p.conflict)throw new Error("A team already has this name. Choose another name.");t.team=p}await u("member",()=>e.send("/api/admin/teams/set-member",{teamId:t.team.id,userId:n.id,security:!0,dependencies:!0}));for(let p of t.bundles)d(),a(`Importing ${p.name}\u2026`),p.uploaded||(p.uploaded=await e.send("/api/admin/bundles",new File([p.bytes],p.name),{"x-bundle-filename":encodeURIComponent(p.name),"x-repo-id":String(i)}));await go(t,i,e,u,c,l);for(let p of t.reports){d(),a(`Importing ${p.name}\u2026`);let h=l.has(p.repoId)?p.repoId:i;if(!p.uploaded){let y=await e.send("/api/admin/reports",new File([p.content],p.name),{"x-report-filename":encodeURIComponent(p.name),"x-repo-id":String(h),"x-repo-directory":encodeURIComponent(p.directory)});if(y.conflict)throw new Error(`Could not reuse the stored report ${p.name}. Retry the import.`);p.uploaded=y}let f=p.uploaded;l.has(f.repoId)||await u(`report-repo:${f.id}:${h}:${p.directory}`,async()=>{if((await e.send("/api/admin/reports/set-repo",{reportId:f.id,repoId:h,directory:p.directory})).conflict)throw new Error(`Could not assign the stored report ${p.name} to its repository.`);f.repoId=h,f.repoDirectory=p.directory});let g=f.repoDirectory??"";await u(`repo:${f.repoId}:${g}`,()=>e.send("/api/admin/teams/set-repo",{teamId:t.team.id,repoId:f.repoId,path:g})),r&&await bt(t.triage,{api:e,resolveConflicts:o,signal:s,ids:p.ids,importedIds:t.importedIds,lookup:t.lookup,path:`/api/admin/reports/${encodeURIComponent(p.uploaded.id)}/import-triage`}),await u(`publish:${p.uploaded.id}`,()=>e.send("/api/admin/reports/set-visible",{reportId:p.uploaded.id,visible:!0}))}return t.team}function er(t){let e=()=>t.isEncryptionEnabled()&&!t.isUnlocked();return{get locked(){return e()},unlock:n=>t.unlockEncryption(n),async read({signal:n}={}){let i=!1,r=t.onVaultStateChange(()=>{i=!0}),o=()=>{if(n?.throwIfAborted(),e()||i)throw new Error("Local data was locked or changed. Unlock it and import triage again.")};try{o();let s=await t.readTriageBlob();return o(),s}finally{r()}}}}function Ne(t){let e=()=>t.isEncryptionEnabled()&&!t.isUnlocked();async function n(){let r=JSON.parse(await t.hydrateKey("deepview.workspaces")||"[]");return(Array.isArray(r)?r:r.workspaces??[]).filter(o=>typeof o.id=="string"&&typeof o.name=="string")}async function i(r,o){let s=!1,a=[t.onVaultStateChange,t.onFileMutated,t.onBundleMutated].map(l=>l(()=>{s=!0})),c=()=>{if(o?.throwIfAborted(),e()||s)throw new Error("Local data was locked or changed. Unlock it and select the workspace again.")};try{c();let l=await r(c);return c(),l}finally{a.forEach(l=>l())}}return{get locked(){return e()},unlock:r=>t.unlockEncryption(r),list:({signal:r}={})=>i(async()=>(await n()).map(o=>({id:o.id,name:o.name})),r),read:(r,{signal:o}={})=>i(async s=>{let a=(await n()).find(f=>f.id===r);if(!a)throw new Error("This local workspace no longer exists.");let c=JSON.stringify(a),l=JSON.parse(await t.hydrateKey("deepview.repoUrls")||"{}"),d=[];for(let f of a.reports??[]){s();let g=await t.withStoredItem("report",f,()=>t.readFile(f));s(),d.push({name:f,content:g,...l[f]?{repo:{github:l[f]}}:{}})}let u=await t.listBundles(),p=[];for(let f of a.bundles??[]){s();let g=u.find(x=>x.integrity===f);if(!g)continue;let y=await t.withStoredItem("bundle",f,()=>t.readBundle(f));s(),p.push({integrity:f,name:g.name,data:y.toBase64()})}let h=await t.readTriageBlob()??{};if(JSON.stringify((await n()).find(f=>f.id===r))!==c)throw new Error("The local workspace changed. Select it again.");return{version:1,workspace:{id:r,name:a.name,privateKey:""},reports:d,bundles:a.bundles??[],bundleBlobs:p,triage:h,repoUrls:l}},o)}}function yo(t,e){if(customElements.get("managed-admin-import"))return;class n extends t{static styles=[G(jt),G(Vt)];static properties={localDeps:{attribute:!1},_busy:{state:!0},_error:{state:!0},_message:{state:!0},_plan:{state:!0},_catalog:{state:!0},_localOpen:{state:!0},_workspaces:{state:!0},_localId:{state:!0},_triage:{state:!0},_repo:{state:!0},_drag:{state:!0}};constructor(){super(),this._busy=!1,this._error="",this._message="",this._plan=null,this._catalog=null,this._workspaces=[],this._localOpen=!1,this._localId="",this._triage="",this._repo=null,this._files=[],this._drag=!1,this._local=!1,this._over=r=>{r.dataTransfer?.types?.includes("Files")&&(r.preventDefault(),this._drag=!0)},this._drop=r=>{r.dataTransfer?.types?.includes("Files")&&(r.preventDefault(),r.stopPropagation(),this._drag=!1,this._busy||(this._files.push(...r.dataTransfer.files),this._nextFile()))},this._localChanged=()=>{this._workspaces=[],this._localId="",!this._unlocking&&(this._local&&(this._plan=null),(this._local||this._importingTriage)&&(this._operation?.abort(),this._message="",this._error=this._importingTriage?"Local data changed or was locked. Import triage again to continue.":"Local data changed or was locked. Choose the workspace again."))},this._blur=()=>{this._readingLocal&&this._localChanged()}}connectedCallback(){super.connectedCallback(),this.addEventListener("dragover",this._over),this.addEventListener("drop",this._drop),globalThis.addEventListener("blur",this._blur),globalThis.addEventListener("storage",this._localChanged),this._offVault=this.localDeps?.onVaultStateChange(this._localChanged),this._loadCatalog()}disconnectedCallback(){this._operation?.abort(),this._offVault?.(),this._plan=null,this._files=[],this.removeEventListener("dragover",this._over),this.removeEventListener("drop",this._drop),globalThis.removeEventListener("blur",this._blur),globalThis.removeEventListener("storage",this._localChanged),super.disconnectedCallback()}updated(r){r.has("session")&&(this._role!=="admin"||r.get("session")?.id!==this.session?.id)&&(this._operation?.abort(),this._plan=null,this._files=[])}async _action(r){if(this._busy||this._role!=="admin")return;let o=this._operation=new AbortController,s=AbortSignal.any([o.signal,this.appState.sessionController.signal]);this._busy=!0,this._error="";try{await r(s),s.throwIfAborted()}catch(a){s.aborted||(this._error=String(a?.message??a))}finally{this._operation===o&&(this._busy=!1)}}async _loadCatalog(){if(this._role==="admin")try{await this._loadCollection("workspace-import:catalog","import options",async r=>{let o=Oe(e,this.session,r),[s,a,c]=await Promise.all([o.send("/api/admin/reports"),o.send("/api/admin/teams"),o.send("/api/admin/bundles")]);return{repos:s.repos,teams:a.teams,bundles:c.bundles}},r=>{this._catalog=r})}catch(r){this._error=String(r?.message??r)}}_browse(){let r=document.createElement("input");r.type="file",r.multiple=!0,r.accept=".enc,.gz,.json",r.addEventListener("change",()=>{this._files.push(...r.files),this._nextFile()},{once:!0}),r.click()}async _prepare(r,o){if(!r)return;if(this._catalog||await this._loadCatalog(),o.throwIfAborted(),!this._catalog)throw new Error("Could not load repositories. Try again.");let s=await Zn(r,this._catalog.repos);o.throwIfAborted();let a=new Set(this._catalog.teams.map(u=>u.name)),c=s.name||"Imported workspace",l=2;for(;a.has(s.name);){let u=` (${l++})`;s.name=c.slice(0,100-u.length)+u}let d=new Set(s.reports.map(u=>u.repoId).filter(u=>u!=null));this._repo=d.size===1?[...d][0]:null,this._triage=Object.keys(s.triage).length>0?"":"skip",this._plan=s,this._message=""}async _nextFile(){if(this._files.length===0||this._busy)return;let r=this._files.shift();this._local=!1,this._plan=null,await this._action(async o=>{let s=await Yn(r,this.promptPassword);o.throwIfAborted(),await this._prepare(s,o)})}async _unlock(r,o){this._unlocking=!0;try{return!r.locked||await r.unlock({signal:o})}finally{this._unlocking=!1}}async _chooseLocal(){this._localOpen=!0,await this._action(async r=>{let o=Ne(this.localDeps);await this._unlock(o,r)&&(r.throwIfAborted(),this._workspaces=await o.list({signal:r}))})}async _readLocal(){if(!this._localId)return;let r=this._localId;this._local=!0,this._plan=null,await this._action(async o=>{let s=Ne(this.localDeps);if(await this._unlock(s,o)){this._readingLocal=!0;try{await this._prepare(await s.read(r,{signal:o}),o)}finally{this._readingLocal=!1}}})}async _import(){!this._plan||!this._triage||!this._csrf||(await this._action(async r=>{if(this._local&&Ne(this.localDeps).locked)throw new Error("Unlock local data and choose the workspace again.");let o=this._plan,s=["teams","reports","bundles","history","workspace-import","scan-sources","repo-impact"];try{let a=await this.appState.mutate(()=>Qn(o,{api:Oe(e,this.session,r),session:this.session,defaultRepo:this._repo,includeTriage:this._triage==="include",resolveConflicts:this.resolveConflicts,signal:r,progress:c=>{this._message=c}}),s);this._catalog.teams.push(a),this._message=`Imported into ${a.name}.`,this._plan=null}finally{this.appState.invalidate(s),o.team&&this.dispatchEvent(new CustomEvent("managed-import-complete",{bubbles:!0,composed:!0}))}}),!this._plan&&!this._error&&await this._nextFile())}async _importLocalTriage(){this._csrf&&await this._action(async r=>{this._importingTriage=!0,this._message="";let o=new Set,s=["reports","history"];try{let a=er(this.localDeps);if(!await this._unlock(a,r))return;this._readingLocal=!0;let c;try{c=await a.read({signal:r})}finally{this._readingLocal=!1}let l=await qn(c,{api:Oe(e,this.session,r),session:this.session,resolveConflicts:this.resolveConflicts,signal:r,importedIds:o});r.throwIfAborted(),this._message=l?`Imported triage for ${l} finding${l===1?"":"s"}.`:"No local triage matches findings in managed reports."}finally{this._importingTriage=!1,this.appState.invalidate(s),o.size>0&&this.dispatchEvent(new CustomEvent("managed-import-complete",{bubbles:!0,composed:!0}))}})}render(){if(this._role!=="admin")return m;let r=this._plan,o=r?Object.keys(r.triage).length:0,s=new Set([...r?.references??[],...r?.bundles.map(l=>l.integrity)??[]]),a=(this._catalog?.bundles??[]).filter(l=>s.has(l.integrity)),c=r?.references.filter(l=>!r.bundles.some(d=>d.integrity===l)).length??0;return b`<div class="wrap" @dragleave="${()=>{this._drag=!1}}">${zt("manage-import",this._role,this.allowShare)}<h1>Import</h1><section class="triage-import" aria-label="Local triage"><button type="button" class="btn" ?disabled="${this._busy||!this._csrf}" @click="${()=>this._importLocalTriage()}">Import triage</button><p>Import saved triage and comments for findings already in managed reports. Unmatched data stays in this browser. Conflicting values prompt for resolution; per-report ignores are skipped.</p></section><h2>Import workspace</h2><p class="intro">Create a new team from a workspace export or a workspace stored in this browser.</p><section class="${`workspace-drop ${this._drag?"dragging":""}`}" aria-label="Workspace files"><strong>Drop workspace files here</strong><span>Encrypted exports, JSON, or compressed JSON. Encrypted files prompt for a password.</span><div class="actions"><button type="button" class="btn" ?disabled="${this._busy||!this._catalog}" @click="${()=>this._browse()}">Choose files</button> <button type="button" class="btn" ?disabled="${this._busy}" @click="${()=>this._chooseLocal()}">Choose local workspace</button></div></section>${this._localOpen?b`<section class="local-choice"><label for="local-workspace">Local workspace</label> <select id="local-workspace" .value="${this._localId}" ?disabled="${this._busy}" @change="${l=>{this._localId=l.target.value}}"><option value="">Choose a workspace…</option>${this._workspaces.map(l=>b`<option value="${l.id}">${l.name}</option>`)}</select> <button type="button" class="btn" ?disabled="${this._busy||!this._localId}" @click="${()=>this._readLocal()}">Select workspace</button> ${!this._busy&&this._workspaces.length===0?b`<p>No unlocked local workspaces. Choose local workspace to unlock or refresh.</p>`:m}</section>`:m} ${r?b`<section class="import-preview" aria-label="Import options">${r.team?b`<p>Team ${r.team.name} has been created. Retry continues its remaining import steps.</p>`:m} <label for="import-team">New team name</label><input id="import-team" maxlength="100" .value="${r.name}" ?disabled="${this._busy||!!r.team}" @input="${l=>{r.name=l.target.value,this.requestUpdate()}}"><p>${r.reports.length} reports / links · ${s.size} source bundles · ${o} triaged findings</p><label for="import-repo">Repository for files and source bundles without an active repository</label> <select id="import-repo" .value="${String(this._repo??"")}" ?disabled="${this._busy||!!r.team}" @change="${l=>{this._repo=l.target.value?Number(l.target.value):null}}"><option value="" ?selected="${this._repo==null}">Choose a repository…</option>${(this._catalog?.repos??[]).map(l=>b`<option value="${String(l.repoId)}" ?selected="${this._repo===l.repoId}">${l.fullName}</option>`)}</select><p>Declared report repositories and directories are preserved. Stored reports without an active repository use the selected repository. The new team receives those repository paths; other published reports in the same paths are also visible to that team.</p><ul>${r.reports.map(l=>b`<li>${l.name}<span>${l.github??"Uses selected repository"}${l.embedded&&l.repoId==null?" \u2014 connect this repository first":""}</span></li>`)}</ul>${a.length>0?b`<p>Existing source bundles in active repositories keep their locations. The new team also receives access to those directories. Unassigned bundles and bundles in inactive repositories use the selected repository.</p><ul>${a.map(l=>b`<li>${l.filename}<span>${l.repoFullName?`${l.repoFullName}${l.repoDirectory?`/${l.repoDirectory}`:""}`:"Uses selected repository"}</span></li>`)}</ul>`:m} ${c?b`<p>${c} referenced source bundles have no bytes in this export. Reports can use matching bundles already on the server.</p>`:m} ${o?b`<fieldset ?disabled="${this._busy||!!r.team}"><legend>Import triage?</legend><label><input type="radio" name="import-triage" value="include" ?checked="${this._triage==="include"}" @change="${()=>{this._triage="include"}}"> Include triage and comments</label> <label><input type="radio" name="import-triage" value="skip" ?checked="${this._triage==="skip"}" @change="${()=>{this._triage="skip"}}"> Skip triage</label><p>Conflicting values prompt for resolution. Triage stays shared by finding ID across teams. Per-report local ignores are not imported.</p></fieldset>`:m} <button type="button" class="btn primary" ?disabled="${this._busy||!this._triage||!this._csrf}" @click="${()=>this._import()}">${this._busy?"Importing\u2026":r.team?"Retry remaining import":"Import workspace"}</button></section>`:m} ${this._message?b`<p role="status">${this._message}</p>`:m} ${this._error?b`<p class="error" role="alert">${this._error}${this._catalog?m:b`<button class="btn" @click="${()=>this._loadCatalog()}">Retry</button>`}</p>`:m} ${this._files.length>0&&!this._busy?b`<button class="btn" @click="${()=>this._nextFile()}">Next workspace file (${this._files.length} waiting)</button>`:m}</div>`}}customElements.define("managed-admin-import",n)}export{yo as registerWorkspaceImport};
|
|
55
55
|
/*! Bundled license information:
|
|
56
56
|
|
|
57
57
|
@lit/reactive-element/css-tag.js:
|