@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,269 @@
1
+ // Persistent workspace activity. Uploads are recorded in the same transaction
2
+ // as their metadata; triage reuses its existing immutable trail, including
3
+ // legacy entries. Never copy annotation bodies or credentials into this feed.
4
+ import { randomUUID } from 'node:crypto'
5
+ import type { DatabaseSync } from 'node:sqlite'
6
+ import { type ManagedSql, sqliteTransaction } from './sql.ts'
7
+ import { inUserTeamScope } from './db-schema.ts'
8
+ import { reviewsIn } from './dependency-reviews.ts'
9
+ import { REVIEW_VERDICTS } from '../common/dependency-reviews.js'
10
+
11
+ export interface ActivityInput {
12
+ kind: 'access' | 'repository' | 'visibility' | 'delete'
13
+ actor: string
14
+ actorId?: string | null
15
+ action: string
16
+ repo?: string | null
17
+ reportId?: string | null
18
+ bundleId?: string | null
19
+ repoId?: number | null
20
+ repoDirectory?: string | null
21
+ report?: string | null
22
+ }
23
+
24
+ export interface ActivityContext {
25
+ finding: string
26
+ reportId: string
27
+ report: string
28
+ repo: string | null
29
+ }
30
+
31
+ // `actor` is the login of who acted as it is now, else the one recorded;
32
+ // `actorId` the user they are (null for a legacy login), and `actorName` the
33
+ // name they chose to show, as it is now.
34
+ export type ActivityEntry = {
35
+ id: string; kind: string; actor: string | null; actorId: string | null; actorName: string | null; action: string
36
+ repo: string | null; reportId: string | null; report: string | null
37
+ finding: string | null; at: number
38
+ }
39
+
40
+ export interface ActivityQuery {
41
+ page: number
42
+ limit: number
43
+ kind: string
44
+ query: string
45
+ repo?: string
46
+ actor?: string
47
+ // null = admin; [] = no accessible findings. Context is supplied by the
48
+ // server, never by the client. It also replaces potentially private context
49
+ // from an old report carrying the same globally shared finding.
50
+ contexts: ActivityContext[] | null
51
+ userId?: string
52
+ }
53
+
54
+ export interface ActivityFilters {
55
+ repos: string[]
56
+ // `id` is the actor's filter key; `userId` the user, null for a legacy login.
57
+ users: { id: string; userId: string | null; login: string; name: string | null; detail: string | null }[]
58
+ }
59
+
60
+ export interface ActivityStore {
61
+ recordActivity(entry: ActivityInput, at: number): Promise<void>
62
+ listActivityReports(userId: string): Promise<Omit<ActivityContext, 'finding'>[]>
63
+ listActivity(query: ActivityQuery): Promise<{ history: ActivityEntry[]; total: number; page: number; limit: number; filters: ActivityFilters }>
64
+ }
65
+
66
+ const triageFields = `'triage:' || e.seq AS id, 'triage' AS kind,
67
+ COALESCE(u.login, e.actor_login) AS actor, e.actor_id AS actorId,
68
+ CASE WHEN e.color IS NULL AND e.triage IS NULL AND e.comment IS NULL AND e.fix IS NULL AND e.flagged IS NULL
69
+ THEN 'cleared triage' ELSE 'updated triage' END AS action`
70
+ const commentFields = `'comment:' || e.seq AS id, 'triage' AS kind,
71
+ COALESCE(u.login, e.actor_login) AS actor, e.actor_id AS actorId, e.action`
72
+ // The events of a finding trail (`table`), with `fields` and the context each
73
+ // recorded.
74
+ const recordedEvents = (fields: string, table: string) => `SELECT ${fields}, e.repo, e.report_id AS reportId, e.report, e.finding_id AS finding, e.at
75
+ FROM ${table} e LEFT JOIN managed_user u ON u.id = e.actor_id`
76
+ // Package reviews as published, read of the reviews themselves, never copied
77
+ // into managed_activity: each once, when it was first published, by its author
78
+ // (their login as they reviewed, and who they are), with its final verdict and
79
+ // what it reviewed as its target; never its comments. Publishing it to more
80
+ // teams, or revoking it, adds no entry. `where` narrows them.
81
+ const reviewVerdict = `CASE r.status ${Object.entries(REVIEW_VERDICTS)
82
+ .map(([status, label]) => `WHEN '${status}' THEN '${label.replace(/ \(.*\)$/u, '')}'`).join(' ')} END`
83
+ const reviewedVersion = (name: string, version: string, patch: string) => `${name} || '@' || ${version} || CASE WHEN ${patch} <> '' THEN ' (patched)' ELSE '' END`
84
+ const reviewEvents = (where = '') => `SELECT 'review:' || r.id AS id, 'review' AS kind, r.user_login AS actor, r.user_id AS actorId,
85
+ 'published a review' || COALESCE(' (' || ${reviewVerdict} || ')', '') AS action,
86
+ NULL AS repo, NULL AS reportId,
87
+ ${reviewedVersion('r.package', 'r.version', 'r.patch_hash')} || CASE WHEN r.base_package = '' THEN ''
88
+ WHEN r.base_package = r.package THEN ' compared with ' || r.base_version || CASE WHEN r.base_patch_hash <> '' THEN ' (patched)' ELSE '' END
89
+ ELSE ' compared with ' || ${reviewedVersion('r.base_package', 'r.base_version', 'r.base_patch_hash')} END AS report,
90
+ NULL AS finding, r.published_at AS at
91
+ FROM managed_dependency_review r WHERE r.published_at IS NOT NULL${where}`
92
+ const adminSource = `${recordedEvents(triageFields, 'managed_finding_triage_event')}
93
+ UNION ALL ${recordedEvents(commentFields, 'managed_finding_comment_event')} UNION ALL
94
+ SELECT id, kind, actor, actor_id AS actorId, action, repo, report_id AS reportId, report, NULL AS finding, at FROM managed_activity
95
+ UNION ALL ${reviewEvents()}`
96
+ // The events of the accessible findings in a finding trail (`table`), with
97
+ // `fields` and the context the server gives each finding. Keep the finite
98
+ // set of accessible findings outside the indexed event lookup. Scanning all
99
+ // events against json_each for every row is quadratic.
100
+ const contextEvents = (fields: string, table: string) => `SELECT ${fields},
101
+ json_extract(c.value, '$.repo') AS repo, json_extract(c.value, '$.reportId') AS reportId,
102
+ json_extract(c.value, '$.report') AS report, e.finding_id AS finding, e.at
103
+ FROM json_each(:contexts) c
104
+ CROSS JOIN ${table} e ON e.finding_id = json_extract(c.value, '$.finding')
105
+ LEFT JOIN managed_user u ON u.id = e.actor_id`
106
+ const managerSource = `${contextEvents(triageFields, 'managed_finding_triage_event')}
107
+ UNION ALL ${contextEvents(commentFields, 'managed_finding_comment_event')}
108
+ UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId,
109
+ CASE WHEN a.kind = 'repository' THEN 'changed a report repository assignment' ELSE a.action END AS action,
110
+ p.full_name AS repo, r.id AS reportId, r.filename AS report, NULL AS finding, a.at
111
+ FROM managed_activity a JOIN managed_report r ON r.id = a.report_id
112
+ LEFT JOIN managed_selected_repo p ON p.repo_id = r.repo_id
113
+ WHERE ${inUserTeamScope(':userId', 'r')}
114
+ UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId,
115
+ CASE WHEN a.kind = 'repository' THEN 'changed a bundle repository assignment' ELSE a.action END AS action,
116
+ p.full_name AS repo, NULL AS reportId, b.filename AS report, NULL AS finding, a.at
117
+ FROM managed_activity a JOIN managed_bundle b ON b.id = a.bundle_id
118
+ LEFT JOIN managed_selected_repo p ON p.repo_id = b.repo_id
119
+ WHERE a.report_id IS NULL AND ${inUserTeamScope(':userId', 'b')}
120
+ UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId, a.action, a.repo, a.report_id AS reportId,
121
+ a.report, NULL AS finding, a.at FROM managed_activity a
122
+ WHERE a.kind = 'delete' AND (a.report_id IS NOT NULL OR a.bundle_id IS NOT NULL)
123
+ AND NOT EXISTS (SELECT 1 FROM managed_report WHERE id = a.report_id)
124
+ AND NOT EXISTS (SELECT 1 FROM managed_bundle WHERE id = a.bundle_id)
125
+ AND ${inUserTeamScope(':userId', 'a')}
126
+ UNION ALL ${reviewEvents(` AND (r.user_id = :userId OR EXISTS (SELECT 1 FROM managed_dependency_review_team rt
127
+ JOIN managed_team t ON t.id = rt.team_id JOIN managed_user u ON u.id = :userId
128
+ WHERE rt.review_id = r.id AND ${reviewsIn(false)}))`)}`
129
+
130
+ export const ACTIVITY_SCHEMA = `
131
+ CREATE TABLE IF NOT EXISTS managed_activity (
132
+ id TEXT PRIMARY KEY, kind TEXT NOT NULL, actor TEXT, action TEXT NOT NULL,
133
+ repo TEXT, report_id TEXT, report TEXT, at INTEGER NOT NULL,
134
+ bundle_id TEXT, repo_id INTEGER, repo_directory TEXT, actor_id TEXT
135
+ ) STRICT;
136
+ CREATE INDEX IF NOT EXISTS managed_activity_at_idx ON managed_activity(at, id);
137
+ CREATE INDEX IF NOT EXISTS finding_triage_event_at_idx ON managed_finding_triage_event(at, seq);
138
+ `
139
+
140
+ export function initActivityMethods(db: DatabaseSync): void {
141
+ db.exec(ACTIVITY_SCHEMA)
142
+ migrateActivityScope(db)
143
+ db.exec('CREATE INDEX IF NOT EXISTS managed_activity_actor_at_idx ON managed_activity(actor_id, at)')
144
+ // Stable upload IDs make backfill idempotent, including after restarts.
145
+ // Snapshots deliberately have no cascading FKs: deletion is itself activity.
146
+ // CREATE TRIGGER IF NOT EXISTS keeps an older body; replace the one that
147
+ // predates server-built bundles so builds are not recorded as uploads.
148
+ const bundleTrigger = db.prepare("SELECT sql FROM sqlite_schema WHERE type = 'trigger' AND name = 'managed_bundle_activity'").get() as { sql: string } | undefined
149
+ if (bundleTrigger && !bundleTrigger.sql.includes('provenance')) db.exec('DROP TRIGGER managed_bundle_activity')
150
+ for (const type of ['report', 'bundle']) {
151
+ const columns = `id, kind, actor, action, repo, report_id, report, at, bundle_id, actor_id`
152
+ const values = (alias: string) => `'${type}-upload:' || ${alias}.id, 'upload',
153
+ COALESCE(${alias}.uploaded_by_login, (SELECT login FROM managed_user WHERE id = ${alias}.uploaded_by)), ${uploadAction(type, alias)},
154
+ (SELECT full_name FROM managed_selected_repo WHERE repo_id = ${alias}.repo_id),
155
+ ${type === 'report' ? `${alias}.id` : 'NULL'}, ${alias}.filename, ${alias}.uploaded_at,
156
+ ${type === 'bundle' ? `${alias}.id` : 'NULL'}, ${alias}.uploaded_by`
157
+ db.exec(`
158
+ CREATE TRIGGER IF NOT EXISTS managed_${type}_activity AFTER INSERT ON managed_${type}
159
+ BEGIN INSERT INTO managed_activity (${columns}) SELECT ${values('NEW')}; END;
160
+ INSERT OR IGNORE INTO managed_activity (${columns}) SELECT ${values('source')} FROM managed_${type} source;
161
+ `)
162
+ }
163
+ }
164
+
165
+ // The creation entry for a stored report or bundle. Shared with the Postgres
166
+ // trigger function; `alias` is the trigger row (NEW) or a backfill alias.
167
+ export function uploadAction(type: string, alias: string): string {
168
+ return type === 'bundle' ? `CASE WHEN ${alias}.provenance = 'build' THEN 'built a bundle' ELSE 'uploaded a bundle' END` : `'uploaded a ${type}'`
169
+ }
170
+
171
+ export function activityMethods(db: ManagedSql): ActivityStore {
172
+ const insert = db.prepare(`INSERT INTO managed_activity (id, kind, actor, action, repo, report_id, report, at, bundle_id, repo_id, repo_directory, actor_id)
173
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
174
+ const admin = activityStatements(db, adminSource)
175
+ const manager = activityStatements(db, managerSource)
176
+ const reports = db.prepare(`SELECT r.id AS reportId, r.filename AS report, p.full_name AS repo
177
+ FROM managed_report r JOIN managed_selected_repo p ON p.repo_id = r.repo_id
178
+ WHERE ${inUserTeamScope('?', 'r')}
179
+ ORDER BY r.uploaded_at DESC, r.id`)
180
+ return {
181
+ async recordActivity(entry, at) {
182
+ await insert.run(randomUUID(), entry.kind, entry.actor, entry.action, entry.repo ?? null, entry.reportId ?? null, entry.report ?? null, at,
183
+ entry.bundleId ?? null, entry.repoId ?? null, entry.repoDirectory ?? null, entry.actorId ?? null)
184
+ },
185
+ async listActivityReports(userId) {
186
+ return (await reports.all(userId)) as Omit<ActivityContext, 'finding'>[]
187
+ },
188
+ async listActivity({ page, limit, kind, query, repo = '', actor = '', contexts, userId }) {
189
+ const stmts = contexts == null ? admin : manager
190
+ const scope = contexts == null ? {} : { contexts: JSON.stringify(contexts), userId: userId ?? '' }
191
+ const params = { ...scope, kind, query, repo, actor }
192
+ const read = async (at: number) => (await stmts.rows.all({ ...params, limit, offset: (at - 1) * limit })) as (ActivityEntry & { total: number | string })[]
193
+ // A page's rows carry the total. Only a page past the last has none to
194
+ // carry it: it is counted, and the last page read in its place.
195
+ let currentPage = page, rows = await read(page)
196
+ let total = rows.length > 0 ? Number(rows[0]!.total) : 0
197
+ if (rows.length === 0 && page > 1) {
198
+ total = Number(((await stmts.count.get(params)) as { total: number | string }).total)
199
+ currentPage = Math.min(page, Math.max(1, Math.ceil(total / limit)))
200
+ if (currentPage !== page) rows = total === 0 ? [] : await read(currentPage)
201
+ }
202
+ const history = rows.map(({ total: _total, ...entry }) => entry)
203
+ const filters: ActivityFilters = { repos: [], users: [] }
204
+ type FacetRow = { facet: string; id: string; userId: string | null; login: string; name: string | null; detail: string | null }
205
+ for (const row of (await stmts.filters.all(scope)) as FacetRow[]) {
206
+ if (row.facet === 'repo') filters.repos.push(row.id)
207
+ else filters.users.push({ id: row.id, userId: row.userId, login: row.login, name: row.name, detail: row.detail })
208
+ }
209
+ return { history, total, page: currentPage, limit, filters }
210
+ },
211
+ }
212
+ }
213
+
214
+ // Both rows and selector choices come from the authorized source. Keep legacy
215
+ // login-only actors separate: a historical login is not proof of user identity.
216
+ // A user shows by their login and name as they are now, as in the selector.
217
+ function activityStatements(db: ManagedSql, source: string) {
218
+ const activity = `WITH events AS (${source}), activity AS (
219
+ SELECT e.id, e.kind, COALESCE(u.login, e.actor) AS actor, e.actorId, u.name AS actorName, e.action,
220
+ e.repo, e.reportId, e.report, e.finding, e.at, COALESCE('user:' || e.actorId, 'legacy:' || e.actor) AS actorKey
221
+ FROM events e LEFT JOIN managed_user u ON u.id = e.actorId
222
+ )`
223
+ const filtered = `${activity} SELECT id, kind, actor, actorId, actorName, action, repo, reportId, report, finding, at FROM activity
224
+ WHERE (:kind = 'all' OR kind = :kind)
225
+ AND (:repo = '' OR repo = :repo) AND (:actor = '' OR actorKey = :actor)
226
+ AND (:query = '' OR instr(lower(coalesce(actor, '') || ' ' || coalesce(actorName, '') || ' ' || action || ' ' ||
227
+ coalesce(repo, '') || ' ' || coalesce(report, '') || ' ' || coalesce(finding, '')), lower(:query)) > 0)`
228
+ // A page's rows each carry the total, so the source is read once for both;
229
+ // the selector choices, repositories then users, once between them.
230
+ return {
231
+ count: db.prepare(`SELECT count(*) AS total FROM (${filtered}) AS filtered`),
232
+ rows: db.prepare(`SELECT filtered.*, count(*) OVER () AS total FROM (${filtered}) AS filtered ORDER BY at DESC,
233
+ CASE WHEN kind = 'triage' THEN CAST(substr(id, instr(id, ':') + 1) AS INTEGER) ELSE 0 END DESC,
234
+ id DESC LIMIT :limit OFFSET :offset`),
235
+ filters: db.prepare(`${activity} SELECT 'repo' AS facet, repo AS id, NULL AS userId, repo AS login, NULL AS name, NULL AS detail,
236
+ repo AS sort, '' AS tiebreak
237
+ FROM (SELECT DISTINCT repo FROM activity WHERE repo IS NOT NULL AND repo <> '') AS repos
238
+ UNION ALL SELECT 'user' AS facet, a.actorKey AS id, a.actorId AS userId, COALESCE(a.actor, a.actorId) AS login, a.actorName AS name,
239
+ CASE WHEN a.actorId IS NULL THEN 'Legacy actor' ELSE NULL END AS detail, COALESCE(a.actor, a.actorId) AS sort, a.actorKey AS tiebreak FROM (
240
+ SELECT actorKey, actorId, actor, actorName, ROW_NUMBER() OVER (PARTITION BY actorKey ORDER BY at DESC, id DESC) AS position
241
+ FROM activity WHERE actorKey IS NOT NULL AND actorKey <> 'legacy:'
242
+ ) a WHERE a.position = 1
243
+ ORDER BY facet, sort, tiebreak`),
244
+ }
245
+ }
246
+
247
+ function migrateActivityScope(db: DatabaseSync): void {
248
+ const columns = new Set((db.prepare('PRAGMA table_info(managed_activity)').all() as { name: string }[]).map(column => column.name))
249
+ const missing = [['bundle_id', 'TEXT'], ['repo_id', 'INTEGER'], ['repo_directory', 'TEXT'], ['actor_id', 'TEXT']].filter(([name]) => !columns.has(name!))
250
+ if (missing.length === 0) return
251
+ sqliteTransaction(db, 'BEGIN', () => {
252
+ for (const [name, type] of missing) db.exec(`ALTER TABLE managed_activity ADD COLUMN ${name} ${type}`)
253
+ if (!columns.has('bundle_id') || !columns.has('actor_id')) {
254
+ db.exec('DROP TRIGGER IF EXISTS managed_report_activity; DROP TRIGGER IF EXISTS managed_bundle_activity;')
255
+ }
256
+ if (!columns.has('bundle_id')) db.exec("UPDATE managed_activity SET bundle_id = substr(id, 15) WHERE id LIKE 'bundle-upload:%'")
257
+ if (!columns.has('actor_id')) {
258
+ // Existing upload targets retain a reliable uploader identity. Do not
259
+ // guess identities from historical logins: names can change or be reused.
260
+ for (const type of ['report', 'bundle']) {
261
+ db.exec(`UPDATE managed_activity SET actor_id = (
262
+ SELECT uploaded_by FROM managed_${type} WHERE id = substr(managed_activity.id, 15)
263
+ ) WHERE id LIKE '${type}-upload:%'`)
264
+ }
265
+ }
266
+ // Legacy deletions/assignments without a durable target/scope remain
267
+ // admin-only; neither filenames nor repository names authorize access.
268
+ })
269
+ }
@@ -0,0 +1,109 @@
1
+ // The commits agents' pull requests brought to a repository's default
2
+ // branch, for its Pulse (repository-pulse.ts commitStats), as the pull
3
+ // requests kept tell them (repository-pulls.ts readPulls: whose each is,
4
+ // and what one merged brought).
5
+ import type { PullList } from './repository-pulls.ts'
6
+ import type { HistoryCommit } from './repository-history.ts'
7
+
8
+ // How long before or after a pull request rebased onto the branch was merged
9
+ // its copies are committed.
10
+ const REBASE_SKEW_MS = 10 * 60_000
11
+
12
+ // The agents' pull requests merged since a year's start, as read so far
13
+ // (agentMerges): the commits each brought, and when it was merged; those
14
+ // rebased onto the branch by their last commit there, when merged, and
15
+ // their commits' subjects, the oldest first (agentCommits); and how far the
16
+ // pull requests are read, as the list tells (repository-pulls.ts PullList:
17
+ // `through`, `reach`, `next`). And of every pull request merged, an agent's
18
+ // or not, its merge commit, when and its number (`pulls`, by which the
19
+ // Commits tab tells those squashed too, http.ts pulseMerges; none of one
20
+ // kept before numbers were), and one rebased so (`pullRebases`), for the
21
+ // commits pushed to the branch directly to be told (directCommits).
22
+ export interface AgentMerges extends Pick<PullList, 'through' | 'reach' | 'next'> { merges: [string, number][]; rebases: Rebase[]
23
+ pulls?: [sha: string, at: number, number?: number][]; pullRebases?: Rebase[] }
24
+ // A pull request rebased onto the branch: its last commit there, when it was
25
+ // merged, its latest commits' subjects, the oldest first, and how many more
26
+ // it had than those read (`more`).
27
+ type Rebase = [sha: string, at: number, subjects: string[], more?: number]
28
+
29
+ // What the pull requests merged since `since` of those read (`list`) brought:
30
+ // an agent's, its merge commit, a squash merge's one commit, and one merged
31
+ // with a merge commit, its own commits too; and every one's merge commit,
32
+ // those rebased by their commits' subjects.
33
+ export function agentMerges(list: PullList, since: number): AgentMerges {
34
+ const merges = new Map<string, number>()
35
+ const [rebases, pulls, pullRebases]: [Rebase[], [string, number, number][], Rebase[]] = [[], [], []]
36
+ for (const { number, merged } of list.rows) {
37
+ if (!merged || merged.at < since) continue
38
+ const { sha, at, subjects, more = 0 } = merged
39
+ const rebase: Rebase | null = subjects ? more > 0 ? [sha, at, subjects, more] : [sha, at, subjects] : null
40
+ pulls.push([sha, at, number])
41
+ if (rebase) pullRebases.push(rebase)
42
+ if (!merged.agent) continue
43
+ for (const oid of [sha, ...merged.own ?? []]) merges.set(oid, at)
44
+ if (rebase) rebases.push(rebase)
45
+ }
46
+ return { merges: [...merges], rebases, through: list.through, ...list.reach === undefined ? {} : { reach: list.reach }, next: list.next, pulls, pullRebases }
47
+ }
48
+
49
+ // Whether two reads of the pull requests merged (agentMerges) bring the
50
+ // same commits, the agents' and every one's (`pulls`, `pullRebases`, which
51
+ // tell those pushed directly), whatever order each read them in.
52
+ export function sameMerges(a: AgentMerges, b: AgentMerges) {
53
+ const sorted = (entries: unknown[] = []) => entries.map(entry => JSON.stringify(entry)).toSorted()
54
+ const brought = (read: AgentMerges) => JSON.stringify([read.merges, read.rebases, read.pulls, read.pullRebases].map(sorted))
55
+ return brought(a) === brought(b)
56
+ }
57
+
58
+ // A commit's subject as GitHub heads its message: whole, or, past what it
59
+ // shows, cut short before an ellipsis.
60
+ const headed = (subject: string, headline: string) => headline.endsWith('…') ? subject.startsWith(headline.slice(0, -1)) : subject === headline
61
+
62
+ // The commits of `commits` (a year's) the agents' pull requests brought
63
+ // (`read`, agentMerges): those it names, and of one rebased, its commits'
64
+ // copies, the last and those below it on their first parents, as long as
65
+ // each one's subject is that of one of its commits older than the last
66
+ // matched, as Commits tells a rebase (repository-squashes.ts squashedPulls),
67
+ // past those of its commits the rebase left none of (an empty one GitHub
68
+ // counted no files of), and, past them all, as many more as it had before
69
+ // its latest read; a squash merge's one commit alone, its subject the pull
70
+ // request's own.
71
+ export function agentCommits(read: AgentMerges, commits: HistoryCommit[]): Set<string> {
72
+ const shas = new Set(read.merges.map(([sha]) => sha))
73
+ const bySha = new Map(commits.map(commit => [commit.sha, commit]))
74
+ for (const [last, merged, subjects, more = 0] of read.rebases) {
75
+ let commit = bySha.get(last)
76
+ let at = subjects.length - 1
77
+ for (; commit && at >= 0; commit = bySha.get(commit.parents[0] ?? '')) {
78
+ const [copied, upTo] = [commit, at]
79
+ const found = subjects.findLastIndex((subject, index) => index <= upTo && headed(copied.subject, subject))
80
+ if (found < 0) break
81
+ shas.add(commit.sha)
82
+ at = found - 1
83
+ }
84
+ // Each of its latest commits read copied, as many as it had before them
85
+ // the commits below, on their first parents, as long as each was
86
+ // committed as it was merged, as a rebase commits its copies: not past
87
+ // its first, its empty ones, which a rebase leaves out, counted too.
88
+ const copiedAsMerged = (when: number | null) => when !== null && Math.abs(when - merged) <= REBASE_SKEW_MS
89
+ for (let rest = at < 0 ? more : 0; commit && rest > 0 && copiedAsMerged(commit.committedAt); rest--, commit = bySha.get(commit.parents[0] ?? '')) {
90
+ shas.add(commit.sha)
91
+ }
92
+ }
93
+ return shas
94
+ }
95
+
96
+ // The commits of `commits` (a year's, from the branch's `head`) pushed to
97
+ // it directly: on its first parents from the head, none a merge, none a
98
+ // pull request brought (`read.pulls`: its merge commit, a squash's one
99
+ // commit, or the copies of one rebased onto it, as agentCommits tells
100
+ // them); those a merge brought from its other parents, not.
101
+ export function directCommits(read: AgentMerges, commits: HistoryCommit[], head: string): Set<string> {
102
+ const pulled = agentCommits({ ...read, merges: (read.pulls ?? []).map(([sha, at]) => [sha, at]), rebases: read.pullRebases ?? [] }, commits)
103
+ const bySha = new Map(commits.map(commit => [commit.sha, commit]))
104
+ const direct = new Set<string>()
105
+ for (let commit = bySha.get(head); commit; commit = bySha.get(commit.parents[0] ?? '')) {
106
+ if (commit.parents.length <= 1 && !pulled.has(commit.sha)) direct.add(commit.sha)
107
+ }
108
+ return direct
109
+ }
@@ -0,0 +1,23 @@
1
+ // The agents the server knows by their GitHub Apps or accounts (the Agents
2
+ // tab's, server-managed/repository-agents.ts, whose marks the Commits tab
3
+ // reads on commits too, repository-history.ts).
4
+ import type { AppAgent, AppAgentMarks } from '../common/managed/agent-tasks.ts'
5
+ import { GITHUB_AGENTS, type GithubAgent } from '../common/managed/github-agents.ts'
6
+
7
+ // The agents known by their GitHub Apps or accounts, beside Claude and
8
+ // Codex: those of GITHUB_AGENTS with branches of their own, in its order
9
+ // (common/managed/github-agents.ts, where each is told, its accounts among
10
+ // it), each its id and name, its avatar (its mark, served by
11
+ // /api/avatar/<avatar>, a GitHub App's, `app-<id>`), the fingerprint it
12
+ // leaves, and its branches' prefix.
13
+ export const APP_AGENTS: readonly (AppAgent & AppAgentMarks)[] = Object.entries<GithubAgent>(GITHUB_AGENTS)
14
+ .flatMap(([id, { name, avatar, prefix, fingerprint }]) => prefix ? [{ id, name, prefix, ...avatar ? { avatar } : {}, ...fingerprint ? { fingerprint } : {} }] : [])
15
+ // The prefixes of the branches agents work on: Claude Code's and Codex's,
16
+ // and the app agents'.
17
+ export const AGENT_BRANCH_PREFIXES = ['claude/', 'codex/', ...APP_AGENTS.map(agent => agent.prefix)]
18
+ // What the marks agents leave on commits are read by, as the history keeps
19
+ // them (repository-history.ts commitMarks), and branches' tips and the
20
+ // commits the app agents' accounts authored (repository-agents.ts): bumped
21
+ // as how they are told changes, so that the Agents tab reads again those
22
+ // kept by older rules.
23
+ export const AGENT_MARKS_READ = 1
@@ -0,0 +1,21 @@
1
+ // Shared avatar cache interface, implemented by storage-stores.ts.
2
+ import type { Buffer } from 'node:buffer'
3
+
4
+ export interface CachedAvatar {
5
+ contentType: string
6
+ bytes: Buffer
7
+ }
8
+
9
+ export interface AvatarStore {
10
+ put(id: string, contentType: string, bytes: Buffer): Promise<void>
11
+ get(id: string): Promise<CachedAvatar | null>
12
+ delete(id: string): Promise<void>
13
+ }
14
+
15
+ // A GitHub account's avatar kept by its numeric id, not a user's: a GitHub
16
+ // App's (`app`) or an account's (`user`, an organization's too). Kept under a
17
+ // key no user's, a v4 UUID, can be (an app's `…-0000-<id>`, an account's
18
+ // `…-0001-<id>`), and fetched from where GitHub serves it.
19
+ export type GithubAvatar = 'app' | 'user'
20
+ export const githubAvatarKey = (kind: GithubAvatar, id: number | string) => `00000000-0000-0000-000${kind === 'app' ? 0 : 1}-${String(id).padStart(12, '0')}`
21
+ export const githubAvatarUrl = (kind: GithubAvatar, id: number | string) => `https://avatars.githubusercontent.com/${kind === 'app' ? 'in' : 'u'}/${id}`
@@ -0,0 +1,26 @@
1
+ // Logical upload-store interfaces shared by disk and Vercel storage.
2
+ import { Buffer } from 'node:buffer'
3
+ import type { Readable } from 'node:stream'
4
+
5
+ export interface OpenedBlob {
6
+ // Remote streams may omit their size; callers then omit Content-Length.
7
+ size: number | null
8
+ stream: Readable
9
+ }
10
+
11
+ export interface BlobStore {
12
+ // Encrypted upload stores return the wrapped data key for the SQL insert.
13
+ put(id: string, bytes: Buffer): Promise<string | null>
14
+ get(id: string): Promise<Buffer | null>
15
+ open(id: string): Promise<OpenedBlob | null>
16
+ delete(id: string): Promise<void>
17
+ }
18
+
19
+ // A blob's bytes whole, its stream closed however the read ends.
20
+ export async function readBytes(stored: OpenedBlob): Promise<Buffer> {
21
+ const parts: Buffer[] = []
22
+ try {
23
+ for await (const part of stored.stream) parts.push(Buffer.from(part))
24
+ return Buffer.concat(parts)
25
+ } finally { stored.stream.destroy() }
26
+ }
@@ -0,0 +1,10 @@
1
+ import { brotliCompress, constants } from 'node:zlib'
2
+ import { promisify } from 'node:util'
3
+ import type { Buffer } from 'node:buffer'
4
+
5
+ const compress = promisify(brotliCompress)
6
+
7
+ // Bundles and cold caches use quality 4; stored reports use quality 9.
8
+ export function encodeBrotli(bytes: Uint8Array, quality = 4): Promise<Buffer> {
9
+ return compress(bytes, { params: { [constants.BROTLI_PARAM_QUALITY]: quality } })
10
+ }
@@ -0,0 +1,176 @@
1
+ import { type Advisory, type CacheStore, type Package, advisories } from '@preventive/upstream/advisories.js'
2
+ import { type Client, HttpError, createClient } from '@preventive/upstream/github.js'
3
+ import { getRepo } from '@preventive/upstream/package.js'
4
+ import { USER_AGENT } from './github-requests.ts'
5
+ import { knownListings } from './known-listings.ts'
6
+ import { lru } from './lru.ts'
7
+ import type { NpmVersionStore } from './npm-packages.ts'
8
+ import { LISTINGS, type UpstreamCacheStore, auditedKeys } from './upstream-cache.ts'
9
+
10
+ export const ADVISORIES_TIMEOUT_MS = 30_000
11
+
12
+ function advisoryGithubClient(token: string | null, signal: AbortSignal): Client {
13
+ const authenticated = createClient({ token, userAgent: USER_AGENT })
14
+ let client = authenticated
15
+ // Published advisories, and where a moved repository is now, remain
16
+ // readable after a token is revoked. Reuse anonymous access for subsequent
17
+ // repositories in this audit as well.
18
+ async function retried<T>(ask: (current: Client) => Promise<T>): Promise<T> {
19
+ const current = client
20
+ try { return await ask(current) } catch (error) {
21
+ if (token === null || current !== authenticated || !(error instanceof HttpError) || error.status !== 401) throw error
22
+ signal.throwIfAborted()
23
+ if (client === authenticated) client = createClient({ token: null, userAgent: USER_AGENT })
24
+ return await ask(client)
25
+ }
26
+ }
27
+ return {
28
+ ...authenticated,
29
+ listRepoAdvisories: options => retried(current => current.listRepoAdvisories(options)),
30
+ getRepo: options => retried(current => current.getRepo(options)),
31
+ }
32
+ }
33
+
34
+ // The managed caller supplies its user's token when available; public shares
35
+ // remain anonymous. Upstream sends this credential only to GitHub and returns
36
+ // published advisories, matching versions across npm, OSV and repository rows:
37
+ // OSV's for npm packages anyone may read too, the malicious packages' records
38
+ // among them, which npm's registry hasn't, each row of malware told so
39
+ // (`malware`); and of a `github` package, OSV's only where github.com serves
40
+ // its repository to anyone (asked with no credentials), so a private one, or
41
+ // one gone, has its own published advisories read alone, as a private npm
42
+ // package's name never reaches OSV either. One the caller says is
43
+ // `internal` is never asked of OSV. `cache` keeps each repository's listing,
44
+ // and the npm packages and github.com's repositories anyone may read
45
+ // (upstream-cache.ts), across audits; `github`, a client of the caller's, asks
46
+ // GitHub in place of one with `githubToken`.
47
+ export async function fetchBundleAdvisories(packages: Package[], signal: AbortSignal,
48
+ { debug = false, repoAdvisories = false, details = false, githubToken = null, github, cache }: {
49
+ debug?: boolean; repoAdvisories?: boolean; details?: boolean; githubToken?: string | null; github?: Client; cache?: CacheStore | undefined
50
+ } = {}): Promise<
51
+ { status: 200; body: Advisory[] } | { status: 502; body: { error: string } }
52
+ > {
53
+ let onAbort: (() => void) | undefined
54
+ try {
55
+ signal.throwIfAborted()
56
+ if (packages.length === 0) return { status: 200, body: [] }
57
+ // Upstream owns each transport's timeout and exposes no cancellation
58
+ // option. Bound the caller's wait for the multi-request audit as well.
59
+ const deadline = new Promise<never>((_resolve, reject) => {
60
+ onAbort = () => reject(signal.reason)
61
+ signal.addEventListener('abort', onAbort, { once: true })
62
+ })
63
+ // npm packages anyone may read are asked of OSV too (upstream's `osv`),
64
+ // for the malicious packages' records npm's registry hasn't: upstream
65
+ // sends OSV only the names npm's registry serves without a token, so a
66
+ // private one's never leaves for OSV, as it never does for Socket; nor a
67
+ // `github` package's github.com serves to no one without credentials. Kept
68
+ // in the caller's store, or without one in upstream's disk cache, where
69
+ // the server set one (auditCache).
70
+ const client = github ?? advisoryGithubClient(githubToken, signal)
71
+ const options = { github: client, repoAdvisories, details, osv: true, ...(cache && { cache }) }
72
+ return { status: 200, body: await Promise.race([advisories(packages, options), deadline]) }
73
+ } catch (error) {
74
+ // Answered as upstream's failure alone: logged, its message, or with
75
+ // `debug` the whole error, but for a request its client gave up on. One
76
+ // past its deadline (aborted with a TimeoutError, as AbortSignal.timeout
77
+ // and the bundle route's timer abort) is the server giving up: logged.
78
+ const cancelled = signal.aborted && (signal.reason as { name?: unknown } | undefined)?.name !== 'TimeoutError'
79
+ if (!cancelled) console.warn('managed: advisories failed:', debug || !(error instanceof Error) ? error : error.message)
80
+ return { status: 502, body: { error: 'upstream-unavailable' } }
81
+ } finally {
82
+ if (onAbort) signal.removeEventListener('abort', onAbort)
83
+ }
84
+ }
85
+
86
+ // advisoryGithubClient with the token `token` gives, asked for once as it is
87
+ // first needed (none where that fails), so that an answer asking GitHub only
88
+ // behind it asks for none before it.
89
+ export function lazyGithubClient(token: () => Promise<string | null>): Client {
90
+ let client: Promise<Client> | undefined
91
+ const ready = () => client ??= token().catch(() => null).then(value => advisoryGithubClient(value, new AbortController().signal))
92
+ return Object.fromEntries(Object.keys(createClient({ token: null })).map(name => [name, async (...args: unknown[]) =>
93
+ await ((await ready()) as unknown as Record<string, (...args: unknown[]) => Promise<unknown>>)[name]!(...args)])) as unknown as Client
94
+ }
95
+
96
+ // As upstream orders advisories: by ecosystem, then package.
97
+ const order = (a: string, b: string) => Number(a > b) - Number(a < b)
98
+ const byPackage = (a: Advisory, b: Advisory) => order(a.ecosystem, b.ecosystem) || order(a.name, b.name)
99
+
100
+ // A bundle's advisories, as fetchBundleAdvisories asks them, with those its
101
+ // packages' repositories publish as known (known-listings.ts): each listing
102
+ // as kept, however old, none asked of GitHub before the answer, nor any
103
+ // package's repository looked up where it names none. With `recheck`, each
104
+ // listing is asked of GitHub first, waited on for half the audit's time at
105
+ // most, and each package's repository looked up where it names none, as
106
+ // upstream's `repoAdvisories` does; those not had by then `unchecked`, and
107
+ // answered as known. GitHub is asked with the token `githubToken` gives.
108
+ export async function fetchKnownBundleAdvisories(packages: Package[], signal: AbortSignal, { recheck = false, details = false, debug = false, githubToken = () => Promise.resolve(null), db, behind }: {
109
+ recheck?: boolean; details?: boolean; debug?: boolean; githubToken?: () => Promise<string | null>; db: UpstreamCacheStore; behind: (work: Promise<unknown>) => void
110
+ }): Promise<{ status: 200; body: Advisory[]; unchecked?: string[] } | { status: 502; body: { error: string } }> {
111
+ const github = lazyGithubClient(githubToken)
112
+ const cache = knownListings(db, signal, { github, behind, keys: auditedKeys(packages, true),
113
+ recheck: recheck ? AbortSignal.any([signal, AbortSignal.timeout(ADVISORIES_TIMEOUT_MS / 2)]) : undefined })
114
+ const named = (pkg: Package) => recheck || pkg.github !== undefined
115
+ const audit = (part: Package[], repoAdvisories: boolean) => fetchBundleAdvisories(part, signal, { debug, repoAdvisories, details, github, cache })
116
+ const [repositories, rest] = await Promise.all([audit(packages.filter(named), true), audit(packages.filter(pkg => !named(pkg)), false)])
117
+ if (repositories.status !== 200) return repositories
118
+ if (rest.status !== 200) return rest
119
+ const unchecked = recheck ? [...cache.unchecked].toSorted() : []
120
+ return { status: 200, body: [...repositories.body, ...rest.body].toSorted(byPackage), ...unchecked.length > 0 ? { unchecked } : {} }
121
+ }
122
+
123
+ // Those `asked` by the GitHub repository each version names, as its document
124
+ // kept (npm-kept.ts) does, as a scan keeps them assessing each: a package's
125
+ // versions naming one repository together, and those naming another apart;
126
+ // and whether any version's document isn't kept, its repository unknown. A
127
+ // version's never changes once published, so each is held here too (null
128
+ // where it names none).
129
+ const versionRepositories = lru<string | null>(50_000)
130
+ export async function versionsRepositories(store: NpmVersionStore, asked: { name: string; versions: string[] }[]): Promise<{ packages: { name: string; versions: string[]; github: string }[]; unknown: boolean }> {
131
+ const versions = asked.flatMap(({ name, versions: each }) => each.map(version => ({ name, version })))
132
+ const unread = versions.filter(({ name, version }) => versionRepositories.get(`${name}@${version}`) === undefined)
133
+ const kept = unread.length > 0 ? await store.readMany?.(unread).catch(() => null) : null
134
+ for (const [key, { json }] of kept ?? []) {
135
+ try { versionRepositories.set(key, getRepo(json).github ?? null) } catch {}
136
+ }
137
+ const named = new Map<string, { name: string; versions: string[]; github: string }>()
138
+ let unknown = false
139
+ for (const { name, version } of versions) {
140
+ const github = versionRepositories.get(`${name}@${version}`)
141
+ unknown ||= github === undefined
142
+ if (!github) continue
143
+ const key = `${name}\0${github.toLowerCase()}`
144
+ const pkg = named.get(key)
145
+ if (pkg) pkg.versions.push(version)
146
+ else named.set(key, { name, versions: [version], github })
147
+ }
148
+ return { packages: [...named.values()], unknown }
149
+ }
150
+
151
+ // What packages' repositories (`github`) publish of their versions, as
152
+ // upstream's `repoAdvisories` tells them, their listings as known
153
+ // (known-listings.ts): upstream asked of those a listing names alone, its
154
+ // registry's and OSV's ones left out. GitHub not waited on, but with `wait`,
155
+ // which asks each listing not fresh first, until `wait` aborts: one not had
156
+ // by then as known. `again` where one wasn't had fresh. A name given with
157
+ // more than one repository, its versions naming each, is asked of each.
158
+ export async function fetchKnownRepositoryAdvisories(packages: (Package & { github: string })[], signal: AbortSignal, { db, github, behind, wait, debug = false }: {
159
+ db: UpstreamCacheStore; github: Client; behind: (work: Promise<unknown>) => void; wait?: AbortSignal | undefined; debug?: boolean
160
+ }): Promise<{ advisories: Advisory[]; again: boolean }> {
161
+ const cache = knownListings(db, signal, { github, behind, keys: auditedKeys(packages, true), wait })
162
+ const listed = await Promise.all(packages.map(pkg => cache.read(LISTINGS, pkg.github.toLowerCase()) as Promise<{ advisories: { ranges?: { ecosystem?: string; name?: string }[] }[] }>))
163
+ const named = packages.filter((pkg, at) => listed[at]!.advisories.some(({ ranges }) => ranges?.some(range => range.ecosystem === pkg.ecosystem && range.name === pkg.name)))
164
+ // Upstream takes a name with one repository an audit: one with more in as many.
165
+ const audits: (typeof named)[] = [], seen = new Map<string, number>()
166
+ for (const pkg of named) {
167
+ const key = `${pkg.ecosystem}\0${pkg.name}`
168
+ const at = seen.get(key) ?? 0
169
+ seen.set(key, at + 1)
170
+ ;(audits[at] ??= []).push(pkg)
171
+ }
172
+ const audited = await Promise.all(audits.map(part => fetchBundleAdvisories(part, signal, { debug, repoAdvisories: true, github, cache })))
173
+ const failed = audited.find(each => each.status !== 200)
174
+ if (failed) throw new Error((failed.body as { error: string }).error)
175
+ return { advisories: audited.flatMap(each => (each.body as Advisory[]).filter(row => row.source === 'repository')), again: cache.unchecked.size > 0 }
176
+ }