@preventive/triage 1.0.0-alpha.6 → 1.0.0-alpha.61

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 (409) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +17 -0
  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 +3 -0
  13. package/common/bundle-compare-diff.js +376 -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-metadata.d.ts +15 -0
  20. package/common/bundle-metadata.js +226 -0
  21. package/common/bundle-pkg-of.d.ts +1 -0
  22. package/common/bundle-pkg-of.js +90 -0
  23. package/common/bundle-reasons.d.ts +2 -0
  24. package/common/bundle-reasons.js +21 -0
  25. package/common/bundle-source-links.d.ts +6 -0
  26. package/common/bundle-source-links.js +216 -0
  27. package/common/bundle-sourcemap.d.ts +10 -0
  28. package/common/bundle-sourcemap.js +100 -0
  29. package/common/bundle-sources.d.ts +7 -0
  30. package/common/bundle-sources.js +333 -0
  31. package/common/bundle-stats.js +41 -0
  32. package/common/bundle-tabs.js +1 -0
  33. package/common/code-language.js +65 -0
  34. package/common/default-scan-models.ts +36 -0
  35. package/common/dependency-reviews.d.ts +18 -0
  36. package/common/dependency-reviews.js +64 -0
  37. package/common/finding-duplicates.js +58 -0
  38. package/common/finding-filters.js +274 -0
  39. package/common/finding-id.js +47 -0
  40. package/common/finding-repo.d.ts +5 -0
  41. package/common/finding-repo.js +67 -0
  42. package/common/github-issue-labels.d.ts +1 -0
  43. package/common/github-issue-labels.js +11 -0
  44. package/common/github-pr.ts +56 -0
  45. package/common/gzip.js +59 -0
  46. package/common/line-diff.d.ts +8 -0
  47. package/common/line-diff.js +57 -0
  48. package/common/linked-workspace-groups.js +63 -0
  49. package/common/managed/agent-tasks.ts +292 -0
  50. package/common/managed/comments.ts +43 -0
  51. package/common/managed/finding-detail.d.ts +5 -0
  52. package/common/managed/finding-detail.js +75 -0
  53. package/common/managed/finding-values.d.ts +2 -0
  54. package/common/managed/finding-values.js +44 -0
  55. package/common/managed/github-agents.ts +114 -0
  56. package/common/managed/github-logins.ts +49 -0
  57. package/common/managed/lite-name.d.ts +2 -0
  58. package/common/managed/lite-name.js +20 -0
  59. package/common/managed/npm-packages.d.ts +7 -0
  60. package/common/managed/npm-packages.js +51 -0
  61. package/common/managed/permissions.ts +31 -0
  62. package/common/managed/report-content.ts +72 -0
  63. package/common/managed/report-filter.ts +120 -0
  64. package/common/managed/repository-alias.ts +65 -0
  65. package/common/managed/roles.ts +35 -0
  66. package/common/managed/routes.d.ts +2 -0
  67. package/common/managed/routes.js +363 -0
  68. package/common/managed/scan-models.ts +6 -0
  69. package/common/managed/team-app.d.ts +15 -0
  70. package/common/managed/team-app.js +100 -0
  71. package/common/managed/team-filters.js +26 -0
  72. package/common/managed/triage.ts +83 -0
  73. package/common/managed/upload-seal.ts +126 -0
  74. package/common/pretty-print.d.ts +5 -0
  75. package/common/pretty-print.js +24 -0
  76. package/common/repo-commit.d.ts +4 -0
  77. package/common/repo-commit.js +30 -0
  78. package/common/revalidation-conflicts.js +48 -0
  79. package/common/revalidation-input-groups.js +56 -0
  80. package/common/save-error-reason.ts +20 -7
  81. package/common/scan-server.ts +13 -0
  82. package/common/security-links.d.ts +5 -0
  83. package/common/security-links.js +33 -0
  84. package/common/server-info.ts +46 -0
  85. package/common/utf8.d.ts +3 -0
  86. package/common/utf8.js +45 -0
  87. package/common/workspace-app.js +71 -0
  88. package/common/workspace-groups.js +176 -0
  89. package/out/activity.js +4 -0
  90. package/out/brotli-fallback.js +3 -3
  91. package/out/chunk-2XUEZHIP.js +28 -0
  92. package/out/chunk-4EMM6UCD.js +1 -0
  93. package/out/chunk-4ISO5F7Y.js +7 -0
  94. package/out/chunk-4XIH7YTX.js +1 -0
  95. package/out/chunk-6CCSTJWB.js +1 -0
  96. package/out/chunk-74AEKRES.js +10 -0
  97. package/out/chunk-7BKKYVWR.js +7 -0
  98. package/out/chunk-7C7DWL7I.js +1 -0
  99. package/out/chunk-B3FNMHOE.js +1 -0
  100. package/out/chunk-BNH52UHC.js +2 -0
  101. package/out/chunk-BRO77PQY.js +42 -0
  102. package/out/chunk-C4Z6ZBXV.js +10 -0
  103. package/out/chunk-DEVAORP2.js +1 -0
  104. package/out/chunk-E3LFSUDJ.js +9 -0
  105. package/out/chunk-G3LY2FV4.js +1 -0
  106. package/out/chunk-GO7FT4OD.js +1 -0
  107. package/out/chunk-GRGIZOTP.js +4 -0
  108. package/out/chunk-HAZKDK4M.js +4 -0
  109. package/out/chunk-HOB3YPS5.js +1 -0
  110. package/out/chunk-IYPY47MC.js +1 -0
  111. package/out/chunk-IZ6MYRYB.js +3 -0
  112. package/out/chunk-J2FWBXFV.js +1 -0
  113. package/out/chunk-JCIIBLKR.js +1 -0
  114. package/out/chunk-JFL7WLRV.js +1 -0
  115. package/out/chunk-JJK5OZG2.js +15 -0
  116. package/out/chunk-JMG5DXII.js +2 -0
  117. package/out/chunk-JOXLZXMI.js +1 -0
  118. package/out/chunk-M37X4LCF.js +14 -0
  119. package/out/chunk-M3Y6SLC4.js +1 -0
  120. package/out/chunk-NRPC74AM.js +1 -0
  121. package/out/chunk-NXATZJQ2.js +1 -0
  122. package/out/chunk-OFZYEWBH.js +244 -0
  123. package/out/chunk-OIERSXON.js +1 -0
  124. package/out/chunk-OOJM4CTU.js +1 -0
  125. package/out/chunk-PAD2JHZT.js +1 -0
  126. package/out/chunk-PNHBZGDD.js +1 -0
  127. package/out/chunk-PTFQKLKO.js +1 -0
  128. package/out/chunk-PWFUOLZK.js +17 -0
  129. package/out/chunk-PXK7EU4V.js +1 -0
  130. package/out/chunk-QCOGVL37.js +52 -0
  131. package/out/chunk-QMVOEBWC.js +13 -0
  132. package/out/chunk-QRKFPLA4.js +80 -0
  133. package/out/chunk-R3NZFXVR.js +1 -0
  134. package/out/chunk-R5O6FAW4.js +2 -0
  135. package/out/chunk-RRBIJL2B.js +1 -0
  136. package/out/chunk-SYXT3SFP.js +2 -0
  137. package/out/chunk-TOXMUOIW.js +5 -0
  138. package/out/chunk-TUII34K2.js +1 -0
  139. package/out/chunk-UCP3JRE2.js +1 -0
  140. package/out/chunk-VFWMQ3LG.js +2 -0
  141. package/out/chunk-VRX2APNA.js +9 -0
  142. package/out/chunk-W3QFV4SP.js +3 -0
  143. package/out/chunk-W6VOKW2N.js +12 -0
  144. package/out/chunk-WCPJDAYA.js +10 -0
  145. package/out/chunk-WMFDQS2L.js +11 -0
  146. package/out/chunk-WREU7JAG.js +1 -0
  147. package/out/chunk-Y5ZHFNBD.js +2 -0
  148. package/out/chunk-YF4M5OCI.js +1 -0
  149. package/out/chunk-Z667U2UJ.js +1 -0
  150. package/out/chunk-ZQHLECTI.js +1 -0
  151. package/out/chunk-ZQNEWVGG.js +1 -0
  152. package/out/client-managed-import.js +4 -0
  153. package/out/client-managed.js +34 -0
  154. package/out/client-sync.js +11 -17
  155. package/out/compare.js +40 -0
  156. package/out/dialogs.js +40 -0
  157. package/out/github-issue-authorized.html +3 -0
  158. package/out/github-issue-authorized.js +1 -0
  159. package/out/graph.js +19 -4
  160. package/out/index.html +106 -8
  161. package/out/prism.js +14 -10
  162. package/out/scan.js +2 -0
  163. package/out/stasis.svg +20 -0
  164. package/out/terminal.js +366 -39
  165. package/out/view.css +1 -1
  166. package/out/view.js +19 -144
  167. package/package.json +383 -63
  168. package/risk/actions/findings.js +161 -0
  169. package/risk/actions/resolve.js +250 -0
  170. package/risk/actions/scripts/commands.js +182 -0
  171. package/risk/actions/scripts/grade.js +113 -0
  172. package/risk/actions/scripts/packages.js +123 -0
  173. package/risk/actions/scripts/shell.js +169 -0
  174. package/risk/actions/uses.js +76 -0
  175. package/risk/actions/workflow.js +110 -0
  176. package/risk/files/characters.js +196 -0
  177. package/risk/files/hosts.js +205 -0
  178. package/risk/files/readability.js +177 -0
  179. package/risk/files/runs-code.js +615 -0
  180. package/risk/files/script.js +118 -0
  181. package/risk/files/stamps.js +47 -0
  182. package/risk/index.d.ts +272 -0
  183. package/risk/index.js +11 -0
  184. package/risk/npm/assess.js +285 -0
  185. package/risk/npm/combined.js +68 -0
  186. package/risk/npm/compare.js +257 -0
  187. package/risk/npm/dependencies.js +172 -0
  188. package/risk/npm/diff.js +79 -0
  189. package/risk/npm/downloads.js +84 -0
  190. package/risk/npm/files.js +445 -0
  191. package/risk/npm/held.js +63 -0
  192. package/risk/npm/install-scripts.js +34 -0
  193. package/risk/npm/malware.js +38 -0
  194. package/risk/npm/manifest.js +65 -0
  195. package/risk/npm/new-dependency.js +60 -0
  196. package/risk/npm/old-version.js +108 -0
  197. package/risk/npm/registry.js +390 -0
  198. package/risk/npm/release.js +85 -0
  199. package/risk/npm/score.js +59 -0
  200. package/risk/npm/specs.js +124 -0
  201. package/risk/npm/tarball.js +96 -0
  202. package/server-common/database-config.ts +16 -0
  203. package/server-common/initialize.ts +18 -0
  204. package/server-common/npm-advisories.ts +101 -0
  205. package/{server → server-common}/origin.ts +5 -5
  206. package/server-common/reap.ts +48 -0
  207. package/server-common/scan-config.ts +19 -0
  208. package/server-common/standalone.ts +29 -0
  209. package/server-common/storage-crypto.ts +182 -0
  210. package/server-common/storage-log.ts +38 -0
  211. package/server-common/vercel-blob.ts +103 -0
  212. package/server-e2e/app.ts +487 -0
  213. package/{server → server-e2e}/bus-receiver.ts +2 -1
  214. package/{server → server-e2e}/cli.js +9 -4
  215. package/{server → server-e2e}/config.ts +50 -42
  216. package/{server → server-e2e}/db-neon.ts +2 -2
  217. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  218. package/{server → server-e2e}/db-stmt.ts +2 -2
  219. package/{server → server-e2e}/db.ts +7 -7
  220. package/{server → server-e2e}/http.ts +44 -13
  221. package/{server → server-e2e}/hub.ts +40 -9
  222. package/server-e2e/index.ts +17 -0
  223. package/server-e2e/lifecycle.ts +95 -0
  224. package/{server → server-e2e}/neon-driver.ts +2 -2
  225. package/{server → server-e2e}/npm-proxy.ts +12 -145
  226. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  227. package/{server → server-e2e}/objstore/blob.ts +1 -1
  228. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  229. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  230. package/{server → server-e2e}/objstore/init.ts +19 -27
  231. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  232. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  233. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  234. package/{server → server-e2e}/objstore/rest.ts +3 -3
  235. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  236. package/{server → server-e2e}/objstore/store.ts +7 -7
  237. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  238. package/{server → server-e2e}/pubsub.ts +12 -9
  239. package/{server → server-e2e}/sign.ts +4 -4
  240. package/{server → server-e2e}/sse-server.ts +60 -33
  241. package/{server → server-e2e}/static.ts +31 -21
  242. package/{server → server-e2e}/sync-handlers.ts +64 -30
  243. package/{server → server-e2e}/ws-server.ts +20 -9
  244. package/server-managed/activity.ts +238 -0
  245. package/server-managed/agent-merges.ts +109 -0
  246. package/server-managed/app-agents.ts +23 -0
  247. package/server-managed/avatar-store.ts +13 -0
  248. package/server-managed/blob-store.ts +26 -0
  249. package/server-managed/brotli.ts +10 -0
  250. package/server-managed/bundle-advisories.ts +103 -0
  251. package/server-managed/bundle-advisory-inventory.ts +77 -0
  252. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  253. package/server-managed/bundle-build-diagnostics.js +23 -0
  254. package/server-managed/bundle-build-leases.ts +41 -0
  255. package/server-managed/bundle-build-worker.js +238 -0
  256. package/server-managed/bundle-build.ts +240 -0
  257. package/server-managed/bundle-cache.ts +199 -0
  258. package/server-managed/bundle-catalog.ts +29 -0
  259. package/server-managed/bundle-commits.ts +133 -0
  260. package/server-managed/bundle-dependency-reviews.ts +68 -0
  261. package/server-managed/bundle-store.ts +24 -0
  262. package/server-managed/bundle-summary-cache.ts +139 -0
  263. package/server-managed/bundle-validation.ts +33 -0
  264. package/server-managed/bundle.ts +119 -0
  265. package/server-managed/cache-storage.ts +20 -0
  266. package/server-managed/cli.js +21 -0
  267. package/server-managed/combined.ts +43 -0
  268. package/server-managed/comments.ts +138 -0
  269. package/server-managed/commit-coauthors.ts +105 -0
  270. package/server-managed/commit-lockfiles.ts +77 -0
  271. package/server-managed/comparison.ts +50 -0
  272. package/server-managed/config.ts +163 -0
  273. package/server-managed/content-access.ts +15 -0
  274. package/server-managed/crypto.ts +25 -0
  275. package/server-managed/db-methods.ts +1877 -0
  276. package/server-managed/db-neon.ts +388 -0
  277. package/server-managed/db-schema.ts +253 -0
  278. package/server-managed/db-table-names.ts +22 -0
  279. package/server-managed/db.ts +146 -0
  280. package/server-managed/dependabot-access.ts +61 -0
  281. package/server-managed/dependabot-alerts.ts +180 -0
  282. package/server-managed/dependency-review-comments.ts +92 -0
  283. package/server-managed/dependency-reviews.ts +363 -0
  284. package/server-managed/github-accounts.ts +59 -0
  285. package/server-managed/github-actions.ts +71 -0
  286. package/server-managed/github-app.ts +347 -0
  287. package/server-managed/github-errors.ts +70 -0
  288. package/server-managed/github-graphql.ts +42 -0
  289. package/server-managed/github-issue-links.ts +264 -0
  290. package/server-managed/github-issue-oauth.ts +30 -0
  291. package/server-managed/github-issues.ts +157 -0
  292. package/server-managed/github-link-oauth.ts +56 -0
  293. package/server-managed/github-links.ts +204 -0
  294. package/server-managed/github-metadata.ts +213 -0
  295. package/server-managed/github-oauth.ts +264 -0
  296. package/server-managed/github-pulls.ts +257 -0
  297. package/server-managed/github-requests.ts +179 -0
  298. package/server-managed/github-users.ts +30 -0
  299. package/server-managed/github-values.ts +26 -0
  300. package/server-managed/history-windows.ts +172 -0
  301. package/server-managed/http-response.ts +76 -0
  302. package/server-managed/http.ts +5796 -0
  303. package/server-managed/import-triage.ts +51 -0
  304. package/server-managed/index.ts +204 -0
  305. package/server-managed/kept-briefly.ts +37 -0
  306. package/server-managed/kept.ts +28 -0
  307. package/server-managed/link-reports.ts +149 -0
  308. package/server-managed/listed-activity.ts +39 -0
  309. package/server-managed/locked-packages.ts +152 -0
  310. package/server-managed/lockfile-scope.ts +49 -0
  311. package/server-managed/lru.ts +30 -0
  312. package/server-managed/managed-issues.ts +92 -0
  313. package/server-managed/management-catalog.ts +45 -0
  314. package/server-managed/management.ts +110 -0
  315. package/server-managed/npm-delta-worker.js +23 -0
  316. package/server-managed/npm-delta.ts +159 -0
  317. package/server-managed/npm-insights.ts +455 -0
  318. package/server-managed/npm-kept.ts +234 -0
  319. package/server-managed/npm-loads.ts +259 -0
  320. package/server-managed/npm-manifest.ts +117 -0
  321. package/server-managed/npm-packages.ts +462 -0
  322. package/server-managed/npm-patch.ts +317 -0
  323. package/server-managed/npm-provenance.ts +127 -0
  324. package/server-managed/npm-risk.ts +287 -0
  325. package/server-managed/object-storage-disk.ts +147 -0
  326. package/server-managed/object-storage-vercel.ts +71 -0
  327. package/server-managed/object-storage.ts +82 -0
  328. package/server-managed/package-entry-points.ts +79 -0
  329. package/server-managed/pretty-print.ts +425 -0
  330. package/server-managed/public-workspace.ts +242 -0
  331. package/server-managed/pull-comment-reviews.ts +161 -0
  332. package/server-managed/pull-dependencies.ts +340 -0
  333. package/server-managed/pull-dependency-reviews.ts +327 -0
  334. package/server-managed/pull-reviews.ts +202 -0
  335. package/server-managed/queue.ts +53 -0
  336. package/server-managed/release-commits.ts +85 -0
  337. package/server-managed/rename-diff-worker.js +26 -0
  338. package/server-managed/rename-diff.ts +236 -0
  339. package/server-managed/repo-path.ts +21 -0
  340. package/server-managed/report-migration.ts +32 -0
  341. package/server-managed/report-query.ts +10 -0
  342. package/server-managed/report-response.ts +16 -0
  343. package/server-managed/report-sources.ts +181 -0
  344. package/server-managed/report-store.ts +77 -0
  345. package/server-managed/repository-actions.ts +220 -0
  346. package/server-managed/repository-agents.ts +422 -0
  347. package/server-managed/repository-aliases.ts +85 -0
  348. package/server-managed/repository-browser.ts +303 -0
  349. package/server-managed/repository-changes.ts +280 -0
  350. package/server-managed/repository-code.ts +215 -0
  351. package/server-managed/repository-dependency-reviews.ts +159 -0
  352. package/server-managed/repository-discovery.ts +83 -0
  353. package/server-managed/repository-history.ts +428 -0
  354. package/server-managed/repository-issues.ts +224 -0
  355. package/server-managed/repository-policy.ts +27 -0
  356. package/server-managed/repository-pulls.ts +207 -0
  357. package/server-managed/repository-pulse.ts +477 -0
  358. package/server-managed/repository-risk-assess.ts +108 -0
  359. package/server-managed/repository-risk-audit.ts +78 -0
  360. package/server-managed/repository-risk-read.ts +170 -0
  361. package/server-managed/repository-risk.ts +483 -0
  362. package/server-managed/repository-squashes.ts +160 -0
  363. package/server-managed/repository-stamp.ts +41 -0
  364. package/server-managed/request-timing.ts +63 -0
  365. package/server-managed/reviewed-dependencies.ts +149 -0
  366. package/server-managed/revisions.ts +35 -0
  367. package/server-managed/scan-downloads.ts +87 -0
  368. package/server-managed/session.ts +132 -0
  369. package/server-managed/slugs.ts +38 -0
  370. package/server-managed/solidity-entry-points.ts +71 -0
  371. package/server-managed/sql-postgres.ts +34 -0
  372. package/server-managed/sql.ts +107 -0
  373. package/server-managed/stasis-config.ts +55 -0
  374. package/server-managed/static.ts +28 -0
  375. package/server-managed/storage-command.ts +16 -0
  376. package/server-managed/storage-db.ts +183 -0
  377. package/server-managed/storage-encryption.ts +288 -0
  378. package/server-managed/storage-maintenance.ts +259 -0
  379. package/server-managed/storage-payload.ts +121 -0
  380. package/server-managed/storage-stores.ts +91 -0
  381. package/server-managed/storage.ts +82 -0
  382. package/server-managed/team-app-summaries.ts +54 -0
  383. package/server-managed/team-app.ts +154 -0
  384. package/server-managed/team-catalog.ts +7 -0
  385. package/server-managed/team-feed.ts +180 -0
  386. package/server-managed/team-npm-scopes.ts +103 -0
  387. package/server-managed/team-reports.ts +351 -0
  388. package/server-managed/triage-response.ts +16 -0
  389. package/server-managed/type-only-proof.js +108 -0
  390. package/server-managed/type-only-worker.js +31 -0
  391. package/server-managed/type-only.ts +115 -0
  392. package/server-managed/uploads.ts +106 -0
  393. package/server-managed/upstream-cache.ts +250 -0
  394. package/server-managed/view-as.ts +58 -0
  395. package/server-managed/worker-turns.ts +76 -0
  396. package/server-managed/workspace-shares.ts +170 -0
  397. package/server.ts +70 -0
  398. package/server/index.ts +0 -480
  399. package/server/lifecycle.ts +0 -208
  400. /package/{LICENSE → LICENSE-MIT} +0 -0
  401. /package/{server → server-e2e}/auth.ts +0 -0
  402. /package/{server → server-e2e}/config.example.json +0 -0
  403. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  404. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  405. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  406. /package/{server → server-e2e}/peer.ts +0 -0
  407. /package/{server → server-e2e}/sse-session.ts +0 -0
  408. /package/{server → server-e2e}/util.ts +0 -0
  409. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,483 @@
1
+ // Every connected repository's npm packages, as its lockfiles lock them, each
2
+ // assessed by risk (npm-risk.ts), for admins: GET /api/admin/repositories/risk
3
+ // answers a line at a time as each is found and assessed, and stops once its
4
+ // reader leaves (`signal`).
5
+ //
6
+ // A repository's lockfiles are listed at its default branch's head by
7
+ // @preventive/upstream's findRepoLockfiles; of them, those of npm's ecosystem
8
+ // that @preventive/lockfile reads (package-lock.json and npm-shrinkwrap.json
9
+ // of `lockfileVersion: 3`, pnpm-lock.yaml of pnpm 9 to 12, and Yarn 1's
10
+ // yarn.lock) are read for their packages. A package from npm's registry is
11
+ // assessed once a scan, however many lockfiles lock it; one from another
12
+ // host with an integrity, such as a company's mirror of npm's, as npm's
13
+ // package of its name and version where npm's integrity is among it; one
14
+ // from elsewhere (git, a tarball with no integrity, a file) is listed, not
15
+ // assessed. Repositories are read a few at a time (READ_AHEAD), each told in
16
+ // turn, as GitHub's limits are the caller's; packages are assessed meanwhile, as many at a time as npm-risk.ts
17
+ // makes spare assessments, those only devDependencies need in every lockfile
18
+ // that locks them (LockedPackage `dev`) once all the rest are, as an install
19
+ // of no devDependencies leaves them out. A lockfile's packages of npm's
20
+ // registry or a mirror are asked of npm's advisories all at once, as `npm
21
+ // audit` asks, each advisory told with whether it is of malware (upstream's
22
+ // `malware`), which alone is a supply chain's risk; the rest are
23
+ // vulnerabilities, told beside. A repository's Dependabot alerts of npm's, open or dismissed,
24
+ // are told once its lockfiles' advisories are, each with the versions its
25
+ // lockfile locks that it covers, for the page to blend them into npm's; one
26
+ // whose alerts couldn't be had tells why, and the scan goes on. Its GitHub
27
+ // Actions are told once its lockfiles are, the references they make
28
+ // resolved as the scan goes on (repository-actions.ts).
29
+ import type { LockfileFormat } from '@preventive/upstream/github.js'
30
+ import { type ActionsSource, type Severity, npmMalwareAdvisory } from '../risk/index.js'
31
+ import { isNpmPackageName, isNpmPackageSpec } from '../common/managed/npm-packages.js'
32
+ import { type Lru, lru } from './lru.ts'
33
+ import type { KeptStore } from './npm-kept.ts'
34
+ import { MAX_SPARE_ASSESSMENTS } from './npm-risk.ts'
35
+ import type { LockedPackage } from './locked-packages.ts'
36
+ import { type Queue, inTurns, queue } from './queue.ts'
37
+ import { type DownloadsSource, readyingDownloads } from './scan-downloads.ts'
38
+ import { type AssessedPackage, type AssessingSource, BUSY_RETRIES, BUSY_WAIT_MS, RISK_KEPT_MS, type RiskFailure, assessPackage, failureOf, isBusy } from './repository-risk-assess.ts'
39
+ import { type AdvisoryRow, type Audit, type AuditSource, auditLockfiles } from './repository-risk-audit.ts'
40
+ import { type DependabotRead, type ListedLockfile, type LockfileRead, type OpenedRepository, type RepositoryFailure, type RepositoryRead, SCAN_READ_KEPT_MS,
41
+ readRepository } from './repository-risk-read.ts'
42
+ import { type DependabotAlert, alertVersions } from './dependabot-alerts.ts'
43
+ import { type ActionAnswers, type ActionLine, type ActionRef, type WorkflowLine, type WorkflowsLine, type WorkflowsRead, actionsLines, answerWeight,
44
+ lockedNames, resolvingActions } from './repository-actions.ts'
45
+
46
+ export { RISK_KEPT_MS, highestSeverity } from './repository-risk-assess.ts'
47
+ export { SCAN_READ_KEPT_MS } from './repository-risk-read.ts'
48
+
49
+ // A repository to read: where `paths` are given, a team's directories in it,
50
+ // only the lockfiles in them or above them, as a workspace's root lockfile
51
+ // locks them too.
52
+ export interface RepositoryRiskRepo { repoId: number; fullName: string; paths?: readonly string[] }
53
+
54
+ interface RepositoryRiskSource<R extends RepositoryRiskRepo> extends AuditSource, AssessingSource {
55
+ repos(): Promise<R[]>
56
+ open(repo: R): Promise<OpenedRepository>
57
+ // Whether a team lists a package's scope, its own packages.
58
+ teamScoped(name: string): Promise<boolean>
59
+ // Where risk lines are kept beyond this instance, as RiskCaches keeps them
60
+ // in it (npm-kept.ts riskLineStore, the database's).
61
+ risks?: KeptStore<RiskLine>
62
+ // Where a repository's lockfiles as listed at a commit, and a lockfile's
63
+ // packages by its blob, are kept beyond this instance, as RiskCaches keeps
64
+ // them in it (npm-kept.ts scanReadStore, the database's), each read for
65
+ // SCAN_READ_KEPT_MS: a scan answered in parts (`partMs`) goes on from
66
+ // where the last stopped on whichever instance answers the next.
67
+ listings?: KeptStore<ListedLockfile[]>
68
+ lockfiles?: KeptStore<LockfileRead>
69
+ // Where a scan answered in parts keeps, from one part to the next, the
70
+ // repositories it told whole (`partMs`): the next tells none of them again,
71
+ // nor asks GitHub of them, but looks up their packages' risks as their
72
+ // lockfiles are kept (`lockfiles`), as the reader has the rest already.
73
+ progress?: { read(): Promise<{ at: number; value: ScanProgress } | null>; write(progress: ScanProgress): Promise<void> } | undefined
74
+ // Readies npm's downloads of packages before they are assessed
75
+ // (scan-downloads.ts); without it, each assessment asks its own.
76
+ downloads?: DownloadsSource
77
+ // GitHub as references are resolved with; none without it.
78
+ actions?: ActionsSource
79
+ // Where Actions' files read and references resolved are kept.
80
+ actionFiles?: KeptStore<WorkflowsRead>
81
+ actionLines?: KeptStore<ActionLine>
82
+ }
83
+
84
+ // A Dependabot alert as a scan tells it: with the versions of its package
85
+ // the lockfile it is of locks that it covers, none where it is of none read
86
+ // (a package.json, bun's lockfile), and whether it is of malware, by the rule
87
+ // upstream tells an advisory's by (risk's npmMalwareAdvisory).
88
+ type DependabotAlertRow = DependabotAlert & { versions: string[]; malware: boolean }
89
+
90
+ // A risk line is of npm's package of its name and version, or, with an
91
+ // `integrity`, of a mirror's that its lockfiles hold to it; its `score` risk's
92
+ // of it, out of 100 (assessNpm `score`, risk/npm/score.js).
93
+ export type RepositoryRiskLine =
94
+ | { type: 'repos'; repos: { id: number; fullName: string }[] }
95
+ | ({ type: 'repo'; id: number } & ({ commit: string; lockfiles: { path: string; format: LockfileFormat }[] } | RiskFailure))
96
+ | ({ type: 'lockfile'; repo: number; path: string; format: LockfileFormat } & ({ packages: LockedPackage[] } | RiskFailure))
97
+ | ({ type: 'risk'; name: string; version: string; integrity?: string; stale?: { assessedAt: number } }
98
+ & ({ published: string | null; severity: Severity | null; score: number; findings: { id: string; severity: Severity; takenDown?: true }[] } | RiskFailure))
99
+ | ({ type: 'advisories'; repo: number; path: string } & ({ advisories: AdvisoryRow[] } | RiskFailure))
100
+ | ({ type: 'dependabot'; repo: number } & ({ alerts: DependabotAlertRow[] } | RiskFailure))
101
+ | WorkflowsLine | WorkflowLine | ActionLine
102
+ | { type: 'done' }
103
+ // The scan stopped for its part's time (repositoryRiskLines `partMs`), what
104
+ // it told kept: to be asked again, from where it stopped.
105
+ | { type: 'continue' }
106
+
107
+ // The repositories a scan answered in parts told whole by a part's end: each
108
+ // by its id, its name and a team's directories in it then, and its
109
+ // lockfiles' keys (`${format}\0${sha}`) of those read, and the references
110
+ // its Actions make, to resolve.
111
+ export interface ScanProgress { repos: ToldRepository[] }
112
+ interface ToldRepository { id: number; name: string; paths: readonly string[] | null; lockfiles: string[]; actions?: ActionRef[] }
113
+
114
+ export type RiskLine = Extract<RepositoryRiskLine, { type: 'risk' }>
115
+
116
+ // What scans keep between them, in this instance's memory: a repository's
117
+ // lockfiles as listed at a commit, and a lockfile's packages by its blob,
118
+ // neither of which changes; a lockfile's advisories, asked again after
119
+ // RISK_KEPT_MS, as npm publishes advisories; and a package's risk line,
120
+ // told stale after RISK_KEPT_MS and assessed again, as risk tells again what
121
+ // of a package changes in time (a deprecation, its age, its downloads). A
122
+ // lockfile's, and its packages' lines, are told only once access to its
123
+ // repository is checked as when it was read.
124
+ interface RiskCaches {
125
+ listings: Lru<ListedLockfile[]>
126
+ lockfiles: Lru<LockfileRead>
127
+ risks: Lru<{ at: number; line: RiskLine }>
128
+ advisories: Lru<{ at: number; audit: Audit }>
129
+ actionFiles: Lru<WorkflowsRead>
130
+ actions: Lru<{ at: number; line: ActionLine }>
131
+ actionAnswers: ActionAnswers
132
+ }
133
+ export const riskCaches = (): RiskCaches => ({
134
+ listings: lru(1000),
135
+ // By the packages they hold, a few hundred bytes each.
136
+ lockfiles: lru(200_000, read => 'packages' in read ? read.packages.length + 1 : 1),
137
+ risks: lru(50_000),
138
+ advisories: lru(50_000, kept => Array.isArray(kept.audit) ? kept.audit.length + 1 : 1),
139
+ // By their text, a kilobyte at a time.
140
+ actionFiles: lru(64 * 1024, read => 'files' in read ? read.files.reduce((sum, file) => sum + ('text' in file ? Math.ceil(file.text.length / 1024) : 1), 1) : 1),
141
+ actions: lru(10_000),
142
+ // What GitHub answered of public repositories' actions, by answerWeight.
143
+ actionAnswers: lru(200_000, answerWeight),
144
+ })
145
+ // How many repositories are read at once (repository-risk-read.ts), ahead of
146
+ // the one told: each asks GitHub one thing after another (opening it, and
147
+ // its head) even where all else is kept.
148
+ const READ_AHEAD = 6
149
+ // How many lockfiles' advisories are asked of npm at once, those of the
150
+ // repositories read ahead as they are read, each told in its turn.
151
+ const AUDITS_AT_ONCE = 4
152
+ // How long a part's progress, written as it ends (`progress`), is waited on.
153
+ const PROGRESS_WRITE_MS = 5000
154
+ // How many kept risk lines are read of the source's `risks` at once.
155
+ const KEPT_READ = 500
156
+ const shared = riskCaches()
157
+
158
+ interface Scan {
159
+ source: RepositoryRiskSource<RepositoryRiskRepo>
160
+ caches: RiskCaches
161
+ signal: AbortSignal
162
+ lines: Queue<RepositoryRiskLine>
163
+ // Each lockfile's packages not yet seen, to look up as kept (lookUp); those
164
+ // already seen, by seenKey, each with whether only devDependencies need it
165
+ // so far; those of them with none kept, put off as long as that holds, by
166
+ // seenKey; and those told stale, to assess again once those with none kept
167
+ // are.
168
+ lookups: Queue<AssessedPackage[]>
169
+ seen: Map<string, boolean>
170
+ dev: Map<string, AssessedPackage>
171
+ stale: AssessedPackage[]
172
+ // The repositories told whole, this part or one before (ScanProgress).
173
+ told: Map<number, ToldRepository>
174
+ actions: ReturnType<typeof resolvingActions> | null
175
+ audits: ReturnType<typeof inTurns>
176
+ }
177
+
178
+ // A package as a scan meets it: by its name, version and a mirror's integrity.
179
+ const seenKey = (pkg: AssessedPackage) => `${pkg.name}@${pkg.version}\0${pkg.integrity ?? ''}`
180
+
181
+ // A package's key, as its risk line is kept: its name, version and a
182
+ // mirror's integrity, and whether a team lists its scope.
183
+ const riskKey = (pkg: AssessedPackage, teamScoped: boolean) => `${seenKey(pkg)}\0${teamScoped}`
184
+ // Whether a line kept `at` is told as it is: within RISK_KEPT_MS, and kept
185
+ // since risk told a score (assessNpm `score`).
186
+ const isFresh = ({ at, line }: { at: number; line: RiskLine }) => Date.now() - at < RISK_KEPT_MS && ('error' in line || typeof line.score === 'number')
187
+
188
+ // A package assessed (assess), its line kept, in RiskCaches and the source's
189
+ // `risks`, where it tells what risk found, or that a mirror's copy isn't npm's.
190
+ async function assessed(scan: Scan, pkg: AssessedPackage): Promise<RiskLine | null> {
191
+ let teamScoped
192
+ try { teamScoped = await scan.source.teamScoped(pkg.name) } catch (error) { return { type: 'risk', ...pkg, ...failureOf(error) } }
193
+ const key = riskKey(pkg, teamScoped)
194
+ const line = await assessPackage(scan.source, scan.signal, pkg, teamScoped)
195
+ if (line && (!('error' in line) || line.error === 'integrity-mismatch')) {
196
+ const at = Date.now()
197
+ scan.caches.risks.set(key, { at, line })
198
+ await scan.source.risks?.write(key, line, at)
199
+ }
200
+ return line
201
+ }
202
+
203
+ // Risk lines kept of `keys`, by key: in this instance's memory, else the
204
+ // source's `risks`, KEPT_READ at a time.
205
+ async function keptLines({ source, caches }: Scan, keys: string[]) {
206
+ const kept = new Map<string, { at: number; line: RiskLine }>()
207
+ const left = keys.filter(key => { const hit = caches.risks.get(key); if (hit) kept.set(key, hit); return !hit })
208
+ for (let from = 0; source.risks && from < left.length; from += KEPT_READ) {
209
+ for (const [key, { at, value }] of await source.risks.readMany(left.slice(from, from + KEPT_READ))) {
210
+ caches.risks.set(key, { at, line: value })
211
+ kept.set(key, { at, line: value })
212
+ }
213
+ }
214
+ return kept
215
+ }
216
+
217
+ // Each lockfile's packages, as assessLater gives them: their risk lines as
218
+ // kept, however old, told at once, a fresh one as it is and an older one as
219
+ // stale (`stale`, when it was assessed), its package assessed again once
220
+ // those with none kept are (`scan.stale`); those with none given to `assess`,
221
+ // but those only devDependencies need so far, put off (`scan.dev`).
222
+ async function lookUp(scan: Scan, assess: (packages: AssessedPackage[]) => void) {
223
+ for (let packages = await scan.lookups.take(); packages !== undefined; packages = await scan.lookups.take()) {
224
+ const keyed: { pkg: AssessedPackage; key: string }[] = []
225
+ for (const pkg of packages) {
226
+ try { keyed.push({ pkg, key: riskKey(pkg, await scan.source.teamScoped(pkg.name)) }) } catch (error) { scan.lines.add({ type: 'risk', ...pkg, ...failureOf(error) }) }
227
+ }
228
+ const kept = await keptLines(scan, keyed.map(({ key }) => key))
229
+ const missing: AssessedPackage[] = []
230
+ for (const { pkg, key } of keyed) {
231
+ const hit = kept.get(key)
232
+ if (hit && isFresh(hit)) scan.lines.add(hit.line)
233
+ else if (hit) { scan.lines.add({ ...hit.line, stale: { assessedAt: hit.at } }); scan.stale.push(pkg) }
234
+ else if (scan.seen.get(seenKey(pkg)) === true) scan.dev.set(seenKey(pkg), pkg)
235
+ else missing.push(pkg)
236
+ }
237
+ if (missing.length > 0) assess(missing)
238
+ }
239
+ }
240
+
241
+ async function assessor(scan: Scan, pending: Queue<AssessedPackage>) {
242
+ for (let next = await pending.take(); next !== undefined; next = await pending.take()) {
243
+ const line = await assessed(scan, next)
244
+ if (line) scan.lines.add(line)
245
+ }
246
+ }
247
+
248
+ // The packages `feed` gives assessed, each given to the assessors once its
249
+ // downloads are readied, where the source readies them (scan-downloads.ts):
250
+ // once all it gives are told, or the scan stops.
251
+ async function assessing(scan: Scan, feed: (assess: (packages: AssessedPackage[]) => void) => Promise<void>) {
252
+ const pending = queue<AssessedPackage>(scan.signal)
253
+ const readying = scan.source.downloads
254
+ ? readyingDownloads<AssessedPackage>(scan.source.downloads, scan.signal, pkg => { pending.add(pkg) }, { busy: isBusy, retries: BUSY_RETRIES, waitMs: BUSY_WAIT_MS }) : null
255
+ const assessors = Array.from({ length: MAX_SPARE_ASSESSMENTS }, () => assessor(scan, pending))
256
+ try { await feed(packages => { if (readying) readying.add(packages); else for (const pkg of packages) pending.add(pkg) }) } finally {
257
+ await readying?.close()
258
+ pending.close()
259
+ }
260
+ await Promise.all(assessors)
261
+ }
262
+
263
+ // A lockfile's packages of npm's registry or a mirror not yet seen this scan,
264
+ // to look up as kept (lookUp), and assess where none is; and one seen as only
265
+ // devDependencies need it, and put off, that this lockfile needs otherwise,
266
+ // to look up again and assess now.
267
+ function assessLater(scan: Scan, packages: LockedPackage[]) {
268
+ const fresh: AssessedPackage[] = []
269
+ for (const { name, version, source, integrity, dev = false } of packages) {
270
+ if ((source !== 'registry' && source !== 'mirror') || version === null || !isNpmPackageName(name) || !isNpmPackageSpec(version)) continue
271
+ const pkg = { name, version, ...integrity === undefined ? {} : { integrity } }
272
+ const key = seenKey(pkg)
273
+ const was = scan.seen.get(key)
274
+ if (was === false || (was && dev)) continue
275
+ scan.seen.set(key, dev)
276
+ if (was === undefined || scan.dev.delete(key)) fresh.push(pkg)
277
+ }
278
+ if (fresh.length > 0) scan.lookups.add(fresh)
279
+ }
280
+
281
+ export type LockfileLine = Extract<RepositoryRiskLine, { type: 'lockfile' }>
282
+
283
+ // A lockfile's advisories line, of its audit (repository-risk-audit.ts auditLockfile).
284
+ const advisoriesLine = ({ repo, path }: LockfileLine, audit: Audit) => ({ type: 'advisories', repo, path, ...Array.isArray(audit) ? { advisories: audit } : audit } as const)
285
+
286
+ // A repository read, its lockfiles' audits asked meanwhile, AUDITS_AT_ONCE
287
+ // across the scan (auditLockfiles), to tell in turn once access is checked again.
288
+ type Audited = (RepositoryRead & { audits: Promise<Audit | null>[] }) | RepositoryFailure
289
+ const audited = (scan: Scan, read: RepositoryRead | RepositoryFailure | null): Audited | null => (read === null || 'type' in read ? read : { ...read, audits: auditLockfiles(scan.source, scan.caches.advisories,
290
+ scan.signal, read.lockfiles.map(({ sha, line }) => ({ key: `${line.format}\0${sha}`, packages: 'packages' in line ? line.packages : null })), scan.audits) })
291
+
292
+ type DependabotLine = Extract<RepositoryRiskLine, { type: 'dependabot' }>
293
+
294
+ // A repository's Dependabot alerts' line, each alert with the versions the
295
+ // lockfile it is of locks that it covers (`lockfiles`, a repository read's),
296
+ // or why they couldn't be had.
297
+ function dependabotLine(repo: number, read: DependabotRead, lockfiles: RepositoryRead['lockfiles']): DependabotLine {
298
+ if ('error' in read) return { type: 'dependabot', repo, ...read }
299
+ const locked = new Map(lockfiles.flatMap(({ line }) => 'packages' in line ? [[line.path, line.packages] as const] : []))
300
+ return { type: 'dependabot', repo, alerts: read.alerts.map(alert => ({ ...alert, versions: alertVersions(alert, locked.get(alert.manifest)),
301
+ malware: npmMalwareAdvisory({ id: alert.ghsa, aliases: alert.aliases, cwe: alert.cwe, title: alert.title }) })) }
302
+ }
303
+
304
+ // A repository's alerts checked again just before they are told, as access to
305
+ // the repository is (DependabotRead `recheck`): why not, where the user's
306
+ // access to them is withdrawn since they were read.
307
+ async function rechecked(read: DependabotRead): Promise<DependabotRead> {
308
+ if (!('alerts' in read) || !read.recheck) return read
309
+ try { await read.recheck() } catch (error) { return failureOf(error, 'checking access to its Dependabot alerts again') }
310
+ return read
311
+ }
312
+
313
+ // A repository read (repository-risk-read.ts readRepository) told: its
314
+ // line, or why it couldn't be read, then its lockfiles', and their
315
+ // advisories, asked as it was read, its packages assessed meanwhile, then
316
+ // its Dependabot alerts.
317
+ // Access to it is checked again
318
+ // just before, however long ago it was read, as GitHub may have withdrawn it.
319
+ async function tellRepository(scan: Scan, repo: RepositoryRiskRepo, read: Audited | null) {
320
+ if (!read || scan.signal.aborted) return
321
+ if ('type' in read) { scan.lines.add(read); return }
322
+ try { await read.recheck() } catch (error) {
323
+ if (!scan.signal.aborted) scan.lines.add({ type: 'repo', id: repo.repoId, ...failureOf(error, 'checking access to it again') })
324
+ return
325
+ }
326
+ if (scan.signal.aborted) return
327
+ const { commit, lockfiles } = read
328
+ scan.lines.add({ type: 'repo', id: repo.repoId, commit, lockfiles: lockfiles.map(({ line: { path, format } }) => ({ path, format })) })
329
+ for (const { line } of lockfiles) {
330
+ scan.lines.add(line)
331
+ if ('packages' in line) assessLater(scan, line.packages)
332
+ }
333
+ const refs = read.actions ? tellActions(scan, repo, read.actions, lockfiles) : []
334
+ for (const [at, { line }] of lockfiles.entries()) {
335
+ if (scan.signal.aborted) return
336
+ const audit = await read.audits[at]
337
+ if (audit) scan.lines.add(advisoriesLine(line, audit))
338
+ }
339
+ if (scan.signal.aborted) return
340
+ const dependabot = read.dependabot && await rechecked(read.dependabot)
341
+ if (scan.signal.aborted) return
342
+ if (dependabot) scan.lines.add(dependabotLine(repo.repoId, dependabot, lockfiles))
343
+ scan.told.set(repo.repoId, { id: repo.repoId, name: repo.fullName, paths: repo.paths ?? null,
344
+ lockfiles: lockfiles.flatMap(({ sha, line }) => 'packages' in line ? [`${line.format}\0${sha}`] : []), ...refs.length > 0 ? { actions: refs } : {} })
345
+ }
346
+
347
+ // A repository's Actions told, and the references they make to resolve.
348
+ function tellActions(scan: Scan, repo: RepositoryRiskRepo, read: WorkflowsRead, lockfiles: RepositoryRead['lockfiles']) {
349
+ const locked = lockfiles.flatMap(({ line }) => 'packages' in line ? [lockedNames(line.path, line.packages)] : [])
350
+ const { lines, refs } = actionsLines(repo.repoId, repo.fullName.split('/')[0]!, read, locked)
351
+ for (const line of lines) scan.lines.add(line)
352
+ scan.actions?.add(refs)
353
+ return refs
354
+ }
355
+
356
+ // Whether an earlier part told `repo` whole, by its name and a team's
357
+ // directories in it as they are now, its packages then looked up as its
358
+ // lockfiles are kept, GitHub asked nothing of it: not where one isn't. It is
359
+ // told as read then, its default branch's head not asked again.
360
+ async function toldBefore(scan: Scan, repo: RepositoryRiskRepo) {
361
+ const told = scan.told.get(repo.repoId)
362
+ if (!told || told.name !== repo.fullName || JSON.stringify(told.paths) !== JSON.stringify(repo.paths ?? null)) return false
363
+ const reads: LockedPackage[][] = [], unknown = told.lockfiles.filter(key => !scan.caches.lockfiles.get(key))
364
+ const stored = unknown.length > 0 && scan.source.lockfiles ? await scan.source.lockfiles.readMany(unknown) : null
365
+ for (const key of told.lockfiles) {
366
+ const read = scan.caches.lockfiles.get(key) ?? stored?.get(key)?.value
367
+ if (!read || !('packages' in read)) return false
368
+ reads.push(read.packages)
369
+ }
370
+ for (const packages of reads) assessLater(scan, packages)
371
+ scan.actions?.add(told.actions ?? [])
372
+ return true
373
+ }
374
+
375
+ // Each repository, READ_AHEAD read at a time, each told in turn, but those an
376
+ // earlier part told whole (ScanProgress), read of none.
377
+ async function readRepositories(scan: Scan) {
378
+ const repos = await scan.source.repos()
379
+ scan.lines.add({ type: 'repos', repos: repos.map(repo => ({ id: repo.repoId, fullName: repo.fullName })) })
380
+ // Those still listed: one no longer is read again should it be once more.
381
+ const listed = new Set(repos.map(repo => repo.repoId))
382
+ // Those within SCAN_READ_KEPT_MS, as their lockfiles are kept that long.
383
+ const kept = await scan.source.progress?.read()
384
+ const progress = kept && Date.now() - kept.at < SCAN_READ_KEPT_MS ? kept.value.repos : []
385
+ for (const told of progress) if (listed.has(told.id)) scan.told.set(told.id, told)
386
+ const reads: Promise<Audited | null>[] = []
387
+ const read = (at: number) => {
388
+ if (reads[at]) return reads[at]
389
+ const repo = repos[at]!
390
+ const started = reads[at] = toldBefore(scan, repo).then(async told => (told ? null : audited(scan, await readRepository(scan, repo))))
391
+ // One read ahead and no longer waited on, as the scan stopped, fails alone.
392
+ started.catch(() => {})
393
+ return started
394
+ }
395
+ for (const [at, repo] of repos.entries()) {
396
+ if (scan.signal.aborted) return
397
+ for (let ahead = at; ahead < Math.min(at + READ_AHEAD, repos.length); ahead++) void read(ahead)
398
+ await tellRepository(scan, repo, await read(at))
399
+ }
400
+ }
401
+
402
+ // What is left to assess once the repositories are read, a turn at a time:
403
+ // the stale ones that more than devDependencies need, then those only
404
+ // devDependencies need, those with none kept before the stale ones.
405
+ function leftOver(scan: Scan): AssessedPackage[][] {
406
+ const dev = (pkg: AssessedPackage) => scan.seen.get(seenKey(pkg)) === true
407
+ return [scan.stale.filter(pkg => !dev(pkg)), [...scan.dev.values(), ...scan.stale.filter(dev)]]
408
+ }
409
+
410
+ // The scan's work, behind its lines (repositoryRiskLines), `done` last, its
411
+ // lines closed once it ends, its failure given to `fail`.
412
+ async function runScan(scan: Scan, fail: (error: unknown) => void) {
413
+ try {
414
+ // Those with no risk line kept assessed first, as their lockfiles are read,
415
+ await assessing(scan, async assess => {
416
+ const looking = lookUp(scan, assess)
417
+ // stopped at once where reading fails;
418
+ try { await readRepositories(scan) } catch (error) { fail(error) } finally { scan.lookups.close() }
419
+ await looking
420
+ })
421
+ // then those told stale, and those only devDependencies need, in turn.
422
+ for (const left of leftOver(scan)) {
423
+ if (!scan.signal.aborted && left.length > 0) await assessing(scan, assess => { assess(left); return Promise.resolve() })
424
+ }
425
+ await scan.actions?.close()
426
+ if (!scan.signal.aborted) scan.lines.add({ type: 'done' })
427
+ } catch (error) { fail(error) } finally { scan.lines.close() }
428
+ }
429
+
430
+ // The scan's lines, in the order they are found: the repositories first,
431
+ // then each repository's lockfiles and their packages once read and access
432
+ // is checked again, and each package's risk: as kept, however old, at once
433
+ // (lookUp), then those with none kept once assessed, while the repositories
434
+ // are still being read, then those told stale once assessed again, and those
435
+ // only devDependencies need after all the rest (leftOver); `done`
436
+ // last. Ends at once, the work
437
+ // under way given up on, where `signal` aborts or the lines are no longer read. A failure of
438
+ // a repository, a lockfile or a package is told in its line; one of the scan
439
+ // itself is thrown, the lines before it told. What it reads is kept in
440
+ // `caches` (RiskCaches), the instance's own unless given. Given `partMs`, it
441
+ // stops once that long, as a function time-limited must (Vercel's), the work
442
+ // under way given up on, its last line `continue`, for its reader to ask
443
+ // again: those it assessed are kept, and told at once then, and the
444
+ // repositories it told whole kept as its source's `progress`.
445
+ export async function* repositoryRiskLines<R extends RepositoryRiskRepo>(source: RepositoryRiskSource<R>, signal: AbortSignal, caches = shared,
446
+ { partMs = null }: { partMs?: number | null } = {}): AsyncGenerator<RepositoryRiskLine> {
447
+ const part = new AbortController(), stopped = new AbortController()
448
+ const parting = partMs === null ? undefined : setTimeout(() => { part.abort() }, partMs)
449
+ const running = AbortSignal.any([signal, stopped.signal, part.signal])
450
+ // The lines told until the part's time is up, those found by then told, and
451
+ // none waited for: the work under way, such as a request to GitHub, which
452
+ // isn't given up on at once, outlasting it.
453
+ const lines = queue<RepositoryRiskLine>(AbortSignal.any([signal, part.signal]), { drain: true })
454
+ const actions = source.actions ? resolvingActions({ source: source.actions, signal: running, tell: line => { lines.add(line) }, memory: caches.actions,
455
+ answers: caches.actionAnswers, store: source.actionLines }) : null
456
+ const scan: Scan = { source, caches, signal: running, lines, lookups: queue(running), seen: new Map(), dev: new Map(), stale: [], told: new Map(), actions,
457
+ audits: inTurns(AUDITS_AT_ONCE) }
458
+ // A failure of the scan itself kept, to throw once the lines before it are
459
+ // told, and the scan stopped.
460
+ const failed: unknown[] = []
461
+ void runScan(scan, error => { failed.push(error); stopped.abort() })
462
+ try {
463
+ let done = false
464
+ for (let line = await scan.lines.take(); line !== undefined; line = await scan.lines.take()) {
465
+ done ||= line.type === 'done'
466
+ yield line
467
+ }
468
+ if (done || signal.aborted) return
469
+ if (part.signal.aborted) {
470
+ // Not waited on past PROGRESS_WRITE_MS, within what Vercel's limit
471
+ // leaves past the part's: the next part then goes on from less.
472
+ let timer
473
+ await Promise.race([source.progress?.write({ repos: [...scan.told.values()] }), new Promise(resolve => { timer = setTimeout(resolve, PROGRESS_WRITE_MS) })])
474
+ clearTimeout(timer)
475
+ yield { type: 'continue' }
476
+ }
477
+ else if (failed.length > 0) throw failed[0]
478
+ } finally {
479
+ // A GitHub request under way isn't waited on: it settles on its own.
480
+ clearTimeout(parting)
481
+ stopped.abort()
482
+ }
483
+ }
@@ -0,0 +1,160 @@
1
+ // The pull requests squashed into a repository's commits, as the code
2
+ // viewer's Commits tab draws them (repository-history.ts), each looked up
3
+ // with GraphQL once and kept by its commit.
4
+ import { linkNoreplyUsers } from './github-accounts.ts'
5
+ import { githubGraphql, notFound } from './github-graphql.ts'
6
+ import { SHA } from './github-values.ts'
7
+ import { COMMIT_FRAGMENT, type GraphCommit, type HistoryCommit, commitActors, commitIds, commitsQuery, graphCommit, inBatches, variablesOf } from './repository-history.ts'
8
+
9
+ // A pull request squashed into a commit of the default branch's history
10
+ // (`merge`): its number, the commit its head was at when merged (`head`,
11
+ // GitHub's own of it, which a branch reused or pushed over since never
12
+ // moves), and its own commits, the latest MAX_SQUASHED of them, `more`
13
+ // where it had more. Drawn as the merge it was, its commits on a lane of
14
+ // their own (repository-history.js).
15
+ export interface SquashedPull { merge: string; number: number; head: string; commits: HistoryCommit[]; more: boolean }
16
+ // The pull requests squashed into commits, kept by each commit (a merged pull
17
+ // request's commits never change); null for a commit none was.
18
+ export interface Squashes {
19
+ read(shas: string[]): Promise<Map<string, SquashedPull | null>>
20
+ write(sha: string, pull: SquashedPull | null): Promise<void>
21
+ }
22
+
23
+ // The pull requests merged as another read told them (http.ts pulseMerges,
24
+ // the Pulse's agent-merges.ts agentMerges): each's merge commit, its number
25
+ // where told (null where not), every one merged from `from` till `to` among
26
+ // them; a commit committed within, as a squash's or a rebase's is as it is
27
+ // merged, the merge commit of the one it names, or of none.
28
+ export interface KnownMerges { numbers: ReadonlyMap<string, number | null>; from: number; to: number }
29
+ // How far within `from` and `to` a commit is told by them, for the clocks
30
+ // of a merge and its commit.
31
+ const KNOWN_SKEW_MS = 5 * 60_000
32
+
33
+ const MAX_SQUASHED = 100
34
+ // Looked up of an answer's commits not yet kept, at most, the newest first;
35
+ // in queries of as many commits, or pull requests (their commits' lines
36
+ // counted, as a history's are), as many at once.
37
+ const MAX_SQUASH_LOOKUPS = 500
38
+ const SQUASH_COMMITS = 100
39
+ const SQUASH_PULLS = 5
40
+ const SQUASH_PARALLEL = 4
41
+
42
+ // The merged pull request that brought each commit in, `c<n>` the `n`th's.
43
+ const mergedPullsQuery = (count: number) => commitsQuery(count, 'c', 'associatedPullRequests(first: 1) { nodes { number mergeCommit { oid } } }')
44
+ // Each pull request's head when merged and its latest commits, `p<n>` the `n`th's.
45
+ const squashedQuery = (count: number) => `query($owner: String!, $name: String!, ${variablesOf('n', count, 'Int!')}) {
46
+ repository(owner: $owner, name: $name) {
47
+ ${Array.from({ length: count }, (_, at) => `p${at}: pullRequest(number: $n${at}) { headRefOid commits(last: ${MAX_SQUASHED}) { totalCount nodes { commit { ...historyCommit } } } }`).join('\n ')}
48
+ }
49
+ }
50
+ ${COMMIT_FRAGMENT}`
51
+
52
+ type MergedPulls = { repository?: Record<string, { associatedPullRequests?: { nodes?: ({ number?: unknown; mergeCommit?: { oid?: unknown } | null } | null)[] } } | null> | null }
53
+ type SquashedPage = { repository?: Record<string, { headRefOid?: unknown; commits?: { totalCount?: unknown; nodes?: ({ commit?: GraphCommit | null } | null)[] } } | null> | null }
54
+
55
+ // Each repository's lookup of squashed pull requests going on, by its full
56
+ // name: one at a time, those asking meanwhile waiting on it, and their
57
+ // commits it doesn't look up looked up once it is done.
58
+ const lookingUp = new Map<string, Promise<void>>()
59
+
60
+ // Whether `promise` settles within `ms`, waited on that long at most.
61
+ const within = (promise: Promise<unknown>, ms: number) => ms === Number.POSITIVE_INFINITY ? promise
62
+ : new Promise<void>(resolve => {
63
+ const timer = setTimeout(resolve, ms)
64
+ void promise.finally(() => { clearTimeout(timer); resolve() })
65
+ })
66
+
67
+ // The pull requests squashed into `commits`, a merged pull request's merge
68
+ // commit of one parent, not one rebased (its commits copied onto the branch,
69
+ // told by their subjects), kept by each commit (`squashes`), those not yet
70
+ // kept looked up with GraphQL, as many as MAX_SQUASH_LOOKUPS an answer, each
71
+ // kept as it is found (lookUpSquashes), of those merges another read told
72
+ // (`known`), the pull request each was merged by not looked up. Answered
73
+ // with those kept once the
74
+ // repository's lookup is done, or `waitMs` on, that lookup going on behind:
75
+ // `behind`, one this started, for the caller to keep alive, and `pending`
76
+ // while one does. Another's lookup done within it, but not of all of these,
77
+ // those it left are looked up as this one's, within what is left of it.
78
+ export async function squashedPulls(fullName: string, token: string, commits: HistoryCommit[], squashes: Squashes,
79
+ waitMs = Number.POSITIVE_INFINITY, fetchImpl: typeof fetch = globalThis.fetch, known: KnownMerges | null = null)
80
+ : Promise<{ pulls: SquashedPull[]; pending: boolean; behind: Promise<void> | null }> {
81
+ const single = commits.filter(commit => commit.parents.length === 1)
82
+ const kept = await squashes.read(single.map(commit => commit.sha))
83
+ let unknown = single.filter(commit => !kept.has(commit.sha))
84
+ if (unknown.length === 0) return { pulls: single.flatMap(commit => kept.get(commit.sha) ?? []), pending: false, behind: null }
85
+ const listed = new Map(commits.map(commit => [commit.sha, commit]))
86
+ const deadline = Date.now() + waitMs
87
+ const found = new Map<string, SquashedPull | null>()
88
+ // Waited on, as long as is left, and those of `unknown` it kept found.
89
+ const settle = async (looking: Promise<void>) => {
90
+ await within(looking, Math.max(0, deadline - Date.now()))
91
+ for (const [sha, pull] of await squashes.read(unknown.map(commit => commit.sha))) found.set(sha, pull)
92
+ unknown = unknown.filter(commit => !found.has(commit.sha))
93
+ }
94
+ const another = lookingUp.get(fullName)
95
+ if (another) await settle(another)
96
+ let behind: Promise<void> | null = null
97
+ if (!another || (unknown.length > 0 && !lookingUp.has(fullName))) {
98
+ const lookup = lookUpSquashes(fullName, token, unknown.slice(0, MAX_SQUASH_LOOKUPS), listed, squashes, fetchImpl, known)
99
+ const done: Promise<void> = lookup.catch(() => {}).finally(() => { if (lookingUp.get(fullName) === done) lookingUp.delete(fullName) })
100
+ lookingUp.set(fullName, done)
101
+ behind = lookup
102
+ await settle(done)
103
+ }
104
+ return { pulls: single.flatMap(commit => kept.get(commit.sha) ?? found.get(commit.sha) ?? []), pending: lookingUp.has(fullName), behind }
105
+ }
106
+
107
+ // The pull requests squashed into `unknown`, of the commits `listed`, looked
108
+ // up, each kept as it is found (squashedPulls); those committed when
109
+ // `known` tells every merge, by it: a merge commit's pull request, by its
110
+ // number, the rest none's.
111
+ async function lookUpSquashes(fullName: string, token: string, unknown: HistoryCommit[], listed: Map<string, HistoryCommit>, squashes: Squashes,
112
+ fetchImpl: typeof fetch, known: KnownMerges | null) {
113
+ const [owner, name] = fullName.split('/') as [string, string]
114
+ const merged: { commit: HistoryCommit; number: number }[] = []
115
+ const asked: HistoryCommit[] = []
116
+ for (const commit of unknown) {
117
+ const told = known !== null && commit.committedAt !== null && commit.committedAt >= known.from + KNOWN_SKEW_MS && commit.committedAt <= known.to - KNOWN_SKEW_MS
118
+ const number = told ? known.numbers.get(commit.sha) : null
119
+ if (number === null) asked.push(commit)
120
+ else if (number === undefined) await squashes.write(commit.sha, null)
121
+ else merged.push({ commit, number })
122
+ }
123
+ await inBatches(asked, SQUASH_COMMITS, SQUASH_PARALLEL, async batch => {
124
+ const data = await githubGraphql(mergedPullsQuery(batch.length), { owner, name, ...commitIds(batch.map(commit => commit.sha)) }, token, fetchImpl,
125
+ notFound) as MergedPulls
126
+ for (const [at, commit] of batch.entries()) {
127
+ const node = data?.repository?.[`c${at}`]
128
+ if (!node) continue
129
+ const pull = node.associatedPullRequests?.nodes?.[0]
130
+ const number = pull?.mergeCommit?.oid === commit.sha && Number.isSafeInteger(pull.number) && (pull.number as number) > 0 ? pull.number as number : null
131
+ if (number === null) await squashes.write(commit.sha, null)
132
+ else merged.push({ commit, number })
133
+ }
134
+ })
135
+ await inBatches(merged, SQUASH_PULLS, SQUASH_PARALLEL, async batch => {
136
+ const data = await githubGraphql(squashedQuery(batch.length), { owner, name, ...Object.fromEntries(batch.map(({ number }, at) => [`n${at}`, number])) },
137
+ token, fetchImpl, notFound) as SquashedPage
138
+ await linkNoreplyUsers(Object.values(data?.repository ?? {}).flatMap(pull => (pull?.commits?.nodes ?? []).flatMap(item => commitActors(item?.commit))), token, fetchImpl)
139
+ for (const [at, { commit, number }] of batch.entries()) {
140
+ const node = data?.repository?.[`p${at}`]
141
+ if (!node) continue
142
+ const own = (node.commits?.nodes ?? []).flatMap(item => graphCommit(item?.commit) ?? [])
143
+ const head = typeof node.headRefOid === 'string' && SHA.test(node.headRefOid) ? node.headRefOid : own.at(-1)?.sha
144
+ // Fast-forwarded, its last commit the merge's own; or rebased, its
145
+ // commits, more than one, copied onto the branch: the merge and those
146
+ // below it on their first parents, by their subjects, its commits'
147
+ // (one squashed is told by its commit's title too, by default, and
148
+ // drawn as it was either way).
149
+ const below = [commit]
150
+ for (let next = listed.get(commit.parents[0] ?? ''); next && below.length < own.length; next = listed.get(next.parents[0] ?? '')) below.push(next)
151
+ const copies = own.toReversed().slice(0, below.length).every((item, step) => below[step]!.subject === item.subject)
152
+ // Its commits' copies as far as those listed go, but not all of them
153
+ // listed: told, and kept, once they are.
154
+ if (own.length > 1 && copies && below.length < own.length) continue
155
+ const rebased = own.length > 1 && copies
156
+ const squashed = head !== undefined && head !== commit.sha && own.length > 0 && !own.some(item => item.sha === commit.sha) && !rebased
157
+ await squashes.write(commit.sha, squashed ? { merge: commit.sha, number, head, commits: own, more: Number(node.commits?.totalCount) > own.length } : null)
158
+ }
159
+ })
160
+ }