@preventive/triage 1.0.0-alpha.8 → 1.0.0-alpha.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (442) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +16 -78
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +6 -0
  13. package/common/bundle-compare-diff.js +377 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-imports.js +20 -0
  20. package/common/bundle-metadata.d.ts +15 -0
  21. package/common/bundle-metadata.js +226 -0
  22. package/common/bundle-pkg-of.d.ts +1 -0
  23. package/common/bundle-pkg-of.js +90 -0
  24. package/common/bundle-reasons.d.ts +6 -0
  25. package/common/bundle-reasons.js +58 -0
  26. package/common/bundle-source-links.d.ts +6 -0
  27. package/common/bundle-source-links.js +216 -0
  28. package/common/bundle-sourcemap.d.ts +10 -0
  29. package/common/bundle-sourcemap.js +100 -0
  30. package/common/bundle-sources.d.ts +10 -0
  31. package/common/bundle-sources.js +374 -0
  32. package/common/bundle-stats.js +41 -0
  33. package/common/bundle-tabs.js +1 -0
  34. package/common/code-language.js +66 -0
  35. package/common/default-scan-models.ts +36 -0
  36. package/common/dependency-reviews.d.ts +18 -0
  37. package/common/dependency-reviews.js +64 -0
  38. package/common/finding-duplicates.js +63 -0
  39. package/common/finding-filters.js +313 -0
  40. package/common/finding-id.js +47 -0
  41. package/common/finding-repo.d.ts +5 -0
  42. package/common/finding-repo.js +67 -0
  43. package/common/github-issue-labels.d.ts +1 -0
  44. package/common/github-issue-labels.js +11 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +14 -0
  48. package/common/line-diff.js +181 -0
  49. package/common/linked-workspace-groups.js +63 -0
  50. package/common/managed/agent-tasks.ts +292 -0
  51. package/common/managed/comments.ts +43 -0
  52. package/common/managed/dependency-routes.js +25 -0
  53. package/common/managed/directory-packages.ts +28 -0
  54. package/common/managed/finding-detail.d.ts +5 -0
  55. package/common/managed/finding-detail.js +75 -0
  56. package/common/managed/finding-values.d.ts +2 -0
  57. package/common/managed/finding-values.js +138 -0
  58. package/common/managed/github-agents.ts +114 -0
  59. package/common/managed/github-logins.ts +49 -0
  60. package/common/managed/lite-name.d.ts +2 -0
  61. package/common/managed/lite-name.js +20 -0
  62. package/common/managed/npm-packages.d.ts +9 -0
  63. package/common/managed/npm-packages.js +63 -0
  64. package/common/managed/permissions.ts +31 -0
  65. package/common/managed/report-content.ts +72 -0
  66. package/common/managed/report-filter.ts +120 -0
  67. package/common/managed/repository-alias.ts +65 -0
  68. package/common/managed/review-view-routes.js +23 -0
  69. package/common/managed/risk-routes.js +30 -0
  70. package/common/managed/roles.ts +41 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +385 -0
  73. package/common/managed/scan-models.ts +6 -0
  74. package/common/managed/stasis-config.ts +7 -0
  75. package/common/managed/team-app.d.ts +19 -0
  76. package/common/managed/team-app.js +129 -0
  77. package/common/managed/team-filters.js +26 -0
  78. package/common/managed/triage.ts +83 -0
  79. package/common/managed/upload-seal.ts +126 -0
  80. package/common/pretty-json.js +98 -0
  81. package/common/pretty-kinds.js +20 -0
  82. package/common/pretty-print.d.ts +6 -0
  83. package/common/pretty-print.js +36 -0
  84. package/common/pretty-sourcemap.js +70 -0
  85. package/common/repo-commit.d.ts +4 -0
  86. package/common/repo-commit.js +30 -0
  87. package/common/revalidation-conflicts.js +48 -0
  88. package/common/revalidation-input-groups.js +56 -0
  89. package/common/save-error-reason.ts +20 -7
  90. package/common/scan-server.ts +13 -0
  91. package/common/security-links.d.ts +5 -0
  92. package/common/security-links.js +33 -0
  93. package/common/server-info.ts +46 -0
  94. package/common/sourcemap-listing.js +78 -0
  95. package/common/sourcemap-mappings.js +136 -0
  96. package/common/sourcemap-unlist.js +85 -0
  97. package/common/stasis-files.d.ts +5 -0
  98. package/common/stasis-files.js +20 -0
  99. package/common/stasis-tgz.d.ts +6 -0
  100. package/common/stasis-tgz.js +27 -0
  101. package/common/utf8.d.ts +3 -0
  102. package/common/utf8.js +45 -0
  103. package/common/whitespace-insensitive.js +19 -0
  104. package/common/workspace-app.js +91 -0
  105. package/common/workspace-groups.js +176 -0
  106. package/out/activity.js +2 -0
  107. package/out/brotli-fallback.js +3 -3
  108. package/out/chunk-2XUEZHIP.js +28 -0
  109. package/out/chunk-55YIWY3H.js +5 -0
  110. package/out/chunk-5AVGKFMR.js +1 -0
  111. package/out/chunk-5CJKUV53.js +1 -0
  112. package/out/chunk-5EAVJAD2.js +3 -0
  113. package/out/chunk-5M2X3QPK.js +6 -0
  114. package/out/chunk-5QWPKTCE.js +40 -0
  115. package/out/chunk-6CCSTJWB.js +1 -0
  116. package/out/chunk-6VOB5WXX.js +2 -0
  117. package/out/chunk-6Y6PZ2BU.js +9 -0
  118. package/out/chunk-74JZTGTO.js +11 -0
  119. package/out/chunk-7BKKYVWR.js +7 -0
  120. package/out/chunk-7C7DWL7I.js +1 -0
  121. package/out/chunk-7HP2VYIC.js +2 -0
  122. package/out/chunk-7YFJUT2P.js +1 -0
  123. package/out/chunk-7YO4QV5P.js +1 -0
  124. package/out/chunk-A4BBBHQU.js +1 -0
  125. package/out/chunk-B64CTMVU.js +4 -0
  126. package/out/chunk-BEKYZCPX.js +14 -0
  127. package/out/chunk-C4Z6ZBXV.js +10 -0
  128. package/out/chunk-CU3FPB3P.js +1 -0
  129. package/out/chunk-DEVAORP2.js +1 -0
  130. package/out/chunk-DUASGS2O.js +8 -0
  131. package/out/chunk-DUS5ARE2.js +53 -0
  132. package/out/chunk-EEJA7JBI.js +13 -0
  133. package/out/chunk-FSU2PLJL.js +1 -0
  134. package/out/chunk-GBMAXAYK.js +3 -0
  135. package/out/chunk-GO7FT4OD.js +1 -0
  136. package/out/chunk-GX5UXWT4.js +1 -0
  137. package/out/chunk-ITUKKCCK.js +10 -0
  138. package/out/chunk-IYPY47MC.js +1 -0
  139. package/out/chunk-JXBRWLMA.js +4 -0
  140. package/out/chunk-K4XJHM2T.js +1 -0
  141. package/out/chunk-LBD3M3J6.js +1 -0
  142. package/out/chunk-LVSLM7HB.js +1 -0
  143. package/out/chunk-LVW7WWV4.js +1 -0
  144. package/out/chunk-MV66NL3G.js +3 -0
  145. package/out/chunk-N57OWFKY.js +15 -0
  146. package/out/chunk-NRPC74AM.js +1 -0
  147. package/out/chunk-OOJM4CTU.js +1 -0
  148. package/out/chunk-OWSEQOL5.js +1 -0
  149. package/out/chunk-PKLVXUEI.js +11 -0
  150. package/out/chunk-PLGH63UC.js +2 -0
  151. package/out/chunk-PNHBZGDD.js +1 -0
  152. package/out/chunk-PTFYDJUP.js +1 -0
  153. package/out/chunk-PWFUOLZK.js +17 -0
  154. package/out/chunk-PXK7EU4V.js +1 -0
  155. package/out/chunk-QD3IBSF4.js +7 -0
  156. package/out/chunk-QI66YA4F.js +1 -0
  157. package/out/chunk-QRKFPLA4.js +80 -0
  158. package/out/chunk-R3NZFXVR.js +1 -0
  159. package/out/chunk-R5O6FAW4.js +2 -0
  160. package/out/chunk-RPNO56H2.js +1 -0
  161. package/out/chunk-SSPDMA6D.js +1 -0
  162. package/out/chunk-SZWPYLPC.js +1 -0
  163. package/out/chunk-TUII34K2.js +1 -0
  164. package/out/chunk-UJP4PQJA.js +1 -0
  165. package/out/chunk-UJSJMXEG.js +1 -0
  166. package/out/chunk-UR4WYMIP.js +1 -0
  167. package/out/chunk-VHEXSGGP.js +1 -0
  168. package/out/chunk-VYYUMYVW.js +9 -0
  169. package/out/chunk-VZPPX6MV.js +1 -0
  170. package/out/chunk-WCDYSIKG.js +1 -0
  171. package/out/chunk-XM4RLC4A.js +2 -0
  172. package/out/chunk-YKCRCNYZ.js +266 -0
  173. package/out/chunk-ZQHLECTI.js +1 -0
  174. package/out/client-managed-import.js +4 -0
  175. package/out/client-managed.js +37 -0
  176. package/out/client-sync.js +11 -17
  177. package/out/compare.js +26 -0
  178. package/out/dialogs.js +40 -0
  179. package/out/github-issue-authorized.html +3 -0
  180. package/out/github-issue-authorized.js +1 -0
  181. package/out/graph.js +19 -4
  182. package/out/index.html +104 -24
  183. package/out/prism.js +14 -10
  184. package/out/scan.js +2 -0
  185. package/out/stasis.svg +20 -0
  186. package/out/terminal.js +367 -39
  187. package/out/view.css +1 -1
  188. package/out/view.js +19 -147
  189. package/package.json +409 -64
  190. package/risk/actions/findings.js +161 -0
  191. package/risk/actions/resolve.js +287 -0
  192. package/risk/actions/scripts/commands.js +182 -0
  193. package/risk/actions/scripts/grade.js +113 -0
  194. package/risk/actions/scripts/packages.js +123 -0
  195. package/risk/actions/scripts/shell.js +169 -0
  196. package/risk/actions/uses.js +94 -0
  197. package/risk/actions/workflow.js +183 -0
  198. package/risk/files/characters.js +341 -0
  199. package/risk/files/hosts.js +206 -0
  200. package/risk/files/readability.js +185 -0
  201. package/risk/files/runs-code.js +563 -0
  202. package/risk/files/script.js +402 -0
  203. package/risk/files/source-map-link.js +43 -0
  204. package/risk/files/stamps.js +47 -0
  205. package/risk/index.d.ts +294 -0
  206. package/risk/index.js +12 -0
  207. package/risk/npm/assess.js +285 -0
  208. package/risk/npm/combined.js +68 -0
  209. package/risk/npm/compare.js +236 -0
  210. package/risk/npm/dependencies.js +172 -0
  211. package/risk/npm/diff.js +79 -0
  212. package/risk/npm/downloads.js +84 -0
  213. package/risk/npm/files.js +445 -0
  214. package/risk/npm/held.js +67 -0
  215. package/risk/npm/install-scripts.js +34 -0
  216. package/risk/npm/malware.js +38 -0
  217. package/risk/npm/manifest.js +65 -0
  218. package/risk/npm/new-dependency.js +60 -0
  219. package/risk/npm/old-version.js +108 -0
  220. package/risk/npm/registry.js +393 -0
  221. package/risk/npm/release.js +85 -0
  222. package/risk/npm/score.js +59 -0
  223. package/risk/npm/specs.js +124 -0
  224. package/risk/npm/tarball.js +169 -0
  225. package/server-common/database-config.ts +16 -0
  226. package/server-common/initialize.ts +18 -0
  227. package/server-common/npm-advisories.ts +101 -0
  228. package/{server → server-common}/origin.ts +5 -5
  229. package/server-common/reap.ts +48 -0
  230. package/server-common/scan-config.ts +19 -0
  231. package/server-common/standalone.ts +29 -0
  232. package/server-common/storage-crypto.ts +182 -0
  233. package/server-common/storage-log.ts +38 -0
  234. package/server-common/vercel-blob.ts +103 -0
  235. package/server-e2e/app.ts +487 -0
  236. package/{server → server-e2e}/bus-receiver.ts +2 -1
  237. package/{server → server-e2e}/cli.js +9 -4
  238. package/{server → server-e2e}/config.ts +50 -42
  239. package/{server → server-e2e}/db-neon.ts +2 -2
  240. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  241. package/{server → server-e2e}/db-stmt.ts +2 -2
  242. package/{server → server-e2e}/db.ts +7 -7
  243. package/{server → server-e2e}/http.ts +44 -13
  244. package/{server → server-e2e}/hub.ts +40 -9
  245. package/server-e2e/index.ts +17 -0
  246. package/server-e2e/lifecycle.ts +95 -0
  247. package/{server → server-e2e}/neon-driver.ts +2 -2
  248. package/{server → server-e2e}/npm-proxy.ts +12 -145
  249. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  250. package/{server → server-e2e}/objstore/blob.ts +1 -1
  251. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  252. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  253. package/{server → server-e2e}/objstore/init.ts +19 -27
  254. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  255. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  257. package/{server → server-e2e}/objstore/rest.ts +3 -3
  258. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  259. package/{server → server-e2e}/objstore/store.ts +7 -7
  260. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  261. package/{server → server-e2e}/pubsub.ts +12 -9
  262. package/{server → server-e2e}/sign.ts +4 -4
  263. package/{server → server-e2e}/sse-server.ts +60 -33
  264. package/{server → server-e2e}/static.ts +18 -17
  265. package/{server → server-e2e}/sync-handlers.ts +64 -30
  266. package/{server → server-e2e}/ws-server.ts +20 -9
  267. package/server-managed/activity.ts +247 -0
  268. package/server-managed/agent-merges.ts +109 -0
  269. package/server-managed/app-agents.ts +23 -0
  270. package/server-managed/avatar-store.ts +13 -0
  271. package/server-managed/blob-store.ts +26 -0
  272. package/server-managed/brotli.ts +10 -0
  273. package/server-managed/bundle-advisories.ts +79 -0
  274. package/server-managed/bundle-advisory-inventory.ts +85 -0
  275. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  276. package/server-managed/bundle-build-diagnostics.js +23 -0
  277. package/server-managed/bundle-build-leases.ts +41 -0
  278. package/server-managed/bundle-build-worker.js +380 -0
  279. package/server-managed/bundle-build.ts +326 -0
  280. package/server-managed/bundle-cache.ts +261 -0
  281. package/server-managed/bundle-catalog.ts +29 -0
  282. package/server-managed/bundle-commits.ts +133 -0
  283. package/server-managed/bundle-dependency-reviews.ts +91 -0
  284. package/server-managed/bundle-store.ts +24 -0
  285. package/server-managed/bundle-summary-cache.ts +139 -0
  286. package/server-managed/bundle-validation.ts +33 -0
  287. package/server-managed/bundle.ts +151 -0
  288. package/server-managed/cache-storage.ts +20 -0
  289. package/server-managed/cli.js +21 -0
  290. package/server-managed/combined.ts +43 -0
  291. package/server-managed/comments.ts +138 -0
  292. package/server-managed/commit-coauthors.ts +105 -0
  293. package/server-managed/commit-lockfiles.ts +78 -0
  294. package/server-managed/comparison.ts +51 -0
  295. package/server-managed/config.ts +163 -0
  296. package/server-managed/content-access.ts +15 -0
  297. package/server-managed/crypto.ts +25 -0
  298. package/server-managed/db-methods.ts +1914 -0
  299. package/server-managed/db-neon.ts +398 -0
  300. package/server-managed/db-schema.ts +263 -0
  301. package/server-managed/db-table-names.ts +22 -0
  302. package/server-managed/db.ts +149 -0
  303. package/server-managed/dependabot-access.ts +61 -0
  304. package/server-managed/dependabot-alerts.ts +180 -0
  305. package/server-managed/dependency-review-comments.ts +143 -0
  306. package/server-managed/dependency-reviews.ts +369 -0
  307. package/server-managed/github-accounts.ts +59 -0
  308. package/server-managed/github-actions.ts +71 -0
  309. package/server-managed/github-app.ts +347 -0
  310. package/server-managed/github-errors.ts +92 -0
  311. package/server-managed/github-graphql.ts +42 -0
  312. package/server-managed/github-issue-links.ts +264 -0
  313. package/server-managed/github-issue-oauth.ts +30 -0
  314. package/server-managed/github-issues.ts +157 -0
  315. package/server-managed/github-link-oauth.ts +56 -0
  316. package/server-managed/github-links.ts +204 -0
  317. package/server-managed/github-metadata.ts +213 -0
  318. package/server-managed/github-oauth.ts +264 -0
  319. package/server-managed/github-pulls.ts +257 -0
  320. package/server-managed/github-requests.ts +181 -0
  321. package/server-managed/github-users.ts +30 -0
  322. package/server-managed/github-values.ts +26 -0
  323. package/server-managed/history-windows.ts +172 -0
  324. package/server-managed/http-response.ts +76 -0
  325. package/server-managed/http.ts +6324 -0
  326. package/server-managed/import-triage.ts +51 -0
  327. package/server-managed/index.ts +204 -0
  328. package/server-managed/kept-briefly.ts +37 -0
  329. package/server-managed/kept.ts +28 -0
  330. package/server-managed/link-reports.ts +149 -0
  331. package/server-managed/listed-activity.ts +39 -0
  332. package/server-managed/locked-packages.ts +234 -0
  333. package/server-managed/lockfile-scope.ts +58 -0
  334. package/server-managed/lru.ts +30 -0
  335. package/server-managed/managed-issues.ts +92 -0
  336. package/server-managed/management-catalog.ts +45 -0
  337. package/server-managed/management.ts +116 -0
  338. package/server-managed/npm-delta-worker.js +142 -0
  339. package/server-managed/npm-delta.ts +277 -0
  340. package/server-managed/npm-insights.ts +455 -0
  341. package/server-managed/npm-kept.ts +265 -0
  342. package/server-managed/npm-loads.ts +259 -0
  343. package/server-managed/npm-manifest.ts +117 -0
  344. package/server-managed/npm-packages.ts +469 -0
  345. package/server-managed/npm-patch-paths.ts +86 -0
  346. package/server-managed/npm-patch.ts +455 -0
  347. package/server-managed/npm-provenance.ts +127 -0
  348. package/server-managed/npm-risk.ts +287 -0
  349. package/server-managed/object-storage-disk.ts +147 -0
  350. package/server-managed/object-storage-vercel.ts +71 -0
  351. package/server-managed/object-storage.ts +82 -0
  352. package/server-managed/package-entry-points.ts +127 -0
  353. package/server-managed/pretty-copies.ts +22 -0
  354. package/server-managed/pretty-format.d.ts +3 -0
  355. package/server-managed/pretty-format.js +13 -0
  356. package/server-managed/pretty-print.ts +442 -0
  357. package/server-managed/public-workspace.ts +243 -0
  358. package/server-managed/pull-comment-reviews.ts +161 -0
  359. package/server-managed/pull-dependencies.ts +370 -0
  360. package/server-managed/pull-dependency-reviews.ts +407 -0
  361. package/server-managed/pull-reviews.ts +202 -0
  362. package/server-managed/queue.ts +54 -0
  363. package/server-managed/release-commits.ts +85 -0
  364. package/server-managed/rename-diff-worker.js +30 -0
  365. package/server-managed/rename-diff.ts +237 -0
  366. package/server-managed/repo-path.ts +21 -0
  367. package/server-managed/report-migration.ts +32 -0
  368. package/server-managed/report-opening.ts +77 -0
  369. package/server-managed/report-query.ts +10 -0
  370. package/server-managed/report-response.ts +16 -0
  371. package/server-managed/report-sources.ts +185 -0
  372. package/server-managed/report-store.ts +77 -0
  373. package/server-managed/repository-actions.ts +220 -0
  374. package/server-managed/repository-agents.ts +422 -0
  375. package/server-managed/repository-aliases.ts +119 -0
  376. package/server-managed/repository-browser.ts +361 -0
  377. package/server-managed/repository-changes.ts +280 -0
  378. package/server-managed/repository-code.ts +222 -0
  379. package/server-managed/repository-dependency-reviews.ts +182 -0
  380. package/server-managed/repository-discovery.ts +83 -0
  381. package/server-managed/repository-history.ts +428 -0
  382. package/server-managed/repository-issues.ts +293 -0
  383. package/server-managed/repository-policy.ts +27 -0
  384. package/server-managed/repository-pulls.ts +207 -0
  385. package/server-managed/repository-pulse.ts +477 -0
  386. package/server-managed/repository-risk-assess.ts +108 -0
  387. package/server-managed/repository-risk-audit.ts +78 -0
  388. package/server-managed/repository-risk-caches.ts +37 -0
  389. package/server-managed/repository-risk-read.ts +260 -0
  390. package/server-managed/repository-risk-stasis.ts +61 -0
  391. package/server-managed/repository-risk-turn.ts +97 -0
  392. package/server-managed/repository-risk.ts +516 -0
  393. package/server-managed/repository-squashes.ts +160 -0
  394. package/server-managed/repository-stamp.ts +41 -0
  395. package/server-managed/request-timing.ts +63 -0
  396. package/server-managed/reviewed-dependencies.ts +170 -0
  397. package/server-managed/revisions.ts +35 -0
  398. package/server-managed/scan-downloads.ts +121 -0
  399. package/server-managed/session.ts +132 -0
  400. package/server-managed/slugs.ts +38 -0
  401. package/server-managed/solidity-entry-points.ts +71 -0
  402. package/server-managed/sql-postgres.ts +34 -0
  403. package/server-managed/sql.ts +107 -0
  404. package/server-managed/stasis-config.ts +147 -0
  405. package/server-managed/stasis-dependencies.ts +221 -0
  406. package/server-managed/static.ts +28 -0
  407. package/server-managed/storage-command.ts +16 -0
  408. package/server-managed/storage-db.ts +183 -0
  409. package/server-managed/storage-encryption.ts +288 -0
  410. package/server-managed/storage-maintenance.ts +259 -0
  411. package/server-managed/storage-payload.ts +121 -0
  412. package/server-managed/storage-stores.ts +91 -0
  413. package/server-managed/storage.ts +82 -0
  414. package/server-managed/team-app-summaries.ts +56 -0
  415. package/server-managed/team-app.ts +156 -0
  416. package/server-managed/team-catalog.ts +7 -0
  417. package/server-managed/team-feed.ts +180 -0
  418. package/server-managed/team-npm-scopes.ts +103 -0
  419. package/server-managed/team-reports.ts +368 -0
  420. package/server-managed/triage-response.ts +16 -0
  421. package/server-managed/type-only-proof.js +161 -0
  422. package/server-managed/type-only-worker.js +31 -0
  423. package/server-managed/type-only.ts +135 -0
  424. package/server-managed/uploads.ts +106 -0
  425. package/server-managed/upstream-cache.ts +256 -0
  426. package/server-managed/view-as.ts +58 -0
  427. package/server-managed/worker-turns.ts +76 -0
  428. package/server-managed/workspace-shares.ts +170 -0
  429. package/server.ts +70 -0
  430. package/strip-types-loader.js +13 -10
  431. package/server/index.ts +0 -480
  432. package/server/lifecycle.ts +0 -208
  433. /package/{LICENSE → LICENSE-MIT} +0 -0
  434. /package/{server → server-e2e}/auth.ts +0 -0
  435. /package/{server → server-e2e}/config.example.json +0 -0
  436. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  437. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  438. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  439. /package/{server → server-e2e}/peer.ts +0 -0
  440. /package/{server → server-e2e}/sse-session.ts +0 -0
  441. /package/{server → server-e2e}/util.ts +0 -0
  442. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,180 @@
1
+ import type { ServerResponse } from 'node:http'
2
+ import { setTimeout as delay } from 'node:timers/promises'
3
+ import type { ManagedHttpDeps } from './http.ts'
4
+ import type { StoredUser, TeamReportAccessSnapshot } from './db.ts'
5
+ import { TeamReportsError, annotationRevisionDigest, teamAnnotationRevision, teamSnapshotKey, teamWorkspaceFindingIds } from './team-reports.ts'
6
+ import type { WorkspaceShareFeedState } from './workspace-shares.ts'
7
+
8
+ // Short database reads work across instances without pinning a Neon connection.
9
+ // All polling belongs to the awaited request; nothing runs after it completes.
10
+ const TEAM_FEED_POLL_MS = 3_000
11
+ export const TEAM_FEED_LIFETIME_MS = 240_000 // below the configured Vercel 300s
12
+ const HEARTBEAT_MS = 15_000
13
+
14
+ type FeedOptions = { pollMs?: number; lifetimeMs?: number }
15
+ type Publish = (event: 'teams' | 'triage', revision: string | undefined) => boolean
16
+
17
+ // Public capabilities remain scoped to their single shared workspace.
18
+ export async function serveTeamFeed(res: ServerResponse, deps: ManagedHttpDeps,
19
+ snapshot: TeamReportAccessSnapshot, recheck: () => Promise<void>,
20
+ options: FeedOptions & { readState?: () => Promise<WorkspaceShareFeedState | null> } = {}): Promise<void> {
21
+ let ids: string[] | undefined
22
+ let previous: WorkspaceShareFeedState | undefined
23
+ const sameAccess = (a: WorkspaceShareFeedState, b?: WorkspaceShareFeedState) => a.grant === b?.grant && a.catalog === b.catalog
24
+ const readState = async () => {
25
+ const state = await options.readState!()
26
+ if (!state) throw new TeamReportsError(404, 'workspace-changed')
27
+ return state
28
+ }
29
+ await serveFeed(res, deps, async publish => {
30
+ const state = options.readState ? await readState() : undefined
31
+ // The first poll still compares the full snapshot loaded before the stream.
32
+ // Unchanged polls validate the live grant without reading report catalogs.
33
+ if (state && sameAccess(state, previous)) {
34
+ if (state.annotations === previous!.annotations) return
35
+ } else await recheck()
36
+ ids ??= [...await teamWorkspaceFindingIds(deps.db, deps.reportStore, snapshot)]
37
+ const triage = await deps.db.getAnnotationRevision(ids)
38
+ const after = options.readState ? await readState() : undefined
39
+ if (!after || !sameAccess(after, state)) await recheck()
40
+ publish('triage', triage)
41
+ // A write during the read must remain pending for the following poll.
42
+ if (after?.annotations === state?.annotations) previous = after
43
+ }, options)
44
+ }
45
+
46
+ // Membership and content notifications cover all of the user's teams. Only
47
+ // the focused team needs report parsing or annotation reads; null is the
48
+ // catalog-only subscription used on landing and management pages.
49
+ export async function serveUserTeamFeed(res: ServerResponse, deps: ManagedHttpDeps,
50
+ sessionId: string, user: StoredUser, teamId: string | null, options: FeedOptions & { reportId?: string | null } = {}): Promise<void> {
51
+ let ids: string[] = [], visibilityKey: string | undefined
52
+ let focused: TeamReportAccessSnapshot | undefined
53
+ let previousState: { catalog: number; annotations: number } | undefined
54
+ const checkUser = (current: { user: Pick<StoredUser, 'id' | 'role'> } | null) => {
55
+ if (!current) throw new TeamReportsError(401, 'unauthenticated')
56
+ if (current.user.id !== user.id || current.user.role !== user.role || current.user.role === 'none') {
57
+ throw new TeamReportsError(403, 'access-changed')
58
+ }
59
+ }
60
+ await serveFeed(res, deps, async publish => {
61
+ const state = await deps.db.getFeedState(sessionId, Date.now())
62
+ checkUser(state)
63
+ if (state!.catalog === previousState?.catalog && (!teamId || state!.annotations === previousState?.annotations)) return
64
+ if (teamId && focused !== undefined && state!.catalog === previousState?.catalog) {
65
+ // Annotation changes cannot change visibility. Read only this workspace's
66
+ // IDs, then fence against concurrent access/content changes before sending.
67
+ const triage = await teamAnnotationRevision(deps.db, focused, ids)
68
+ const after = await deps.db.getFeedState(sessionId, Date.now())
69
+ checkUser(after)
70
+ if (after!.catalog !== state!.catalog) return
71
+ publish('triage', triage)
72
+ if (after!.annotations === state!.annotations) previousState = state!
73
+ return
74
+ }
75
+ const catalog = await deps.db.getUserTeamFeedSnapshot(sessionId, Date.now())
76
+ checkUser(catalog)
77
+ // The session read again after the catalog, as the catalog is published
78
+ // next: one statement, as the poll's own check is.
79
+ checkUser(await deps.db.getFeedState(sessionId, Date.now()))
80
+ // Publish catalog state before loading any report blobs. A slow or broken
81
+ // focused report must not hide membership/content changes from the client.
82
+ if (!publish('teams', catalog!.revision)) return
83
+ if (!teamId) {
84
+ // A mutation during the snapshot must cause a fresh read next poll.
85
+ const current = await deps.db.getFeedState(sessionId, Date.now())
86
+ checkUser(current)
87
+ if (current!.catalog === state!.catalog) previousState = state!
88
+ return
89
+ }
90
+ let triage: string | undefined
91
+ const snapshot = await deps.db.getTeamReportAccessSnapshot(sessionId, Date.now(), teamId, options.reportId)
92
+ if (!snapshot) throw new TeamReportsError(401, 'unauthenticated')
93
+ checkUser(snapshot)
94
+ const key = teamSnapshotKey(snapshot)
95
+ if (key !== visibilityKey) {
96
+ try {
97
+ ids = snapshot.teamId ? [...await teamWorkspaceFindingIds(deps.db, deps.reportStore, snapshot)] : []
98
+ visibilityKey = key
99
+ } catch {
100
+ // Missing, malformed or temporarily unavailable blobs only suspend
101
+ // triage. Retry visibility on the next poll, even for the same key.
102
+ publish('triage', undefined)
103
+ return
104
+ }
105
+ }
106
+ // As GET /api/teams/:id/annotations answers it, so that a client holding
107
+ // that answer knows this tells nothing new.
108
+ if (snapshot.teamId) triage = await teamAnnotationRevision(deps.db, snapshot, ids)
109
+ const current = await deps.db.getTeamReportAccessSnapshot(sessionId, Date.now(), teamId, options.reportId)
110
+ // A concurrent access/content change discards only the annotation read.
111
+ checkUser(current)
112
+ if (!current || teamSnapshotKey(current) !== key) return
113
+ publish('triage', triage)
114
+ focused = snapshot.teamId ? snapshot : undefined
115
+ const after = await deps.db.getFeedState(sessionId, Date.now())
116
+ checkUser(after)
117
+ if (after!.catalog === state!.catalog && after!.annotations === state!.annotations) previousState = state!
118
+ }, { ...options, triageRevision: true })
119
+ }
120
+
121
+ // With `triageRevision`, a triage event tells its revision's digest, as the
122
+ // focused team's annotations answer it; else none, as a public share's.
123
+ async function serveFeed(res: ServerResponse, deps: ManagedHttpDeps, read: (publish: Publish) => Promise<void>,
124
+ { pollMs = TEAM_FEED_POLL_MS, lifetimeMs = TEAM_FEED_LIFETIME_MS, triageRevision = false }: FeedOptions & { triageRevision?: boolean }): Promise<void> {
125
+ const controller = new AbortController()
126
+ const close = () => controller.abort()
127
+ res.once('close', close)
128
+ const deadline = setTimeout(close, lifetimeMs)
129
+ const stopped = () => controller.signal.aborted || res.destroyed || deps.isShuttingDown()
130
+ // Notifications carry no annotation bodies, finding IDs, or global cursors.
131
+ // The catalog's opaque version, and a focused team's annotation revision's
132
+ // digest, let clients reuse an identical REST snapshot; every connection
133
+ // still confirms current access, including after reconnects.
134
+ function write(frame: string): boolean {
135
+ if (stopped()) return false
136
+ if (res.write(frame)) return true
137
+ // Slow consumers reconnect and read current state; never queue a backlog.
138
+ res.destroy()
139
+ return false
140
+ }
141
+ try {
142
+ if (stopped()) return
143
+ res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8',
144
+ 'cache-control': 'private, no-store, no-transform', 'x-accel-buffering': 'no',
145
+ 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer' })
146
+ res.flushHeaders()
147
+ let heartbeat = Date.now()
148
+ const previous = new Map<string, string>()
149
+ const publish: Publish = (event, revision) => {
150
+ if (stopped()) return false
151
+ if (revision === undefined) { previous.delete(event); return true }
152
+ if (revision === previous.get(event)) return true
153
+ const data = event === 'teams' ? JSON.stringify({ revision }) : triageRevision ? JSON.stringify({ revision: annotationRevisionDigest(revision) }) : '{}'
154
+ if (!write(`event: ${event}\ndata: ${data}\n\n`)) return false
155
+ previous.set(event, revision)
156
+ heartbeat = Date.now()
157
+ return true
158
+ }
159
+ while (!stopped()) {
160
+ if (deps.db.withRequest) await deps.db.withRequest(() => read(publish))
161
+ else await read(publish)
162
+ if (stopped()) break
163
+ if (Date.now() - heartbeat >= HEARTBEAT_MS) {
164
+ if (!write(': keepalive\n\n')) break
165
+ heartbeat = Date.now()
166
+ }
167
+ await delay(pollMs, undefined, { signal: controller.signal }).catch(error => {
168
+ if (!controller.signal.aborted) throw error
169
+ })
170
+ }
171
+ } catch (error) {
172
+ if (!res.headersSent) throw error
173
+ if (error instanceof TeamReportsError) write('event: close\ndata: {}\n\n')
174
+ else if (!stopped()) throw error
175
+ } finally {
176
+ clearTimeout(deadline)
177
+ res.off('close', close)
178
+ if (res.headersSent && !res.destroyed) res.end()
179
+ }
180
+ }
@@ -0,0 +1,103 @@
1
+ // npm scopes a team lists: its members, whatever their role, may read that
2
+ // scope's private packages in the npm viewer (npm-packages.ts), as admins and
3
+ // managers may read any. Hidden teams grant nothing, as for their content.
4
+ import { MAX_TEAM_NPM_SCOPES, normalizeNpmScope } from '../common/managed/npm-packages.js'
5
+ import type { Role } from '../common/managed/roles.ts'
6
+ import { reviewsIn } from './dependency-reviews.ts'
7
+ import { ManagedMutationError, sessionAdmin } from './management.ts'
8
+ import { type ManagedSql, jsonRows } from './sql.ts'
9
+
10
+ export const TEAM_NPM_SCOPE_SCHEMA = `
11
+ CREATE TABLE IF NOT EXISTS managed_team_npm_scope (
12
+ team_id TEXT NOT NULL REFERENCES managed_team(id) ON DELETE CASCADE,
13
+ scope TEXT NOT NULL,
14
+ PRIMARY KEY (team_id, scope)
15
+ ) STRICT;
16
+ `
17
+
18
+ export interface TeamNpmScopeStore {
19
+ // Every team's scopes, sorted, keyed by team id; teams without any are absent.
20
+ listTeamNpmScopes(): Promise<Record<string, string[]>>
21
+ // Replaces a team's scopes; admin only. Answers what changed, or null for no team.
22
+ setTeamNpmScopes(sessionId: string, teamId: string, scopes: unknown): Promise<{ added: string[]; removed: string[] } | null>
23
+ // The scopes a user's visible teams list.
24
+ listUserNpmScopes(userId: string): Promise<string[]>
25
+ // Whether any visible team lists the scope: whoever reads its packages,
26
+ // they are the instance's own, whose new releases aren't flagged (http.ts).
27
+ hasTeamNpmScope(scope: string): Promise<boolean>
28
+ // Who session `sessionId` names now, as readSession reads it, their own
29
+ // or, where `viewerSessionId` names an admin's own one, a view of it: their
30
+ // role, the scopes their teams list (listUserNpmScopes), and whether they
31
+ // read the dependency reviews published to team `teamId`
32
+ // (dependency-reviews.ts reviewsIn); in one statement, as a list of a
33
+ // team's reviews asks again once npm is read. Null where it names none.
34
+ getNpmReviewReader(sessionId: string, viewerSessionId: string | null, now: number, teamId: string): Promise<NpmReviewReader | null>
35
+ }
36
+ export interface NpmReviewReader { id: string; role: Role; scopes: string[]; readsTeam: boolean }
37
+
38
+ // Each distinct scope, normalized; a list with one npm could not publish
39
+ // under, or too many, is refused whole.
40
+ export function parseTeamNpmScopes(input: unknown): string[] {
41
+ if (!Array.isArray(input)) throw new ManagedMutationError(400, 'bad-scopes')
42
+ const scopes = new Set<string>()
43
+ for (const value of input) {
44
+ const scope = normalizeNpmScope(value)
45
+ if (scope === null) throw new ManagedMutationError(400, 'bad-scope')
46
+ scopes.add(scope)
47
+ }
48
+ if (scopes.size > MAX_TEAM_NPM_SCOPES) throw new ManagedMutationError(400, 'too-many-scopes')
49
+ return [...scopes].toSorted()
50
+ }
51
+
52
+ export function teamNpmScopeMethods(db: ManagedSql): TeamNpmScopeStore {
53
+ return {
54
+ async listTeamNpmScopes() {
55
+ const rows = await db.prepare('SELECT team_id AS teamId, scope FROM managed_team_npm_scope ORDER BY team_id, scope').all() as { teamId: string; scope: string }[]
56
+ const result: Record<string, string[]> = {}
57
+ for (const { teamId, scope } of rows) (result[teamId] ??= []).push(scope)
58
+ return result
59
+ },
60
+ async setTeamNpmScopes(sessionId, teamId, input) {
61
+ await sessionAdmin(db, sessionId)
62
+ const scopes = parseTeamNpmScopes(input)
63
+ if (!await db.prepare('SELECT id FROM managed_team WHERE id = ?').get(teamId)) return null
64
+ const current = (await db.prepare('SELECT scope FROM managed_team_npm_scope WHERE team_id = ?').all(teamId) as { scope: string }[]).map(row => row.scope)
65
+ const removed = current.filter(scope => !scopes.includes(scope)).toSorted()
66
+ const added = scopes.filter(scope => !current.includes(scope))
67
+ for (const scope of removed) await db.prepare('DELETE FROM managed_team_npm_scope WHERE team_id = ? AND scope = ?').run(teamId, scope)
68
+ for (const scope of added) await db.prepare('INSERT INTO managed_team_npm_scope (team_id, scope) VALUES (?, ?)').run(teamId, scope)
69
+ return { added, removed }
70
+ },
71
+ async listUserNpmScopes(userId) {
72
+ const rows = await db.prepare(`SELECT DISTINCT ns.scope FROM managed_team_user tu
73
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
74
+ JOIN managed_team_npm_scope ns ON ns.team_id = tu.team_id
75
+ WHERE tu.user_id = ? ORDER BY ns.scope`).all(userId) as { scope: string }[]
76
+ return rows.map(row => row.scope)
77
+ },
78
+ getNpmReviewReader: (sessionId, viewerSessionId, now, teamId) => npmReviewReader(db, sessionId, viewerSessionId, now, teamId),
79
+ async hasTeamNpmScope(scope) {
80
+ return !!await db.prepare(`SELECT 1 AS listed FROM managed_team_npm_scope ns
81
+ JOIN managed_team t ON t.id = ns.team_id AND t.hidden = 0
82
+ WHERE ns.scope = ? LIMIT 1`).get(scope)
83
+ },
84
+ }
85
+ }
86
+
87
+ // getNpmReviewReader's statement, its session held to what readSession's
88
+ // own are (db-methods.ts selectOwnSessionStmt, selectViewSessionStmt).
89
+ async function npmReviewReader(db: ManagedSql, sessionId: string, viewerSessionId: string | null, now: number, teamId: string): Promise<NpmReviewReader | null> {
90
+ const row = await db.prepare(`WITH reader AS (
91
+ SELECT u.id AS id, u.role AS role FROM managed_session s JOIN managed_user u ON u.id = s.user_id
92
+ WHERE s.id = ? AND s.expires_at > ? AND ((? IS NULL AND s.viewer_session IS NULL) OR (s.viewer_session = ? AND EXISTS (
93
+ SELECT 1 FROM managed_session p JOIN managed_user a ON a.id = p.user_id
94
+ WHERE p.id = s.viewer_session AND p.expires_at > ? AND p.viewer_session IS NULL AND a.role = 'admin')))
95
+ )
96
+ SELECT v.id AS id, v.role AS role,
97
+ (SELECT json_group_array(x.scope ORDER BY x.scope) FROM (SELECT DISTINCT ns.scope AS scope FROM managed_team_user tu
98
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0 JOIN managed_team_npm_scope ns ON ns.team_id = tu.team_id
99
+ WHERE tu.user_id = v.id) x) AS scopes,
100
+ CASE WHEN EXISTS (SELECT 1 FROM managed_team t JOIN managed_user u ON u.id = v.id WHERE t.id = ? AND ${reviewsIn(false)}) THEN 1 ELSE 0 END AS readsTeam
101
+ FROM reader v`).get(sessionId, now, viewerSessionId, viewerSessionId, now, teamId) as { id: string; role: Role; scopes: unknown; readsTeam: unknown } | undefined
102
+ return row ? { id: row.id, role: row.role, scopes: jsonRows<string>(row.scopes), readsTeam: Number(row.readsTeam) === 1 } : null
103
+ }
@@ -0,0 +1,368 @@
1
+ // Team content is filtered as one workspace, with separate report envelopes.
2
+ // Bounded snapshots retain filtered content and visibility for repeated reads.
3
+ import { mergeLinkGroups } from './link-reports.ts'
4
+ import { Buffer } from 'node:buffer'
5
+ import { createHash } from 'node:crypto'
6
+ import { backfillFindingIds, reportEntries, stampSecurityGroups } from '@preventive/report'
7
+ import { managedFindingSourcePaths, readManagedReport } from '../common/managed/report-content.ts'
8
+ import { filterReportData, projectFinding } from '../common/managed/report-filter.ts'
9
+ import { revalidationLinks, securityLinks } from '../common/security-links.js'
10
+ import { treeDependencyDirectory } from '../client/dependency-paths.js'
11
+ import { liteWorkspace } from '../common/managed/finding-detail.js'
12
+ import { managedTeamView } from '../common/managed/team-app.js'
13
+ import { packTeamReports, unpackTeamReport } from '../common/managed/finding-values.js'
14
+ import type { BlobStore } from './blob-store.ts'
15
+ import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
16
+ import type { TeamWorkspaceSummary } from './team-app.ts'
17
+ import { triageWireEntry } from './triage-response.ts'
18
+ import { visibleManagedIssues } from './managed-issues.ts'
19
+ import { MAX_REPORT_QUERY_BYTES, MAX_REPORT_QUERY_COUNT } from './report-query.ts'
20
+ import { ourRepoSlugs } from '../common/finding-repo.js'
21
+
22
+ type Finding = Record<string, unknown>
23
+ // `confirmedDefault` where a manager switched the report to open on Confirmed,
24
+ // and `opensAsApp` where it opens as an App view on its own, so switched or by
25
+ // its rows (common/managed/team-app.js), which its team's view counts as
26
+ // holding it off Confirmed none of its findings (common/finding-filters.js
27
+ // confirmedCoverage); each left out otherwise.
28
+ type TeamReport = { id: string; filename: string; data: unknown; repo: { github: string | null; directory: string }; confirmedDefault?: true; opensAsApp?: true }
29
+ type ReportVisibility = { ids: Set<string>; sourcePaths: Set<string> }
30
+ type Visibility = Map<string, ReportVisibility>
31
+ const VISIBILITY_CACHE_MAX_ITEMS = 250_000
32
+ const VISIBILITY_CACHE_MAX_SNAPSHOTS = 32
33
+ const caches = new WeakMap<ManagedDb, Map<string, Visibility>>()
34
+ const REPORT_CACHE_BYTES = 16 * 1024 * 1024
35
+ // A workspace's encoded reports, the same without their findings' detail for
36
+ // the board (`lite`), its reports' file trees apart, and its team's catalog
37
+ // summary (team-app.ts).
38
+ type EncodedWorkspace = { reports: Buffer; lite: Buffer; trees: Buffer; summary: TeamWorkspaceSummary }
39
+ // One as kept: without its whole reports where they would not fit
40
+ // (retainReports).
41
+ type RetainedWorkspace = Omit<EncodedWorkspace, 'reports'> & { reports?: Buffer }
42
+ export type TeamResponsePart = 'reports' | 'lite' | 'trees'
43
+ // The part a team's `reports` or `trees` route asks for.
44
+ export const teamResponsePart = (route: string, url: URL): TeamResponsePart =>
45
+ route === 'trees' ? 'trees' : url.searchParams.get('lite') === '1' ? 'lite' : 'reports'
46
+ const reportCaches = new WeakMap<ManagedDb, Map<string, RetainedWorkspace>>()
47
+ const encodedBytes = ({ reports, lite, trees }: RetainedWorkspace) => (reports?.length ?? 0) + lite.length + trees.length
48
+ // A workspace's report reads at once. Its reports' sizes are bounded together
49
+ // before any is read, and each is held parsed till the build ends, so more at
50
+ // once costs only the raw bytes in flight: a cold build of a team's reports
51
+ // is so many storage round trips one after another.
52
+ const WORKSPACE_READS_AT_ONCE = 16
53
+ // Its whole reports, by far its largest part, are kept with the rest where
54
+ // they fit, and left out where they do not: the board's copy and the trees,
55
+ // which a team's view opens on, are kept all the same, so that opening it
56
+ // again reads none of its reports, its whole reports built again apart.
57
+ function retainReports(db: ManagedDb, key: string, encoded: EncodedWorkspace) {
58
+ let kept: RetainedWorkspace = encoded
59
+ if (encodedBytes(kept) > REPORT_CACHE_BYTES) { const { reports: _reports, ...rest } = encoded; kept = rest }
60
+ if (encodedBytes(kept) > REPORT_CACHE_BYTES) return
61
+ let cache = reportCaches.get(db)
62
+ if (!cache) { cache = new Map(); reportCaches.set(db, cache) }
63
+ cache.delete(key)
64
+ let total = encodedBytes(kept) + [...cache.values()].reduce((sum, value) => sum + encodedBytes(value), 0)
65
+ for (const [oldest, value] of cache) {
66
+ if (total <= REPORT_CACHE_BYTES && cache.size < VISIBILITY_CACHE_MAX_SNAPSHOTS) break
67
+ cache.delete(oldest); total -= encodedBytes(value)
68
+ }
69
+ cache.set(key, kept)
70
+ }
71
+ function visibilityWeight(visible: Visibility): number {
72
+ return [...visible.values()].reduce((sum, v) => sum + v.ids.size + v.sourcePaths.size, 0)
73
+ }
74
+ function retainVisibility(db: ManagedDb, key: string, visible: Visibility): void {
75
+ let cache = caches.get(db)
76
+ // Replacement contributes its weight once and does not evict a peer merely
77
+ // because the cache already holds the maximum number of snapshots.
78
+ cache?.delete(key)
79
+ const incoming = visibilityWeight(visible)
80
+ if (incoming > VISIBILITY_CACHE_MAX_ITEMS) return
81
+ if (!cache) { cache = new Map(); caches.set(db, cache) }
82
+ let total = incoming + [...cache.values()].reduce((sum, entry) => sum + visibilityWeight(entry), 0)
83
+ for (const [oldest, entry] of cache) {
84
+ if (cache.size < VISIBILITY_CACHE_MAX_SNAPSHOTS && total <= VISIBILITY_CACHE_MAX_ITEMS) break
85
+ cache.delete(oldest)
86
+ total -= visibilityWeight(entry)
87
+ }
88
+ cache.set(key, visible)
89
+ }
90
+ export class TeamReportsError extends Error {
91
+ status: number
92
+ constructor(status: number, error: string) { super(error); this.status = status }
93
+ }
94
+ export function teamSnapshotKey(snapshot: TeamReportAccessSnapshot): string {
95
+ return JSON.stringify([snapshot.user.id, snapshot.user.role, snapshot.teamId, snapshot.hiddenReportId ?? null, snapshot.reports, snapshot.repositories, snapshot.linkRevision])
96
+ }
97
+ // What a built workspace is kept by: everything its build reads, and nothing
98
+ // of who asked. A user's role and grants decide which reports (and which
99
+ // hidden preview) their snapshot holds and each one's permissions, all of it
100
+ // in the key, so members whose snapshots agree share one build.
101
+ function workspaceKey(snapshot: TeamReportAccessSnapshot): string {
102
+ return JSON.stringify([snapshot.teamId, snapshot.hiddenReportId ?? null, snapshot.reports, snapshot.repositories, snapshot.linkRevision])
103
+ }
104
+ export async function teamSnapshot(db: ManagedDb, sessionId: string, teamId: string, reportId: string | null = null): Promise<TeamReportAccessSnapshot> {
105
+ const snapshot = await db.getTeamReportAccessSnapshot(sessionId, Date.now(), teamId, reportId)
106
+ if (!snapshot) throw new TeamReportsError(401, 'unauthenticated')
107
+ if (!snapshot.teamId) throw new TeamReportsError(404, 'no-team')
108
+ if (reportId !== null && !snapshot.reports.some(report => report.id === reportId)) throw new TeamReportsError(404, 'no-report')
109
+ return snapshot
110
+ }
111
+ export async function recheckTeam(db: ManagedDb, sessionId: string, snapshot: TeamReportAccessSnapshot): Promise<void> {
112
+ if (teamSnapshotKey(await teamSnapshot(db, sessionId, snapshot.teamId!, snapshot.reportId)) !== teamSnapshotKey(snapshot)) throw new TeamReportsError(404, 'workspace-changed')
113
+ }
114
+ function groupsOf(data: unknown): Finding[][] {
115
+ return (reportEntries(data) ?? []).map(entry => (Array.isArray(entry) ? entry : [entry]).filter(
116
+ (finding): finding is Finding => finding !== null && typeof finding === 'object' && !Array.isArray(finding),
117
+ ))
118
+ }
119
+ // A links document counts by its links, every other report by its findings.
120
+ function hasContent(data: unknown): boolean {
121
+ const links = linksOf(data)
122
+ if (links) return links.length > 0
123
+ return (reportEntries(data) ?? []).some(entry => !Array.isArray(entry) || entry.length > 0)
124
+ }
125
+ function linksOf(data: unknown): string[][] | null {
126
+ const record = data as { source?: string; links?: string[][] }
127
+ if (record?.source !== 'links' || !Array.isArray(record.links)) return null
128
+ if (!record.links.every(ids => Array.isArray(ids) && ids.every(id => typeof id === 'string'))) throw new TeamReportsError(422, 'unreadable-links')
129
+ return record.links
130
+ }
131
+ // A report's file tree goes apart, asked for by its graph or Files alone
132
+ // (loadTeamTreesResponse). The report tells in its place how many files it
133
+ // holds (`treeFiles`) and the dependency directory it names
134
+ // (`treeDependencies`), which classifies findings as the tree itself would
135
+ // (client/dependency-paths.js). Each file's is sent without the hash of its
136
+ // tree (`treeHash`), which no team view reads.
137
+ function withoutTree(report: TeamReport): string | null {
138
+ const tree = (report.data as { tree?: unknown } | null)?.tree
139
+ if (!tree || typeof tree !== 'object' || Array.isArray(tree)) return null
140
+ const { tree: _tree, ...data } = report.data as Finding
141
+ const named = treeDependencyDirectory(tree)
142
+ report.data = { ...data, treeFiles: Object.keys(tree).length, ...(named ? { treeDependencies: named } : {}) }
143
+ const files = Object.entries(tree).map(([file, entry]) => {
144
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return [file, entry]
145
+ const { treeHash: _treeHash, ...kept } = entry as Finding
146
+ return [file, kept]
147
+ })
148
+ return `${JSON.stringify(report.id)}:${JSON.stringify(Object.fromEntries(files))}`
149
+ }
150
+ // The snapshot's reports, read WORKSPACE_READS_AT_ONCE at a time, in its
151
+ // order, their findings' IDs backfilled.
152
+ async function readWorkspaceReports(store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<TeamReport[]> {
153
+ const reports: TeamReport[] = []
154
+ let inputBytes = 0, next = 0
155
+ // Bound both remote reads and raw buffers, retaining stable report order for
156
+ // the cross-report classification that follows. Finish workers on failure.
157
+ const results = await Promise.allSettled(Array.from({ length: Math.min(WORKSPACE_READS_AT_ONCE, snapshot.reports.length) }, async () => {
158
+ while (next < snapshot.reports.length) {
159
+ const index = next++
160
+ const access = snapshot.reports[index]!
161
+
162
+ const bytes = await store.get(access.id)
163
+ if (!bytes) throw new TeamReportsError(503, 'unavailable')
164
+ inputBytes += bytes.length
165
+ if (inputBytes > MAX_REPORT_QUERY_BYTES) throw new TeamReportsError(413, 'batch-too-large')
166
+ const parsed = readManagedReport(bytes.toString('utf8'), access.filename)
167
+ if (!parsed.data) throw new TeamReportsError(422, 'unreadable-report')
168
+ // Backfill before filtering so links, annotations and the client agree on
169
+ // IDs even when hiding a component would change the original row shape.
170
+ await backfillFindingIds(groupsOf(parsed.data).flat())
171
+ reports[index] = { id: access.id, filename: access.filename, data: parsed.data, repo: access.repo, ...access.confirmedDefault ? { confirmedDefault: true as const } : {} }
172
+ }
173
+ }))
174
+ for (const result of results) if (result.status === 'rejected') throw result.reason
175
+ return reports
176
+ }
177
+ async function buildTeamWorkspace(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<EncodedWorkspace & { visible: Visibility }> {
178
+ if (snapshot.reports.length > MAX_REPORT_QUERY_COUNT || snapshot.reports.reduce((n, r) => n + r.byteSize, 0) > MAX_REPORT_QUERY_BYTES) throw new TeamReportsError(413, 'batch-too-large')
179
+ const reports = await readWorkspaceReports(store, snapshot)
180
+ const globalLinks = snapshot.linkRevision ? await db.getEnabledLinkGroups(snapshot.linkRevision) : []
181
+ const groups = reports.flatMap(report => groupsOf(report.data).map(group => group.map(f => projectFinding(f, report.data as Finding)!)))
182
+ // Unknown IDs can connect known findings. App findings link to the inputs
183
+ // they revalidated in other reports, as the App view counts them.
184
+ stampSecurityGroups(groups, { linkedIds: securityLinks([
185
+ ...globalLinks, ...reports.flatMap(report => linksOf(report.data) ?? []), ...revalidationLinks(groups.flat()),
186
+ ]).linkedIds })
187
+ const securityIds = new Set(groups.flat().filter(f => f['isSecurity'] === true).map(f => String(f['id'])))
188
+ const allIds = new Set<string>(), visible: Visibility = new Map()
189
+ for (let i = 0; i < reports.length; i++) {
190
+ const access = snapshot.reports[i]!, report = reports[i]!
191
+ // A finding's `repo` none of the team's (common/finding-repo.js
192
+ // isStrayRepo) is removed before anything reads it.
193
+ const ours = ourRepoSlugs([...snapshot.repositories.map(repo => repo.github), access.repo.github])
194
+ report.data = filterReportData(report.data, access.permissions, access.repo, securityIds, ours)
195
+ if (report.data && typeof report.data === 'object' && ('think' in report.data || 'reportRepo' in report.data)) {
196
+ const { think: _think, reportRepo: _reportRepo, ...data } = report.data as Finding
197
+ report.data = data
198
+ }
199
+ const ids = new Set<string>()
200
+ for (const finding of groupsOf(report.data).flat()) {
201
+ // Preserve linked security classification for the UI lens, including a
202
+ // linked component that a dependency permission will hide from the UI.
203
+ finding['isSecurity'] = securityIds.has(String(finding['id']))
204
+ // The hash of its file's tree, the fingerprint its ID was derived from,
205
+ // whether its run thought and the repository its report named, which
206
+ // nothing a team view reads, nor an export (@preventive/report
207
+ // write-md-finding.js) writes.
208
+ delete finding['treeHash']
209
+ delete finding['_idBasis']
210
+ delete finding['think']
211
+ delete finding['reportRepo']
212
+ if (typeof finding['id'] === 'string') { ids.add(finding['id']); allIds.add(finding['id']) }
213
+ }
214
+ visible.set(report.id, { ids, sourcePaths: managedFindingSourcePaths(groupsOf(report.data).flat()) })
215
+ }
216
+ for (const report of reports) {
217
+ const links = linksOf(report.data)
218
+ // Hidden previews are independently authorized; preserve a hidden links
219
+ // document even though its referenced findings are outside this response.
220
+ if (links && !snapshot.hiddenReportId) report.data = { source: 'links', findings: [], links: links.map(ids => [...new Set(ids.filter(id => allIds.has(id)))]).filter(ids => ids.length >= 2) }
221
+ }
222
+ const trees = Buffer.from(`{"trees":{${reports.map(withoutTree).filter(tree => tree !== null).join(',')}}}`)
223
+ const links = mergeLinkGroups(globalLinks, allIds)
224
+ // Its rows read once (common/managed/team-app.js managedTeamView) for both
225
+ // what its catalog entry tells and the board's copy: its findings without
226
+ // their detail, and in App mode its rows as the App view shows them
227
+ // (common/managed/finding-detail.js).
228
+ const view = managedTeamView(Object.assign(reports.map(({ filename, data, confirmedDefault }) => ({ filename, data, confirmedDefault })), { links }))
229
+ // As the reader's own grants leave each report, which they would open alone.
230
+ view.opensAsApp.forEach((opens, index) => { if (opens) reports[index]!.opensAsApp = true })
231
+ const lite = liteWorkspace(reports, links, view)
232
+ const restricted = snapshot.reports.some(report => !report.permissions.dependencies || !report.permissions.security)
233
+ const encoded = {
234
+ // Bounded together, as when the trees were sent with their reports.
235
+ reports: encodeReports(reports, links, trees.length),
236
+ lite: encodeReports(lite.reports, links, 0, { folded: lite.folded, lens: lite.lens }),
237
+ trees,
238
+ // Its App classification, and the reports a restricted reader finds
239
+ // nothing in, which its catalog leaves out.
240
+ summary: { app: view.app, empty: restricted ? reports.filter(report => !hasContent(report.data)).map(report => report.id) : [] },
241
+ }
242
+ retainVisibility(db, workspaceKey(snapshot), visible)
243
+ retainReports(db, workspaceKey(snapshot), encoded)
244
+ return { ...encoded, visible }
245
+ }
246
+ // `{ reports, links }` as a response sends them, `spent` bytes already
247
+ // counted against the bound; `folded` and its `lens` where the board's copy
248
+ // left out rows App mode does not show (common/managed/finding-detail.js).
249
+ // The values its reports and their findings tell again and again (their
250
+ // severity, file, model, repository and so on) are sent once each, in
251
+ // `values`, and its findings' field names once for each shape of them, in
252
+ // `keys` (common/managed/finding-values.js).
253
+ function encodeReports(reports: readonly TeamReport[], links: readonly string[][], spent: number,
254
+ { folded = false, lens = null }: { folded?: false | 'rows' | 'app'; lens?: unknown } = {}): Buffer {
255
+ let outputBytes = spent + 14
256
+ const parts = [Buffer.from('{"reports":[')]
257
+ const packed = packTeamReports(reports)
258
+ for (const [index, report] of packed.reports.entries()) {
259
+ const bytes = Buffer.from(JSON.stringify(report))
260
+ outputBytes += bytes.length + 1
261
+ if (outputBytes > MAX_REPORT_QUERY_BYTES) throw new TeamReportsError(413, 'batch-too-large')
262
+ if (index) parts.push(Buffer.from(','))
263
+ parts.push(bytes)
264
+ }
265
+ const tail = JSON.stringify({ ...links.length > 0 ? { links } : {}, ...folded ? { folded, lens } : {}, ...packed.values ? { values: packed.values } : {}, ...packed.keys ? { keys: packed.keys } : {} })
266
+ const suffix = Buffer.from(tail === '{}' ? ']}' : `],${tail.slice(1)}`)
267
+ if (outputBytes + suffix.length > MAX_REPORT_QUERY_BYTES) throw new TeamReportsError(413, 'batch-too-large')
268
+ parts.push(suffix)
269
+ return Buffer.concat(parts)
270
+ }
271
+ const pendingWorkspaces = new WeakMap<ManagedDb, Map<string, ReturnType<typeof buildTeamWorkspace>>>()
272
+ async function loadTeamWorkspace(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot) {
273
+ let pending = pendingWorkspaces.get(db)
274
+ if (!pending) { pending = new Map(); pendingWorkspaces.set(db, pending) }
275
+ const key = workspaceKey(snapshot)
276
+ const existing = pending.get(key)
277
+ if (existing) return existing
278
+ const job = buildTeamWorkspace(db, store, snapshot)
279
+ pending.set(key, job)
280
+ try { return await job } finally { pending.delete(key) }
281
+ }
282
+ // Treat the encoded body as immutable and recheck access before sending it.
283
+ // Warm HTTP reads need neither a parsed copy nor another serialization pass.
284
+ // Its `lite` reports and its `trees`, by report ID (withoutTree), are of the
285
+ // same snapshot and take the same recheck.
286
+ export async function loadTeamReportsResponse(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot,
287
+ part: TeamResponsePart = 'reports'): Promise<Buffer> {
288
+ const cached = reportCaches.get(db)?.get(workspaceKey(snapshot))
289
+ return cached?.[part] ?? (await loadTeamWorkspace(db, store, snapshot))[part]
290
+ }
291
+ // A team's catalog summary (team-app.ts), as its workspace was built.
292
+ export async function loadTeamSummary(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<TeamWorkspaceSummary> {
293
+ return reportCaches.get(db)?.get(workspaceKey(snapshot))?.summary ?? (await loadTeamWorkspace(db, store, snapshot)).summary
294
+ }
295
+ export async function loadTeamReports(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<TeamReport[]> {
296
+ // Object consumers get their own copy, including when sharing a cold load.
297
+ const body = JSON.parse((await loadTeamReportsResponse(db, store, snapshot)).toString('utf8')) as { reports: TeamReport[]; values?: unknown; keys?: unknown }
298
+ return body.reports.map(report => unpackTeamReport(report, body)!)
299
+ }
300
+ async function teamVisibility(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<Visibility> {
301
+ // A large snapshot may deliberately remain uncached, or be evicted by
302
+ // another request. Authorization uses this load's result in either case.
303
+ return caches.get(db)?.get(workspaceKey(snapshot)) ?? (await loadTeamWorkspace(db, store, snapshot)).visible
304
+ }
305
+ // The findings `visible`'s reports show, each once.
306
+ const findingIdsOf = (visible: Visibility) => new Set([...visible.values()].flatMap(report => [...report.ids]))
307
+ export async function teamWorkspaceFindingIds(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<Set<string>> {
308
+ return findingIdsOf(await teamVisibility(db, store, snapshot))
309
+ }
310
+
311
+ // What a focused team's annotations are at, for the snapshot reading them, as
312
+ // its feed tells it (team-feed.ts serveUserTeamFeed) and its annotations
313
+ // answer it (loadTeamAnnotations): the snapshot's key and the revision of
314
+ // every visible finding's annotations (getAnnotationRevision), its workspace's
315
+ // findings being `ids` (teamWorkspaceFindingIds).
316
+ export async function teamAnnotationRevision(db: ManagedDb, snapshot: TeamReportAccessSnapshot, ids: readonly string[]): Promise<string> {
317
+ return JSON.stringify([teamSnapshotKey(snapshot), await db.getAnnotationRevision(ids)])
318
+ }
319
+
320
+ // A revision as the client is told it: a digest, telling only whether what it
321
+ // covers changed, none of the finding IDs, batches or issues it is read from.
322
+ export const annotationRevisionDigest = (revision: string): string => createHash('sha256').update(revision).digest('base64url')
323
+ export async function teamReportVisibility(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot, reportId: string): Promise<ReportVisibility> {
324
+ if (!snapshot.reports.some(r => r.id === reportId)) throw new TeamReportsError(404, 'no-report')
325
+ const visible = await teamVisibility(db, store, snapshot)
326
+ return visible.get(reportId)!
327
+ }
328
+ // A report's visibility for the session's current snapshot. A workspace built
329
+ // (or waited for) here outlives that snapshot's read, so the team's access is
330
+ // read again after it; one kept is answered with no read in between, which
331
+ // leaves nothing for another snapshot read to guard.
332
+ async function sessionReportVisibility(db: ManagedDb, store: BlobStore, sessionId: string, teamId: string, reportId: string): Promise<ReportVisibility> {
333
+ const snapshot = await teamSnapshot(db, sessionId, teamId, reportId)
334
+ const kept = caches.get(db)?.get(workspaceKey(snapshot))?.get(reportId)
335
+ if (kept) return kept
336
+ const visible = await teamReportVisibility(db, store, snapshot, reportId)
337
+ await recheckTeam(db, sessionId, snapshot)
338
+ return visible
339
+ }
340
+ export async function teamFindingIds(db: ManagedDb, store: BlobStore, sessionId: string, teamId: string, reportId: string): Promise<Set<string>> {
341
+ return (await sessionReportVisibility(db, store, sessionId, teamId, reportId)).ids
342
+ }
343
+ export async function teamSourcePaths(db: ManagedDb, store: BlobStore, sessionId: string, teamId: string, reportId: string): Promise<Set<string>> {
344
+ return (await sessionReportVisibility(db, store, sessionId, teamId, reportId)).sourcePaths
345
+ }
346
+
347
+ // Serialize shared annotation bodies once. Reports carry only the annotated
348
+ // finding IDs visible in that report; callers revalidate access before sending.
349
+ // With them, the digest of the revision the whole workspace's are at, as the
350
+ // team's feed tells it (`revision`), read before them: a write between leaves
351
+ // it older than what is sent, so the feed's next differs and the client reads
352
+ // again, never the reverse.
353
+ export async function loadTeamAnnotations(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot, reportId: string | null = null) {
354
+ // Restrict annotation reads only after classifying the complete workspace:
355
+ // links and findings in other reports can affect this report's visibility.
356
+ if (reportId !== null && !snapshot.reports.some(r => r.id === reportId)) throw new TeamReportsError(404, 'no-report')
357
+ const workspace = await teamVisibility(db, store, snapshot)
358
+ const visible = reportId === null ? workspace : new Map([[reportId, workspace.get(reportId)!]])
359
+ const all = findingIdsOf(workspace), ids = findingIdsOf(visible)
360
+ const revision = await teamAnnotationRevision(db, snapshot, [...all])
361
+ const { triage, comments, issues: savedIssues } = await db.getAnnotations([...ids])
362
+ const issues = Object.fromEntries(visibleManagedIssues(savedIssues, snapshot)
363
+ .map(issue => [issue.findingId, { url: issue.issueUrl!, autoFix: issue.autoFixUrl, duplicateOf: issue.duplicateOfUrl }]))
364
+ const entries = Object.fromEntries(triage.map(row => [row.findingId, triageWireEntry(row)]))
365
+ const annotated = new Set([...triage.map(row => row.findingId), ...comments.map(comment => comment.findingId), ...Object.keys(issues)])
366
+ const reports = Object.fromEntries([...visible].map(([id, report]) => [id, [...report.ids].filter(finding => annotated.has(finding))]))
367
+ return { reports, entries, comments, issues, revision: annotationRevisionDigest(revision) }
368
+ }