@preventive/triage 1.0.0-alpha.9 → 1.0.0-alpha.90

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 (448) 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 +378 -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 +80 -0
  35. package/common/default-scan-models.ts +37 -0
  36. package/common/dependency-reviews.d.ts +19 -0
  37. package/common/dependency-reviews.js +67 -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 +3 -0
  44. package/common/github-issue-labels.js +42 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +15 -0
  48. package/common/line-diff.js +188 -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 +48 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +386 -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/npm-token.d.ts +2 -0
  81. package/common/npm-token.js +14 -0
  82. package/common/pretty-json.js +123 -0
  83. package/common/pretty-kinds.js +20 -0
  84. package/common/pretty-print.d.ts +7 -0
  85. package/common/pretty-print.js +41 -0
  86. package/common/pretty-sourcemap.js +70 -0
  87. package/common/repo-commit.d.ts +4 -0
  88. package/common/repo-commit.js +30 -0
  89. package/common/revalidation-conflicts.js +48 -0
  90. package/common/revalidation-input-groups.js +56 -0
  91. package/common/scan-server.ts +13 -0
  92. package/common/security-links.d.ts +5 -0
  93. package/common/security-links.js +33 -0
  94. package/common/server-info.ts +46 -0
  95. package/common/sourcemap-listing.js +78 -0
  96. package/common/sourcemap-mappings.js +136 -0
  97. package/common/sourcemap-unlist.js +85 -0
  98. package/common/stasis-files.d.ts +5 -0
  99. package/common/stasis-files.js +20 -0
  100. package/common/stasis-tgz.d.ts +6 -0
  101. package/common/stasis-tgz.js +27 -0
  102. package/common/utf8.d.ts +3 -0
  103. package/common/utf8.js +45 -0
  104. package/common/whitespace-insensitive.js +19 -0
  105. package/common/workspace-app.js +91 -0
  106. package/common/workspace-groups.js +176 -0
  107. package/out/activity.js +2 -0
  108. package/out/brotli-fallback.js +3 -3
  109. package/out/chunk-2XUEZHIP.js +28 -0
  110. package/out/chunk-3DOSBILK.js +4 -0
  111. package/out/chunk-55YIWY3H.js +5 -0
  112. package/out/chunk-5AVGKFMR.js +1 -0
  113. package/out/chunk-5PWEAEA5.js +1 -0
  114. package/out/chunk-6VOB5WXX.js +2 -0
  115. package/out/chunk-6Y6PZ2BU.js +9 -0
  116. package/out/chunk-74JZTGTO.js +11 -0
  117. package/out/chunk-7BKKYVWR.js +7 -0
  118. package/out/chunk-7C7DWL7I.js +1 -0
  119. package/out/chunk-7HP2VYIC.js +2 -0
  120. package/out/chunk-7YFJUT2P.js +1 -0
  121. package/out/chunk-A4BBBHQU.js +1 -0
  122. package/out/chunk-B64CTMVU.js +4 -0
  123. package/out/chunk-BEKYZCPX.js +14 -0
  124. package/out/chunk-BZJU5EEV.js +1 -0
  125. package/out/chunk-C4Z6ZBXV.js +10 -0
  126. package/out/chunk-CJVMNJDZ.js +3 -0
  127. package/out/chunk-CU3FPB3P.js +1 -0
  128. package/out/chunk-DEVAORP2.js +1 -0
  129. package/out/chunk-DUASGS2O.js +8 -0
  130. package/out/chunk-EEJA7JBI.js +13 -0
  131. package/out/chunk-ESXA7KID.js +1 -0
  132. package/out/chunk-FSU2PLJL.js +1 -0
  133. package/out/chunk-GO7FT4OD.js +1 -0
  134. package/out/chunk-GX5UXWT4.js +1 -0
  135. package/out/chunk-HGWFRZNC.js +267 -0
  136. package/out/chunk-IYPY47MC.js +1 -0
  137. package/out/chunk-JZAROLQT.js +40 -0
  138. package/out/chunk-K4XJHM2T.js +1 -0
  139. package/out/chunk-KP2XM324.js +6 -0
  140. package/out/chunk-LRWB6QVO.js +1 -0
  141. package/out/chunk-LVSLM7HB.js +1 -0
  142. package/out/chunk-LVW7WWV4.js +1 -0
  143. package/out/chunk-N57OWFKY.js +15 -0
  144. package/out/chunk-NRPC74AM.js +1 -0
  145. package/out/chunk-OOJM4CTU.js +1 -0
  146. package/out/chunk-PKLVXUEI.js +11 -0
  147. package/out/chunk-PLGH63UC.js +2 -0
  148. package/out/chunk-PNHBZGDD.js +1 -0
  149. package/out/chunk-PWFUOLZK.js +17 -0
  150. package/out/chunk-PXK7EU4V.js +1 -0
  151. package/out/chunk-QD3IBSF4.js +7 -0
  152. package/out/chunk-QI66YA4F.js +1 -0
  153. package/out/chunk-QRKFPLA4.js +80 -0
  154. package/out/chunk-R3NZFXVR.js +1 -0
  155. package/out/chunk-R5O6FAW4.js +2 -0
  156. package/out/chunk-RAM3GDAD.js +1 -0
  157. package/out/chunk-RPNO56H2.js +1 -0
  158. package/out/chunk-SMNFBOLO.js +10 -0
  159. package/out/chunk-SSPDMA6D.js +1 -0
  160. package/out/chunk-SZTCJVZJ.js +55 -0
  161. package/out/chunk-SZWPYLPC.js +1 -0
  162. package/out/chunk-TKPNRQNN.js +3 -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-UTYWTUTC.js +1 -0
  168. package/out/chunk-VHEXSGGP.js +1 -0
  169. package/out/chunk-VYYUMYVW.js +9 -0
  170. package/out/chunk-WBK5ZN4K.js +3 -0
  171. package/out/chunk-WCDYSIKG.js +1 -0
  172. package/out/chunk-XM4RLC4A.js +2 -0
  173. package/out/chunk-XRAAYXPR.js +1 -0
  174. package/out/chunk-ZQHLECTI.js +1 -0
  175. package/out/client-managed-import.js +4 -0
  176. package/out/client-managed.js +35 -0
  177. package/out/client-sync.js +11 -17
  178. package/out/compare.js +26 -0
  179. package/out/dialogs.js +40 -0
  180. package/out/github-issue-authorized.html +3 -0
  181. package/out/github-issue-authorized.js +1 -0
  182. package/out/graph.js +19 -5
  183. package/out/index.html +105 -25
  184. package/out/prism.js +14 -10
  185. package/out/scan.js +2 -0
  186. package/out/stasis.svg +20 -0
  187. package/out/terminal.js +367 -39
  188. package/out/view.css +1 -1
  189. package/out/view.js +19 -148
  190. package/package.json +416 -64
  191. package/risk/actions/findings.js +161 -0
  192. package/risk/actions/resolve.js +287 -0
  193. package/risk/actions/scripts/commands.js +182 -0
  194. package/risk/actions/scripts/grade.js +113 -0
  195. package/risk/actions/scripts/packages.js +123 -0
  196. package/risk/actions/scripts/shell.js +169 -0
  197. package/risk/actions/uses.js +94 -0
  198. package/risk/actions/workflow.js +183 -0
  199. package/risk/files/characters.js +354 -0
  200. package/risk/files/hosts.js +206 -0
  201. package/risk/files/readability.js +185 -0
  202. package/risk/files/runs-code.js +568 -0
  203. package/risk/files/script.js +420 -0
  204. package/risk/files/source-map-link.js +43 -0
  205. package/risk/files/stamps.js +47 -0
  206. package/risk/index.d.ts +309 -0
  207. package/risk/index.js +12 -0
  208. package/risk/npm/assess.js +303 -0
  209. package/risk/npm/combined.js +68 -0
  210. package/risk/npm/compare.js +236 -0
  211. package/risk/npm/dependencies.js +172 -0
  212. package/risk/npm/diff.js +79 -0
  213. package/risk/npm/downloads.js +84 -0
  214. package/risk/npm/files.js +445 -0
  215. package/risk/npm/held.js +67 -0
  216. package/risk/npm/install-scripts.js +34 -0
  217. package/risk/npm/malware.js +38 -0
  218. package/risk/npm/manifest.js +65 -0
  219. package/risk/npm/new-dependency.js +60 -0
  220. package/risk/npm/old-version.js +108 -0
  221. package/risk/npm/registry.js +401 -0
  222. package/risk/npm/release.js +85 -0
  223. package/risk/npm/score.js +59 -0
  224. package/risk/npm/specs.js +124 -0
  225. package/risk/npm/tarball.js +169 -0
  226. package/server-common/database-config.ts +16 -0
  227. package/server-common/initialize.ts +18 -0
  228. package/server-common/npm-advisories.ts +101 -0
  229. package/{server → server-common}/origin.ts +5 -5
  230. package/server-common/reap.ts +48 -0
  231. package/server-common/scan-config.ts +19 -0
  232. package/server-common/standalone.ts +29 -0
  233. package/server-common/storage-crypto.ts +182 -0
  234. package/server-common/storage-log.ts +38 -0
  235. package/server-common/vercel-blob.ts +103 -0
  236. package/server-e2e/app.ts +487 -0
  237. package/{server → server-e2e}/bus-receiver.ts +2 -1
  238. package/{server → server-e2e}/cli.js +9 -4
  239. package/{server → server-e2e}/config.ts +52 -42
  240. package/{server → server-e2e}/db-neon.ts +2 -2
  241. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  242. package/{server → server-e2e}/db-stmt.ts +2 -2
  243. package/{server → server-e2e}/db.ts +7 -7
  244. package/{server → server-e2e}/http.ts +44 -13
  245. package/{server → server-e2e}/hub.ts +40 -9
  246. package/server-e2e/index.ts +17 -0
  247. package/server-e2e/lifecycle.ts +95 -0
  248. package/{server → server-e2e}/neon-driver.ts +2 -2
  249. package/{server → server-e2e}/npm-proxy.ts +12 -145
  250. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  251. package/{server → server-e2e}/objstore/blob.ts +1 -1
  252. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  253. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  254. package/{server → server-e2e}/objstore/init.ts +19 -27
  255. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  257. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  258. package/{server → server-e2e}/objstore/rest.ts +3 -3
  259. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  260. package/{server → server-e2e}/objstore/store.ts +7 -7
  261. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  262. package/{server → server-e2e}/pubsub.ts +12 -9
  263. package/{server → server-e2e}/sign.ts +4 -4
  264. package/{server → server-e2e}/sse-server.ts +3 -3
  265. package/{server → server-e2e}/static.ts +18 -17
  266. package/{server → server-e2e}/sync-handlers.ts +56 -30
  267. package/{server → server-e2e}/ws-server.ts +20 -9
  268. package/server-managed/activity.ts +269 -0
  269. package/server-managed/agent-merges.ts +109 -0
  270. package/server-managed/app-agents.ts +23 -0
  271. package/server-managed/avatar-store.ts +21 -0
  272. package/server-managed/blob-store.ts +26 -0
  273. package/server-managed/brotli.ts +10 -0
  274. package/server-managed/bundle-advisories.ts +176 -0
  275. package/server-managed/bundle-advisory-inventory.ts +85 -0
  276. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  277. package/server-managed/bundle-build-diagnostics.js +23 -0
  278. package/server-managed/bundle-build-leases.ts +41 -0
  279. package/server-managed/bundle-build-worker.js +387 -0
  280. package/server-managed/bundle-build.ts +328 -0
  281. package/server-managed/bundle-cache.ts +261 -0
  282. package/server-managed/bundle-catalog.ts +29 -0
  283. package/server-managed/bundle-commits.ts +133 -0
  284. package/server-managed/bundle-dependency-reviews.ts +91 -0
  285. package/server-managed/bundle-store.ts +24 -0
  286. package/server-managed/bundle-summary-cache.ts +139 -0
  287. package/server-managed/bundle-validation.ts +33 -0
  288. package/server-managed/bundle.ts +151 -0
  289. package/server-managed/cache-storage.ts +20 -0
  290. package/server-managed/cli.js +21 -0
  291. package/server-managed/combined.ts +43 -0
  292. package/server-managed/comments.ts +138 -0
  293. package/server-managed/commit-coauthors.ts +105 -0
  294. package/server-managed/commit-lockfiles.ts +78 -0
  295. package/server-managed/comparison.ts +51 -0
  296. package/server-managed/config.ts +163 -0
  297. package/server-managed/content-access.ts +15 -0
  298. package/server-managed/crypto.ts +25 -0
  299. package/server-managed/db-methods.ts +1950 -0
  300. package/server-managed/db-neon.ts +401 -0
  301. package/server-managed/db-schema.ts +271 -0
  302. package/server-managed/db-table-names.ts +22 -0
  303. package/server-managed/db.ts +150 -0
  304. package/server-managed/dependabot-access.ts +85 -0
  305. package/server-managed/dependabot-alerts.ts +197 -0
  306. package/server-managed/dependency-review-comments.ts +158 -0
  307. package/server-managed/dependency-reviews.ts +369 -0
  308. package/server-managed/github-accounts.ts +59 -0
  309. package/server-managed/github-actions.ts +71 -0
  310. package/server-managed/github-app.ts +347 -0
  311. package/server-managed/github-errors.ts +92 -0
  312. package/server-managed/github-graphql.ts +42 -0
  313. package/server-managed/github-issue-links.ts +264 -0
  314. package/server-managed/github-issue-oauth.ts +30 -0
  315. package/server-managed/github-issues.ts +169 -0
  316. package/server-managed/github-link-oauth.ts +56 -0
  317. package/server-managed/github-links.ts +204 -0
  318. package/server-managed/github-metadata.ts +218 -0
  319. package/server-managed/github-oauth.ts +264 -0
  320. package/server-managed/github-pulls.ts +290 -0
  321. package/server-managed/github-requests.ts +181 -0
  322. package/server-managed/github-users.ts +53 -0
  323. package/server-managed/github-values.ts +26 -0
  324. package/server-managed/history-windows.ts +172 -0
  325. package/server-managed/http-response.ts +76 -0
  326. package/server-managed/http.ts +6722 -0
  327. package/server-managed/import-triage.ts +51 -0
  328. package/server-managed/index.ts +204 -0
  329. package/server-managed/kept-briefly.ts +37 -0
  330. package/server-managed/kept.ts +28 -0
  331. package/server-managed/known-listings.ts +112 -0
  332. package/server-managed/link-reports.ts +149 -0
  333. package/server-managed/listed-activity.ts +39 -0
  334. package/server-managed/locked-packages.ts +234 -0
  335. package/server-managed/lockfile-scope.ts +58 -0
  336. package/server-managed/lru.ts +30 -0
  337. package/server-managed/managed-issues.ts +92 -0
  338. package/server-managed/management-catalog.ts +45 -0
  339. package/server-managed/management.ts +116 -0
  340. package/server-managed/npm-delta-worker.js +203 -0
  341. package/server-managed/npm-delta.ts +277 -0
  342. package/server-managed/npm-insights.ts +455 -0
  343. package/server-managed/npm-kept.ts +274 -0
  344. package/server-managed/npm-loads.ts +259 -0
  345. package/server-managed/npm-manifest.ts +117 -0
  346. package/server-managed/npm-packages.ts +477 -0
  347. package/server-managed/npm-patch-paths.ts +86 -0
  348. package/server-managed/npm-patch.ts +457 -0
  349. package/server-managed/npm-provenance.ts +127 -0
  350. package/server-managed/npm-risk.ts +310 -0
  351. package/server-managed/object-storage-disk.ts +147 -0
  352. package/server-managed/object-storage-vercel.ts +71 -0
  353. package/server-managed/object-storage.ts +82 -0
  354. package/server-managed/package-entry-points.ts +127 -0
  355. package/server-managed/pretty-copies.ts +22 -0
  356. package/server-managed/pretty-format.d.ts +4 -0
  357. package/server-managed/pretty-format.js +27 -0
  358. package/server-managed/pretty-print.ts +444 -0
  359. package/server-managed/public-workspace.ts +242 -0
  360. package/server-managed/pull-comment-reviews.ts +161 -0
  361. package/server-managed/pull-dependencies.ts +370 -0
  362. package/server-managed/pull-dependency-reviews.ts +458 -0
  363. package/server-managed/pull-reviews.ts +202 -0
  364. package/server-managed/pulse-walk.ts +164 -0
  365. package/server-managed/queue.ts +54 -0
  366. package/server-managed/release-commits.ts +85 -0
  367. package/server-managed/rename-diff-worker.js +30 -0
  368. package/server-managed/rename-diff.ts +237 -0
  369. package/server-managed/repo-path.ts +21 -0
  370. package/server-managed/report-migration.ts +32 -0
  371. package/server-managed/report-opening.ts +77 -0
  372. package/server-managed/report-query.ts +10 -0
  373. package/server-managed/report-response.ts +16 -0
  374. package/server-managed/report-sources.ts +185 -0
  375. package/server-managed/report-store.ts +77 -0
  376. package/server-managed/repository-actions.ts +220 -0
  377. package/server-managed/repository-agents.ts +422 -0
  378. package/server-managed/repository-aliases.ts +119 -0
  379. package/server-managed/repository-browser.ts +362 -0
  380. package/server-managed/repository-changes.ts +280 -0
  381. package/server-managed/repository-code.ts +222 -0
  382. package/server-managed/repository-dependency-reviews.ts +220 -0
  383. package/server-managed/repository-discovery.ts +83 -0
  384. package/server-managed/repository-history.ts +444 -0
  385. package/server-managed/repository-issues.ts +293 -0
  386. package/server-managed/repository-policy.ts +27 -0
  387. package/server-managed/repository-pulls.ts +207 -0
  388. package/server-managed/repository-pulse.ts +409 -0
  389. package/server-managed/repository-risk-assess.ts +179 -0
  390. package/server-managed/repository-risk-audit.ts +145 -0
  391. package/server-managed/repository-risk-caches.ts +56 -0
  392. package/server-managed/repository-risk-kept.ts +86 -0
  393. package/server-managed/repository-risk-read.ts +296 -0
  394. package/server-managed/repository-risk-stasis.ts +61 -0
  395. package/server-managed/repository-risk-turn.ts +97 -0
  396. package/server-managed/repository-risk.ts +528 -0
  397. package/server-managed/repository-squashes.ts +160 -0
  398. package/server-managed/repository-stamp.ts +41 -0
  399. package/server-managed/request-timing.ts +63 -0
  400. package/server-managed/reviewed-dependencies.ts +170 -0
  401. package/server-managed/revisions.ts +35 -0
  402. package/server-managed/scan-downloads.ts +121 -0
  403. package/server-managed/session.ts +132 -0
  404. package/server-managed/slugs.ts +38 -0
  405. package/server-managed/solidity-entry-points.ts +71 -0
  406. package/server-managed/sql-postgres.ts +34 -0
  407. package/server-managed/sql.ts +107 -0
  408. package/server-managed/stasis-config.ts +147 -0
  409. package/server-managed/stasis-dependencies.ts +280 -0
  410. package/server-managed/static.ts +28 -0
  411. package/server-managed/storage-command.ts +16 -0
  412. package/server-managed/storage-db.ts +183 -0
  413. package/server-managed/storage-encryption.ts +288 -0
  414. package/server-managed/storage-maintenance.ts +259 -0
  415. package/server-managed/storage-payload.ts +121 -0
  416. package/server-managed/storage-stores.ts +91 -0
  417. package/server-managed/storage.ts +82 -0
  418. package/server-managed/team-app-summaries.ts +57 -0
  419. package/server-managed/team-app.ts +162 -0
  420. package/server-managed/team-catalog.ts +7 -0
  421. package/server-managed/team-feed.ts +180 -0
  422. package/server-managed/team-icons.ts +50 -0
  423. package/server-managed/team-npm-scopes.ts +103 -0
  424. package/server-managed/team-progress.ts +77 -0
  425. package/server-managed/team-reports.ts +369 -0
  426. package/server-managed/triage-response.ts +16 -0
  427. package/server-managed/type-only-proof.js +181 -0
  428. package/server-managed/type-only-worker.js +31 -0
  429. package/server-managed/type-only.ts +135 -0
  430. package/server-managed/uploads.ts +106 -0
  431. package/server-managed/upstream-cache.ts +275 -0
  432. package/server-managed/view-as.ts +58 -0
  433. package/server-managed/worker-turns.ts +76 -0
  434. package/server-managed/workspace-shares.ts +170 -0
  435. package/server.ts +70 -0
  436. package/strip-types-loader.js +13 -10
  437. package/server/index.ts +0 -480
  438. package/server/lifecycle.ts +0 -208
  439. /package/{LICENSE → LICENSE-MIT} +0 -0
  440. /package/{server → server-e2e}/auth.ts +0 -0
  441. /package/{server → server-e2e}/config.example.json +0 -0
  442. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  443. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  444. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  445. /package/{server → server-e2e}/peer.ts +0 -0
  446. /package/{server → server-e2e}/sse-session.ts +0 -0
  447. /package/{server → server-e2e}/util.ts +0 -0
  448. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,237 @@
1
+ // Compare's diff of a JavaScript file minified on both sides with the names a
2
+ // minifier renamed alike hidden (GET /api/bundles/:id/rename-diff, GET
3
+ // /api/npm/rename-diff): both sides pretty-printed, as the pretty-print toggle
4
+ // has them (pretty-print.ts), then diffed by @preventive/compare's
5
+ // renamedDiffs in a worker, off the event loop and two at a time per process,
6
+ // with whitespace changes shown and hidden both. Answered as Brotli-encoded
7
+ // JSON, `{ before, blocks, reason, reads, assumed, marks, ignoringWhitespace }`
8
+ // (rename-diff-worker.js), the two files' hashes, `hash` and `otherHash`, and
9
+ // those of the two copies diffed, `prettyHash` and `otherPrettyHash`, which
10
+ // the viewer checks are those it asked about and draws: one file's asked for
11
+ // by both its sides' paths and hashes, or every pair a comparison's viewer
12
+ // diffs so, a line each (renamedPairs). The last few answers are kept in
13
+ // memory by both files' hashes, a private npm version's never, each side read
14
+ // again through the pretty-print cache first, which checks that its source
15
+ // holds a file of that hash. Access is the caller's to check.
16
+ import { Buffer } from 'node:buffer'
17
+ import { promisify } from 'node:util'
18
+ import { brotliDecompress } from 'node:zlib'
19
+ import { layoutPackageDirs, treeLayout } from '@preventive/compare'
20
+ import { computeFileHash } from '@preventive/report'
21
+ import { FILE_HASH } from '../common/bundle-metadata.js'
22
+ import { computeBundleDiff } from '../common/bundle-compare-diff.js'
23
+ import { bundlePkgOf } from '../common/bundle-pkg-of.js'
24
+ import { needsPrettyPrint, prettyExtension } from '../common/pretty-print.js'
25
+ import { type ChangeBlock, blocksHold, textLines } from '../common/line-diff.js'
26
+ import type { OpenedBlob } from './blob-store.ts'
27
+ import { encodeBrotli } from './brotli.ts'
28
+ import { pathOrder } from './npm-packages.ts'
29
+ import { type ComparedSide, PrettyError, type PrettyRequest, opened, prettyText } from './pretty-print.ts'
30
+ import { workerTurns } from './worker-turns.ts'
31
+
32
+ // What a minifier renames: JavaScript, as the viewer offers it for.
33
+ const RENAMABLE = new Set(['js', 'mjs', 'cjs'])
34
+ // Diffs worked out at once per process, each in a worker of its own, and
35
+ // those waiting their turn past them (a Diff view asks for all it shows at
36
+ // once), any more refused.
37
+ const MAX_ACTIVE_DIFFS = 2
38
+ const MAX_WAITING_DIFFS = 16
39
+ // The longest a diff may take, its wait for a worker included, and the most
40
+ // text it is asked of: both sides pretty-printed, which the largest files
41
+ // formatted (MAX_PRETTY_BYTES) stay under.
42
+ const DIFF_TIMEOUT_MS = 60_000
43
+ const MAX_DIFF_CHARS = 64 * 1024 * 1024
44
+ // Answers kept, the one read last last: each holds the old side as diffed.
45
+ // As many as a comparison's viewer may ask for beside the pairs it has come
46
+ // (renamedPairs), so that neither is worked out twice.
47
+ const KEPT_DIFFS = 32
48
+
49
+ // `blocks` and `marks` with whitespace changes shown, `ignoringWhitespace`'s
50
+ // hidden as diff -b hides them.
51
+ export interface RenameDiff {
52
+ before: string; blocks: ChangeBlock[]; reason: string | null; reads: string[]; assumed: string[]; marks: ChangeBlock[]
53
+ ignoringWhitespace: { blocks: ChangeBlock[]; marks: ChangeBlock[] }
54
+ }
55
+
56
+ export interface RenameDiffRequest { base: PrettyRequest; other: PrettyRequest }
57
+
58
+ // The two files a request names, a base's `path` and `hash` and the other
59
+ // side's `otherPath` and `otherHash`, or null where either is no JavaScript
60
+ // file named by its hash.
61
+ export function renameDiffRequest(params: URLSearchParams): RenameDiffRequest | null {
62
+ const side = (path: string, hash: string): PrettyRequest | null => {
63
+ const extension = prettyExtension(path)
64
+ return extension !== null && RENAMABLE.has(extension) && FILE_HASH.test(hash) ? { path, hash, extension } : null
65
+ }
66
+ const base = side(params.get('path') ?? '', params.get('hash') ?? ''), other = side(params.get('otherPath') ?? '', params.get('otherHash') ?? '')
67
+ return base && other ? { base, other } : null
68
+ }
69
+
70
+ const workers = workerTurns({ what: 'rename diff', active: MAX_ACTIVE_DIFFS, waiting: MAX_WAITING_DIFFS, error: PrettyError,
71
+ busy: 'diff-busy', timeout: 'diff-timeout', failed: 'undiffable' })
72
+ const kept = new Map<string, Buffer>()
73
+ const pending = new Map<string, Promise<Buffer>>()
74
+
75
+ // Whether a worker's answer is one as rename-diff-worker.js gives it, its
76
+ // blocks taking the old side it answered to the new one asked of, whitespace
77
+ // changes shown and hidden: checked again here, apart from the worker, as an
78
+ // answer that is not would hide a change.
79
+ function answers(diff: unknown, original: string, after: string): diff is RenameDiff {
80
+ const { before, blocks, reason, reads, assumed, marks, ignoringWhitespace } = (diff ?? {}) as Partial<RenameDiff>
81
+ const strings = (list: unknown) => Array.isArray(list) && list.every(item => typeof item === 'string')
82
+ return typeof before === 'string' && (reason === null || typeof reason === 'string') && strings(reads) && strings(assumed)
83
+ && blocksHold(before, after, blocks, false) && marksFit(original, after, marks)
84
+ && blocksHold(before, after, ignoringWhitespace?.blocks, true) && marksFit(original, after, ignoringWhitespace?.marks)
85
+ }
86
+
87
+ // Whether marked blocks (rename-diff-worker.js) are blocks of the diff of the
88
+ // two files as they are: in order, apart, within both, each as many lines on
89
+ // either side.
90
+ function marksFit(before: string, after: string, marks: unknown): boolean {
91
+ if (!Array.isArray(marks)) return false
92
+ const [olds, news] = [textLines(before).length, textLines(after).length]
93
+ let i = 0, j = 0
94
+ for (const mark of marks as Partial<ChangeBlock>[]) {
95
+ const { a0, a1, b0, b1 } = mark ?? {}
96
+ if (![a0, a1, b0, b1].every(Number.isInteger)) return false
97
+ const [x0, x1, y0, y1] = [a0, a1, b0, b1] as [number, number, number, number]
98
+ if (x0 < i || y0 < j || x1 <= x0 || x1 - x0 !== y1 - y0 || x1 > olds || y1 > news) return false
99
+ i = x1
100
+ j = y1
101
+ }
102
+ return true
103
+ }
104
+
105
+ // The two sides diffed in a worker, its answer checked (answers).
106
+ function inWorker(before: string, after: string, { base, other }: RenameDiffRequest, deadline: number): Promise<RenameDiff> {
107
+ if (before.length + after.length > MAX_DIFF_CHARS) throw new PrettyError(413, 'diff-too-large')
108
+ return workers.run(new URL('./rename-diff-worker.js', import.meta.url), {
109
+ workerData: { before, after, extension: base.extension, otherExtension: other.extension }, execArgv: [],
110
+ resourceLimits: { maxOldGenerationSizeMb: 1024 },
111
+ }, answer => {
112
+ if (answers(answer, before, after)) return answer
113
+ console.warn('managed: a rename diff answered what does not take its old side to the new')
114
+ return null
115
+ }, deadline)
116
+ }
117
+
118
+ // `work` given until `deadline`: past it, answered 504 and left to finish on its own.
119
+ function byDeadline<T>(work: Promise<T>, deadline: number): Promise<T> {
120
+ let timer: ReturnType<typeof setTimeout> | undefined
121
+ const late = new Promise<never>((_, reject) => { timer = setTimeout(() => { reject(new PrettyError(504, 'diff-timeout')) }, deadline - Date.now()) })
122
+ return Promise.race([work, late]).finally(() => { clearTimeout(timer) })
123
+ }
124
+
125
+ // An answer as sent, naming the files asked about and the pretty-printed
126
+ // copies of them it was worked out from.
127
+ async function encoded(diff: RenameDiff, { base, other }: RenameDiffRequest, [before, after]: [string, string]): Promise<Buffer> {
128
+ const [prettyHash, otherPrettyHash] = await Promise.all([computeFileHash(before), computeFileHash(after)])
129
+ return encodeBrotli(Buffer.from(JSON.stringify({ ...diff, hash: base.hash, otherHash: other.hash, prettyHash, otherPrettyHash })))
130
+ }
131
+
132
+ // The answer for the two files a request names, Brotli-encoded, `texts`
133
+ // reading both sides pretty-printed (and so checking each is its source's):
134
+ // kept by their hashes where `keep`, readers asking for one meanwhile sharing
135
+ // it. A minute for it, its wait for a worker included.
136
+ export async function renameDiffOf(request: RenameDiffRequest, texts: () => Promise<[string, string]>, keep = true): Promise<OpenedBlob> {
137
+ return opened(await answerOf(request, texts, keep))
138
+ }
139
+
140
+ // Sides `verified` to be the files the request names (renamedPairs) are read
141
+ // only where no answer is kept or on its way; others are read first, as
142
+ // reading them checks they are.
143
+ async function answerOf(request: RenameDiffRequest, texts: () => Promise<[string, string]>, keep: boolean, verified = false): Promise<Buffer> {
144
+ // Sides not kept are formatted again for each diff (pretty-print.ts), so
145
+ // they are read in its turn: the files a Diff view asks for at once wait
146
+ // here rather than being refused by the formats running. Within its minute
147
+ // too, its turn not held past it by a version's files still downloading.
148
+ if (!keep) {
149
+ const deadline = Date.now() + DIFF_TIMEOUT_MS
150
+ let sides: [string, string] = ['', '']
151
+ const diff = await workers.inTurn(deadline, async () => {
152
+ sides = await byDeadline(texts(), deadline)
153
+ return inWorker(sides[0], sides[1], request, deadline)
154
+ })
155
+ return encoded(diff, request, sides)
156
+ }
157
+ // A file's type is part of how it is read: the same text as a script and as a module differ.
158
+ const key = `${request.base.hash}\0${request.base.extension}\0${request.other.hash}\0${request.other.extension}`
159
+ const held = () => {
160
+ const found = kept.get(key)
161
+ if (found) {
162
+ kept.delete(key)
163
+ kept.set(key, found)
164
+ }
165
+ return found ?? pending.get(key)
166
+ }
167
+ let answer = verified ? held() : undefined
168
+ if (!answer) {
169
+ const [before, after] = await texts()
170
+ answer = held()
171
+ if (!answer) {
172
+ const deadline = Date.now() + DIFF_TIMEOUT_MS
173
+ const job = workers.inTurn(deadline, () => inWorker(before, after, request, deadline)).then(diff => encoded(diff, request, [before, after])).finally(() => pending.delete(key))
174
+ pending.set(key, answer = job)
175
+ }
176
+ }
177
+ const body = await answer
178
+ kept.set(key, body)
179
+ if (kept.size > KEPT_DIFFS) kept.delete(kept.keys().next().value!)
180
+ return body
181
+ }
182
+
183
+ const decompress = promisify(brotliDecompress)
184
+
185
+ // What a minifier renames, by its path's extension.
186
+ const renamable = ({ extension }: PrettyRequest) => RENAMABLE.has(extension)
187
+
188
+ // One of a comparison's pairs of files (renamedPairs), its sides named as a
189
+ // request names them, with its answer as renameDiffOf sends it, or why it has
190
+ // none, as a PrettyError tells it.
191
+ export type RenamedLine = { path: string; hash: string; otherPath: string; otherHash: string } & (Partial<RenameDiff> | { error: string; status: number })
192
+
193
+ // The files that changed between a comparison's two sides, as its viewer
194
+ // pairs them (ui/view/bundle-comparison.js prepareComparison): at one path as
195
+ // the other side lays them out, or renamed within a package, as the bundles
196
+ // record their packages; every file there, those that can be formatted by
197
+ // their texts and the rest by their hashes. A file the viewer pairs otherwise
198
+ // (its files are its resources too) it asks about alone.
199
+ export function comparedFiles(sides: readonly [ComparedSide, ComparedSide]) {
200
+ const [olds, news] = sides.map(({ files, hashes }) => {
201
+ const texts = new Map(files.map(file => [file.path, file.text]))
202
+ return new Map<string, unknown>([...hashes].map(([path, hash]) => [path, texts.get(path) ?? { format: 'digest', digest: hash }]))
203
+ }) as [Map<string, unknown>, Map<string, unknown>]
204
+ const layout = treeLayout(olds.keys(), news.keys())
205
+ const packageDirs = layoutPackageDirs(sides[0].packageDirs, sides[1].packageDirs, layout)
206
+ return computeBundleDiff(olds, news, path => bundlePkgOf(path, { packageDir: packageDirs?.get(path) }), layout).files
207
+ }
208
+
209
+ // The pairs of JavaScript files minified on both sides that changed between a
210
+ // comparison's two sides, paired as its viewer pairs them (comparedFiles),
211
+ // each diffed as renameDiffOf diffs it, from both sides' copies, kept or
212
+ // made, as they are iterated: in path order, one after another, leaving a
213
+ // worker to the files a viewer asks for alone (a pair it reads otherwise, one
214
+ // it shows first).
215
+ export function renamedPairs([base, other]: readonly [ComparedSide, ComparedSide], keep = true): AsyncGenerator<RenamedLine> {
216
+ const formattable = ({ files }: ComparedSide) => new Map(files.map(file => [file.path, file]))
217
+ const [olds, news] = [formattable(base), formattable(other)]
218
+ const pairs = comparedFiles([base, other]).changed.flatMap(({ path, basePath = path }) => {
219
+ const [from, to] = [olds.get(basePath), news.get(path)]
220
+ return from && to && from.hash !== to.hash && [from, to].every(file => renamable(file) && needsPrettyPrint(file.path, file.text)) ? [[from, to] as const] : []
221
+ }).toSorted(([, a], [, b]) => pathOrder(a.path, b.path))
222
+ return (async function* () {
223
+ for (const [from, to] of pairs) {
224
+ const request = { base: { path: from.path, hash: from.hash, extension: from.extension }, other: { path: to.path, hash: to.hash, extension: to.extension } }
225
+ const named = { path: from.path, hash: from.hash, otherPath: to.path, otherHash: to.hash }
226
+ const copy = async (side: ComparedSide, { text, ...file }: typeof from) => prettyText(await side.kept(file) ?? await side.made(file, text))
227
+ let body
228
+ try { body = await answerOf(request, async () => [await copy(base, from), await copy(other, to)], keep, true) }
229
+ catch (err) {
230
+ if (!(err instanceof PrettyError)) throw err
231
+ yield { ...named, error: err.message, status: err.status }
232
+ continue
233
+ }
234
+ yield { ...JSON.parse((await decompress(body)).toString('utf8')) as Partial<RenameDiff>, ...named }
235
+ }
236
+ })()
237
+ }
@@ -0,0 +1,21 @@
1
+ const MAX_TEAM_PATH = 500
2
+
3
+ // Canonicalize only equivalent Git paths: '/' separates components and empty
4
+ // or '.' components do not change the directory. Reject ambiguous input rather
5
+ // than deleting characters from directory names used for authorization.
6
+ // `{ ok:false }` makes the handler 400; `{ path:null }` means the whole repo.
7
+ export function normalizeTeamPath(raw: unknown): { ok: true; path: string | null } | { ok: false } {
8
+ if (typeof raw !== 'string') return { ok: true, path: null }
9
+ // Spaces and backslashes can be literal parts of Git directory names.
10
+ // Neither trimming nor treating '\\' as a separator preserves that identity.
11
+ if (/\p{Cc}/u.test(raw) || raw.includes('\\') || raw !== raw.trim()) return { ok: false }
12
+ const segments: string[] = []
13
+ for (const seg of raw.split('/')) {
14
+ if (seg === '' || seg === '.') continue
15
+ if (seg === '..' || seg !== seg.trim()) return { ok: false }
16
+ segments.push(seg)
17
+ }
18
+ const path = segments.join('/')
19
+ if (path.length > MAX_TEAM_PATH) return { ok: false }
20
+ return { ok: true, path: path === '' ? null : path }
21
+ }
@@ -0,0 +1,32 @@
1
+ // SQLite deployments store report blobs beside the database. Recover location
2
+ // metadata before introducing directory-based team access. Schema and data move
3
+ // together so a missing/corrupt blob leaves the migration retryable after repair.
4
+ import { readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import type { DatabaseSync } from 'node:sqlite'
7
+ import { reportRepoGithub } from '@preventive/report'
8
+ import { readManagedReport } from '../common/managed/report-content.ts'
9
+ import { normalizeTeamPath } from './repo-path.ts'
10
+ import { isBlobId } from './object-storage.ts'
11
+ import { sqliteTransaction } from './sql.ts'
12
+
13
+ export function migrateReportLocations(db: DatabaseSync, reportDir: string): void {
14
+ const columns = db.prepare('PRAGMA table_info(managed_report)').all() as { name: string }[]
15
+ if (columns.some((column) => column.name === 'repo_directory')) return
16
+ sqliteTransaction(db, 'BEGIN IMMEDIATE', () => {
17
+ db.exec("ALTER TABLE managed_report ADD COLUMN repo_directory TEXT NOT NULL DEFAULT ''")
18
+ const update = db.prepare('UPDATE managed_report SET repo_directory = ?, repo_embedded = ? WHERE id = ?')
19
+ const reports = db.prepare('SELECT id, filename FROM managed_report').all() as { id: string, filename: string }[]
20
+ for (const { id, filename } of reports) {
21
+ // Same opaque UUID boundary as the blob store; never splice arbitrary
22
+ // database text into a filesystem path during an upgrade.
23
+ if (!isBlobId(id)) throw new Error(`Invalid legacy report id: ${id}`)
24
+ const { data } = readManagedReport(readFileSync(join(reportDir, id), 'utf8'), filename)
25
+ if (data == null) throw new Error(`Cannot migrate location of unreadable report ${id}`)
26
+ const embedded = reportRepoGithub(data) != null
27
+ const directory = normalizeTeamPath(data.repo?.directory)
28
+ if (!directory.ok) throw new Error(`Cannot migrate invalid directory of report ${id}`)
29
+ update.run(directory.path ?? '', embedded ? 1 : 0, id)
30
+ }
31
+ })
32
+ }
@@ -0,0 +1,77 @@
1
+ // Whether a stored report may be switched to open on Confirmed (Manage →
2
+ // Reports), told of its content alone: where its pass leaves Confirmed rows of
3
+ // its own but it is no App view on its own, by the stricter rule App mode
4
+ // keeps (common/workspace-app.js confirmedDefaultOffered). A switched report's
5
+ // findings count as covered wherever Confirmed would hide them
6
+ // (common/finding-filters.js confirmedCoverage), both for the outcome a view
7
+ // opens on and for its team's App mode.
8
+ //
9
+ // Read as a report is uploaded, and kept (managed_report confirmed_offered):
10
+ // its bytes never change. One uploaded before the column is read as the
11
+ // reports page lists it, a bounded share of them each time, or as its switch
12
+ // is asked for.
13
+ import { backfillFindingIds, reportEntries } from '@preventive/report'
14
+ import { readManagedReport } from '../common/managed/report-content.ts'
15
+ import { managedReportConfirmedDefaultOffered } from '../common/managed/team-app.js'
16
+ import type { BlobStore } from './blob-store.ts'
17
+ import type { ManagedDb } from './db.ts'
18
+ import { eachOf } from './queue.ts'
19
+
20
+ // Of a report's parsed content, its findings' IDs backfilled first as a team's
21
+ // are (team-reports.ts), which it changes in place. A report whose rows cannot
22
+ // be read this way has no switch to offer.
23
+ export async function confirmedDefaultOffered(filename: string, data: unknown): Promise<boolean> {
24
+ try {
25
+ const findings = (reportEntries(data) ?? []).flatMap(entry => Array.isArray(entry) ? entry : [entry])
26
+ .filter((finding): finding is Record<string, unknown> => finding !== null && typeof finding === 'object' && !Array.isArray(finding))
27
+ await backfillFindingIds(findings)
28
+ return managedReportConfirmedDefaultOffered(filename, data)
29
+ } catch (error) {
30
+ console.warn('managed: reading a report for its opening failed:', error)
31
+ return false
32
+ }
33
+ }
34
+
35
+ // Of a stored report, read of its blob: null where its bytes cannot be read
36
+ // now, so a later read tries again.
37
+ async function readStored(store: BlobStore, report: { id: string; filename: string }): Promise<boolean | null> {
38
+ const bytes = await store.get(report.id).catch(() => null)
39
+ if (!bytes) return null
40
+ const { data } = readManagedReport(bytes.toString('utf8'), report.filename)
41
+ return data == null ? false : confirmedDefaultOffered(report.filename, data)
42
+ }
43
+
44
+ // The same, kept.
45
+ export async function readConfirmedOffered(db: ManagedDb, store: BlobStore, report: { id: string; filename: string }): Promise<boolean | null> {
46
+ const offered = await readStored(store, report)
47
+ if (offered !== null) await db.setReportsConfirmedOffered([{ id: report.id, offered }])
48
+ return offered
49
+ }
50
+
51
+ // At most this many bytes of reports not read yet are read for one listing,
52
+ // two at a time, and kept in one write; the rest wait for the next.
53
+ const LISTING_READ_BYTES = 64 * 1024 * 1024
54
+ const LISTING_READS_AT_ONCE = 2
55
+
56
+ // The listed reports, those not read for their opening yet read, as many as
57
+ // fit the bound: the first always, however large.
58
+ export async function withConfirmedOffered<T extends { id: string; filename: string; byteSize: number; confirmedOffered: boolean | null }>(
59
+ db: ManagedDb, store: BlobStore, reports: readonly T[]): Promise<T[]> {
60
+ let budget = LISTING_READ_BYTES
61
+ const unread = reports.filter(report => {
62
+ if (report.confirmedOffered !== null || budget <= 0) return false
63
+ budget -= report.byteSize
64
+ return true
65
+ })
66
+ if (unread.length === 0) return [...reports]
67
+ const read = new Map<string, boolean>()
68
+ await eachOf(unread, LISTING_READS_AT_ONCE, async report => {
69
+ const offered = await readStored(store, report).catch((error: unknown) => {
70
+ console.warn('managed: reading a report for its opening failed:', error)
71
+ return null
72
+ })
73
+ if (offered !== null) read.set(report.id, offered)
74
+ })
75
+ if (read.size > 0) await db.setReportsConfirmedOffered([...read].map(([id, offered]) => ({ id, offered })))
76
+ return reports.map(report => read.has(report.id) ? { ...report, confirmedOffered: read.get(report.id)! } : report)
77
+ }
@@ -0,0 +1,10 @@
1
+ // Large workspaces remain a single request. Bound both the stored input and
2
+ // the encoded response, independently of the per-upload size limit.
3
+ export const MAX_REPORT_QUERY_COUNT = 4096
4
+ export const MAX_REPORT_QUERY_BYTES = 1024 * 1024 * 1024
5
+
6
+ // The import catalog scans a bounded page, not the whole installation. A
7
+ // report larger than the byte target occupies a page by itself; upload limits
8
+ // still bound that single report and the cursor must always make progress.
9
+ export const FINDING_CATALOG_PAGE_COUNT = 128
10
+ export const FINDING_CATALOG_PAGE_BYTES = 32 * 1024 * 1024
@@ -0,0 +1,16 @@
1
+ import { MIMEType } from 'node:util'
2
+
3
+ // The metadata envelope is opt-in. Wildcards keep the legacy raw report;
4
+ // an explicit, acceptable application/json range requests the envelope.
5
+ export function acceptsReportMetadata(accept: string | undefined): boolean {
6
+ // Commas inside quoted media-type parameters do not separate ranges.
7
+ for (const range of accept?.match(/(?:[^",]|"(?:\\.|[^"\\])*")+/gu) ?? []) {
8
+ try {
9
+ const media = new MIMEType(range.trim())
10
+ if (media.essence !== 'application/json') continue
11
+ const quality = media.params.get('q') ?? '1'
12
+ if (/^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u.test(quality) && Number(quality) > 0) return true
13
+ } catch { /* Ignore malformed media ranges. */ }
14
+ }
15
+ return false
16
+ }
@@ -0,0 +1,185 @@
1
+ import { Buffer } from 'node:buffer'
2
+ import { createHash } from 'node:crypto'
3
+ import { extname } from 'node:path'
4
+ import { promisify } from 'node:util'
5
+ import { gzip } from 'node:zlib'
6
+ import { bundlePackageDirs, bundlePackageRepos, bundleSourcesAsMap } from '../common/bundle-sources.js'
7
+ import { bundleSourceLinkImports } from '../common/bundle-source-links.js'
8
+ import type { BundleDetails } from '../common/bundle-metadata.js'
9
+ import { loadManagedFindings, managedFindingSourcePaths } from '../common/managed/report-content.ts'
10
+ import { type ViewerPermissions, filterReportContent } from '../common/managed/report-filter.ts'
11
+ import { ourRepoSlugs } from '../common/finding-repo.js'
12
+ import { CacheMissError, type CacheStorage } from './cache-storage.ts'
13
+ import { readBundleDetails } from './bundle-cache.ts'
14
+ import type { BlobStore } from './blob-store.ts'
15
+ import type { BundleStore } from './bundle-store.ts'
16
+ import type { ManagedBundle, ManagedDb, ReportRecord } from './db.ts'
17
+ import { inTurns } from './queue.ts'
18
+ import { ourRepositoryNames } from './repository-aliases.ts'
19
+
20
+ const compress = promisify(gzip)
21
+ const reportFormat = (filename: string) => extname(filename).toLowerCase()
22
+
23
+ function bundleDirectory(id: string) {
24
+ if (!/^[a-f\d-]{36}$/iu.test(id)) throw new Error('Invalid bundle id')
25
+ return id
26
+ }
27
+ function reportDirectory(bundleId: string, sha256: string) {
28
+ return `${bundleDirectory(bundleId)}/v1-${createHash('sha256').update(sha256).digest('hex')}`
29
+ }
30
+ function formatDirectory(bundleId: string, sha256: string, name: string) {
31
+ return `${reportDirectory(bundleId, sha256)}/${createHash('sha256').update(reportFormat(name)).digest('hex')}`
32
+ }
33
+ function sourceCacheFilename(report: ReportRecord, bundle: ManagedBundle, permissions: ViewerPermissions, repo: { github: string | null }, sourcePaths?: Set<string>) {
34
+ const key = createHash('sha256').update(JSON.stringify([
35
+ 'finding-access-v11', sourcePaths ? [...sourcePaths].toSorted() : null, bundle.integrity, bundle.kind, permissions.dependencies, permissions.security, repo,
36
+ ])).digest('hex')
37
+ return `${formatDirectory(bundle.id, report.sha256, report.filename)}/${key}.json.gz`
38
+ }
39
+
40
+ // Match the report's spelling exactly, then an unambiguous path suffix. Never
41
+ // guess between duplicate basenames or treat a bundle path as a disk pathname.
42
+ function selectSources(sourcePaths: Set<string>, sources: Map<string, string>) {
43
+ const byBasename = new Map<string, string[]>()
44
+ for (const file of sources.keys()) {
45
+ const basename = file.split('/').at(-1)!
46
+ const candidates = byBasename.get(basename) ?? []
47
+ candidates.push(file)
48
+ byBasename.set(basename, candidates)
49
+ }
50
+ const files = new Map<string, string>(), paths = new Map<string, string>()
51
+ function add(path: unknown) {
52
+ if (typeof path !== 'string' || !path || paths.has(path)) return
53
+ let file = sources.has(path) ? path : null
54
+ if (file === null) {
55
+ const suffix = path.startsWith('/') ? path : `/${path}`
56
+ const matches = byBasename.get(path.split('/').at(-1)!)?.filter(candidate => candidate.endsWith(suffix)) ?? []
57
+ if (matches.length === 1) file = matches[0]!
58
+ }
59
+ if (file === null) return
60
+ paths.set(path, file)
61
+ files.set(file, sources.get(file)!)
62
+ }
63
+ for (const path of sourcePaths) add(path)
64
+ return { files: [...files], paths: [...paths] }
65
+ }
66
+
67
+ function encodeSources(integrity: string, details: BundleDetails, selection: ReturnType<typeof selectSources>) {
68
+ const sources = new Map(selection.files)
69
+ const imports = [...bundleSourceLinkImports(details, sources)].map(([parent, targets]) => [parent, [...targets]])
70
+ const bundle = details.kind === 'stasis' ? details.bundle as { formats: Map<string, string> } : null
71
+ const formats = [...(bundle?.formats ?? [])].filter(([file]) => sources.has(file))
72
+ const packageDirs = [...(bundlePackageDirs(details) ?? [])].filter(([file]) => sources.has(file))
73
+ // The repository and commit each of those files' packages records, which
74
+ // the finding's dependency evidence links to (focus-code.js).
75
+ const packageRepos = [...bundlePackageRepos(details, new Set(packageDirs.map(([, dir]) => dir)))]
76
+ return compress(Buffer.from(JSON.stringify({ integrity, ...selection, imports, formats, packageDirs, packageRepos })), { level: 6 })
77
+ }
78
+
79
+ type SourcemapEdges = (bundle: ManagedBundle) => Promise<BundleDetails['edges']>
80
+
81
+ // A sourcemap's imports follow the edges its metadata keeps (the bundle
82
+ // cache's `sourcemapEdges`), read with the parser, else what edges-lite.js reads.
83
+ async function lendSourcemapEdges(details: BundleDetails, bundle: ManagedBundle, sourcemapEdges?: SourcemapEdges) {
84
+ if (details.kind !== 'sourcemap' || !sourcemapEdges) return
85
+ const edges = await sourcemapEdges(bundle).catch(() => undefined)
86
+ if (edges) details.edges = edges
87
+ }
88
+
89
+ // The repositories that are ours, so that a finding's `repo` none of them is
90
+ // left out (common/finding-repo.js isStrayRepo).
91
+ async function oursFor(db: ManagedDb, repo: { github: string | null }): Promise<Set<string>> {
92
+ return ourRepoSlugs([...await ourRepositoryNames(db), repo.github])
93
+ }
94
+
95
+ // Immutable report hashes share a derivative across duplicate uploads. Bundle
96
+ // identity and visibility are part of the key: a broader viewer's sources must
97
+ // never populate a restricted response. Group derivatives by hash and filename
98
+ // format so each format's permissions can be removed after its last deletion.
99
+ export function createReportSourcesCache(storage: CacheStorage, db: ManagedDb, reports: BlobStore, bundles: BundleStore, sourcemapEdges?: SourcemapEdges) {
100
+ const pending = new Map<string, { reportId: string; job: Promise<boolean> }>()
101
+ const enqueue = inTurns(1)
102
+ async function referenced(report: ReportRecord, bundle: ManagedBundle) {
103
+ const names = await db.listReportFilenamesWithBundleHash(bundle.id, report.sha256)
104
+ return names.some(name => reportFormat(name) === reportFormat(report.filename)) && await db.getBundle(bundle.id) != null
105
+ }
106
+ async function build(target: string, report: ReportRecord, bundle: ManagedBundle, permissions: ViewerPermissions, repo: { github: string | null }, sourcePaths?: Set<string>) {
107
+ // Team requests supply paths from their already-filtered members. Reopening
108
+ // the original report by ID would conflate visible and hidden occurrences.
109
+ if (!sourcePaths) {
110
+ const bytes = await reports.get(report.id)
111
+ if (!bytes) return false
112
+ const parsed = await loadManagedFindings(filterReportContent(bytes.toString('utf8'), permissions, report.filename, repo, await oursFor(db, repo)), report.filename)
113
+ if (!parsed) return false
114
+ sourcePaths = managedFindingSourcePaths(parsed.findings)
115
+ }
116
+ const details = await readBundleDetails(bundle, bundles)
117
+ if (!details) return false
118
+ await lendSourcemapEdges(details, bundle, sourcemapEdges)
119
+ const selection = selectSources(sourcePaths, bundleSourcesAsMap(details))
120
+ const body = await encodeSources(bundle.integrity, details, selection)
121
+ // A duplicate with the same hash AND format can use these parsed bytes.
122
+ // Another format must not keep a deleted variant's late build alive.
123
+ if (!(await referenced(report, bundle))) return false
124
+ await storage.put(target, body)
125
+ // Another instance may finish deletion while this write is in flight.
126
+ // Recheck after publishing so a late builder cannot resurrect its cache.
127
+ if (!(await referenced(report, bundle))) {
128
+ await storage.delete(formatDirectory(bundle.id, report.sha256, report.filename))
129
+ return false
130
+ }
131
+ return true
132
+ }
133
+ async function ensure(target: string, report: ReportRecord, bundle: ManagedBundle, permissions: ViewerPermissions, repo: { github: string | null }, sourcePaths?: Set<string>): Promise<boolean> {
134
+ const existing = pending.get(target)
135
+ if (existing) {
136
+ const ready = await existing.job
137
+ if (ready || existing.reportId === report.id) return ready
138
+ // Deletion can also win before the initiator reads its blob. Retry with
139
+ // this request's row instead of caching that other row's miss as 204.
140
+ const initiator = await db.getReport(existing.reportId)
141
+ if (initiator?.bundleId === bundle.id && initiator.sha256 === report.sha256) return false
142
+ if (pending.get(target) === existing) pending.delete(target)
143
+ return ensure(target, report, bundle, permissions, repo, sourcePaths)
144
+ }
145
+ const job = (async () => {
146
+ if (await storage.exists(target)) return true
147
+ // Serial cold builds bound peak decompression/parsing memory.
148
+ return enqueue(() => build(target, report, bundle, permissions, repo, sourcePaths))
149
+ })()
150
+ const entry = { reportId: report.id, job }
151
+ pending.set(target, entry)
152
+ try { return await job } finally { if (pending.get(target) === entry) pending.delete(target) }
153
+ }
154
+ return {
155
+ async open(report: ReportRecord, bundle: ManagedBundle, permissions: ViewerPermissions, sourcePaths?: Set<string>) {
156
+ const repo = { github: report.repoId == null ? null : await db.getRepoFullName(report.repoId) }
157
+ const target = sourceCacheFilename(report, bundle, permissions, repo, sourcePaths)
158
+ try { return { ...await storage.open(target), repo } }
159
+ catch (error) { if (!(error instanceof CacheMissError)) throw error }
160
+ if (!(await ensure(target, report, bundle, permissions, repo, sourcePaths))) return null
161
+ const opened = await storage.open(target)
162
+ return { ...opened, repo }
163
+ },
164
+ async deleteBundle(id: string) {
165
+ const prefix = `${bundleDirectory(id)}/`
166
+ await Promise.allSettled([...pending].filter(([key]) => key.startsWith(prefix)).map(([, entry]) => entry.job))
167
+ await storage.delete(bundleDirectory(id))
168
+ },
169
+ async deleteReport(report: Pick<ReportRecord, 'bundleId' | 'sha256' | 'filename'>) {
170
+ const { bundleId, sha256 } = report
171
+ if (bundleId === null) return
172
+ // Called after metadata deletion. Serialize with builders so a cold
173
+ // request cannot recreate a derivative after its cleanup has finished.
174
+ await enqueue(async () => {
175
+ const names = await db.listReportFilenamesWithBundleHash(bundleId, sha256)
176
+ if (names.length === 0) {
177
+ await storage.delete(reportDirectory(bundleId, sha256))
178
+ } else if (!names.some(name => reportFormat(name) === reportFormat(report.filename))) {
179
+ await storage.delete(formatDirectory(bundleId, sha256, report.filename))
180
+ }
181
+ })
182
+ },
183
+ }
184
+ }
185
+ export type ReportSourcesCache = ReturnType<typeof createReportSourcesCache>