@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,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
+ }
@@ -0,0 +1,41 @@
1
+ // A repository's change stamp: what moves as anything its tabs read of it
2
+ // changes, but the checks its pull requests run, which move no pull
3
+ // request's update time, read in one cheap GraphQL query: when it was last
4
+ // pushed to, which branch is its default, how many branches and tags it
5
+ // has, and how many pull requests and issues it has and when the one
6
+ // updated last was. An answer kept of it
7
+ // is read again behind its readers only where its stamp moved since the
8
+ // answer was read (http.ts keptAnswer).
9
+ import { GithubApiError } from './github-errors.ts'
10
+ import { githubGraphql } from './github-graphql.ts'
11
+
12
+ // The rules a stamp is read by: its key's, so that a stamp read by others is
13
+ // none's (http.ts stampOf).
14
+ export const STAMP_READ = 2
15
+
16
+ const STAMP_QUERY = `query($owner: String!, $name: String!) {
17
+ repository(owner: $owner, name: $name) {
18
+ pushedAt
19
+ defaultBranchRef { name }
20
+ heads: refs(refPrefix: "refs/heads/", first: 1) { totalCount }
21
+ tags: refs(refPrefix: "refs/tags/", first: 1) { totalCount }
22
+ pullRequests(first: 1, orderBy: { field: UPDATED_AT, direction: DESC }) { totalCount nodes { updatedAt } }
23
+ issues(first: 1, orderBy: { field: UPDATED_AT, direction: DESC }) { totalCount nodes { updatedAt } }
24
+ }
25
+ }`
26
+ type Counted = { totalCount?: unknown; nodes?: ({ updatedAt?: unknown } | null)[] | null } | null
27
+ type Stamped = { repository?: { pushedAt?: unknown; defaultBranchRef?: { name?: unknown } | null; heads?: Counted; tags?: Counted; pullRequests?: Counted; issues?: Counted } | null }
28
+ | null
29
+
30
+ // Repository `fullName`'s stamp, read with `token`, as text to compare.
31
+ export async function repositoryStamp(fullName: string, token: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<{ stamp: string }> {
32
+ const [owner, name] = fullName.split('/') as [string, string]
33
+ const repository = (await githubGraphql(STAMP_QUERY, { owner, name }, token, fetchImpl) as Stamped)?.repository
34
+ if (!repository) throw new GithubApiError(404, 'github-not-found')
35
+ // One missing a count tells nothing: none, never one that would move with nothing.
36
+ const { heads, tags, pullRequests, issues } = repository
37
+ if (![heads, tags, pullRequests, issues].every(connection => Number.isSafeInteger(connection?.totalCount))) throw new GithubApiError(502, 'github-malformed')
38
+ const latest = (connection: Counted | undefined) => [connection?.totalCount, connection?.nodes?.[0]?.updatedAt ?? null]
39
+ return { stamp: JSON.stringify([repository.pushedAt ?? null, repository.defaultBranchRef?.name ?? null, heads?.totalCount, tags?.totalCount, ...latest(pullRequests),
40
+ ...latest(issues)]) }
41
+ }
@@ -0,0 +1,63 @@
1
+ // Where a request's time goes, told back in its Server-Timing header, which
2
+ // DevTools shows beside the request: the database's statements and the time
3
+ // spent in its operations (sql.ts), new pooled connections and their
4
+ // handshakes (db-neon.ts), GitHub's calls (github-requests.ts githubJson), and
5
+ // the whole, from the handler's start to its answer's head; an instance's
6
+ // first request marked cold. Counts and durations alone, nothing of what was
7
+ // asked; a streamed answer's head tells what was known as it was written.
8
+ import { AsyncLocalStorage } from 'node:async_hooks'
9
+ import { ServerResponse } from 'node:http'
10
+
11
+ interface Timing {
12
+ started: number
13
+ cold: boolean
14
+ statements: number
15
+ db: number; dbMs: number
16
+ conn: number; connMs: number
17
+ gh: number; ghMs: number
18
+ }
19
+ const requests = new AsyncLocalStorage<Timing>()
20
+ let served = false
21
+
22
+ // `work` timed, its response's head carrying what it spent where; a test's
23
+ // stand-in for a response, not a ServerResponse, is left as it is.
24
+ export function runTimed<T>(res: ServerResponse, work: () => T): T {
25
+ const timing: Timing = { started: performance.now(), cold: !served, statements: 0, db: 0, dbMs: 0, conn: 0, connMs: 0, gh: 0, ghMs: 0 }
26
+ served = true
27
+ if (res instanceof ServerResponse) {
28
+ const writeHead = res.writeHead
29
+ res.writeHead = function (this: ServerResponse, ...args: Parameters<ServerResponse['writeHead']>) {
30
+ if (!this.headersSent) this.setHeader('server-timing', header(timing))
31
+ return writeHead.apply(this, args)
32
+ } as ServerResponse['writeHead']
33
+ }
34
+ return requests.run(timing, work)
35
+ }
36
+
37
+ // `work`, its time counted as `kind`'s where a request is timed.
38
+ export async function timed<T>(kind: 'db' | 'conn' | 'gh', work: () => Promise<T>): Promise<T> {
39
+ const timing = requests.getStore()
40
+ if (!timing) return work()
41
+ const start = performance.now()
42
+ try { return await work() } finally {
43
+ timing[kind]++
44
+ timing[`${kind}Ms`] += performance.now() - start
45
+ }
46
+ }
47
+
48
+ // A statement sent to the database, where a request is timed.
49
+ export function countStatement(): void {
50
+ const timing = requests.getStore()
51
+ if (timing) timing.statements++
52
+ }
53
+
54
+ function header(timing: Timing): string {
55
+ const ms = (value: number) => value.toFixed(1)
56
+ return [
57
+ ...timing.db > 0 || timing.statements > 0 ? [`db;dur=${ms(timing.dbMs)};desc="${timing.statements} statements"`] : [],
58
+ ...timing.conn > 0 ? [`conn;dur=${ms(timing.connMs)}`] : [],
59
+ ...timing.gh > 0 ? [`gh;dur=${ms(timing.ghMs)};desc="${timing.gh} calls"`] : [],
60
+ ...timing.cold ? ['cold;desc="first request of this instance"'] : [],
61
+ `app;dur=${ms(performance.now() - timing.started)}`,
62
+ ].join(', ')
63
+ }
@@ -0,0 +1,170 @@
1
+ // The reviewed dependencies a host keeps beyond the app, as it registers
2
+ // them before the server is assembled (server.ts registerReviewedDependencies):
3
+ // an async method telling whether a dependency, as a lockfile locks it, is
4
+ // reviewed there (`lookup`), and, optionally, one naming the version to
5
+ // review one a pull request adds against (`base`, pull-dependency-reviews.ts),
6
+ // one reading the reviews of
7
+ // dependencies an open pull request's comments make (`parseComments`,
8
+ // pull-comment-reviews.ts), and one formatting one's own dependency reviews
9
+ // as a comment, for a copy button to give (`formatDependencyReviews`,
10
+ // dependency-review-comments.ts). Registered, they replace the commit a repository
11
+ // is reviewed since (pull-dependency-reviews.ts): a version passes by the
12
+ // reviews its teams publish, and those its pull request's comments make, as
13
+ // many as the repository requires, or by `lookup`'s saying so, and is
14
+ // otherwise unreviewed. A patched version's (pnpm's patchedDependencies)
15
+ // reviews are of its patch, its teams' and its comments' alike. Those
16
+ // comments' reviews count for the pull request alone, as it is open: the
17
+ // host's to keep, as it is merged, among those `lookup` tells of.
18
+ //
19
+ // Each version is asked of `lookup` (and `base`) once a request, as many at once as
20
+ // ASK_AT_ONCE, its answer kept in this instance KEPT_MS; one it fails to
21
+ // answer is unreviewed, and counted so (`unasked`), or has no base.
22
+ import { isExactVersion } from '@preventive/upstream/semver.js'
23
+ import { isNpmPackageName } from '../common/managed/npm-packages.js'
24
+ import { type Lru, lru } from './lru.ts'
25
+
26
+ export type ReviewedLockfile = 'npm' | 'pnpm' | 'yarn1'
27
+ // A dependency as a lockfile locks it: npm's with its integrity where it has
28
+ // one (one with none asked of as it is, `lookup` passing it or not, as only
29
+ // the host may), its shasum where the lockfile
30
+ // has one (Yarn 1's, after a tarball's `#`), and the hash of its patch where
31
+ // it is patched (pnpm's).
32
+ export interface ReviewedDependency {
33
+ ecosystem: 'npm'
34
+ lockfile: ReviewedLockfile
35
+ name: string
36
+ version: string
37
+ integrity?: string
38
+ shasum?: string
39
+ patchHash?: string
40
+ }
41
+ export type ReviewVerdict = 'accept' | 'accept-with-nits' | 'request-changes' | 'reject'
42
+ // A comment of an open pull request's, as `parseComments` is given it: one
43
+ // on the pull request (`comment`), a review's own (`review`, whatever its
44
+ // state, a comment's alone too), or one on a line of its diff
45
+ // (`review-comment`); by its author's GitHub login; when it was written, and
46
+ // last edited (`editedAt`) where it was.
47
+ export interface ReviewComment {
48
+ kind: 'comment' | 'review' | 'review-comment'
49
+ id: string
50
+ author: string | null
51
+ body: string
52
+ state?: string
53
+ createdAt: string
54
+ editedAt?: string
55
+ url: string
56
+ }
57
+ // What `parseComments` reads: the pull request, its comments, and the
58
+ // dependencies: every one the lockfiles its review holds to add that can be
59
+ // reviewed and `lookup` doesn't pass, and the others still wanting reviews.
60
+ export interface ParseCommentsInput { repository: string; number: number; comments: ReviewComment[]; dependencies: ReviewedDependency[] }
61
+ // A review its comments make, by `user` (a GitHub login, one of their
62
+ // authors'), of each of `dependencies`, with its verdict, as of `time` (when
63
+ // it was made, an ISO date or milliseconds; that user's latest comment's
64
+ // where none is told).
65
+ export interface CommentReview {
66
+ user: string
67
+ time?: string | number
68
+ dependencies: { ecosystem?: 'npm'; name: string; version: string; integrity: string; patchHash?: string; status: ReviewVerdict }[]
69
+ }
70
+ // A version a dependency review is of, or compared it with: its package's
71
+ // name, its version, the integrity and, where npm tells one, the shasum of
72
+ // its tarball, each held to the tarball reviewed, and its patch's hash where
73
+ // it is known (pnpm's patched dependencies').
74
+ export interface ReviewedVersion { name: string; version: string; integrity: string; shasum?: string; patchHash?: string }
75
+ // One of one's own published dependency reviews, as `formatDependencyReviews`
76
+ // is given it: the version it is of (`new`) and the one it compared it with
77
+ // (`old`, none where it read its package whole); its verdict (`status`);
78
+ // whether it read every file (`coverage`, `full`, else `partial`); its final
79
+ // comment; each file's verdict and comment (`files`, of those with either);
80
+ // by whom (`reviewer`, their GitHub login), and when it was published.
81
+ export interface DependencyReviewEntry {
82
+ ecosystem: 'npm'
83
+ old: ReviewedVersion | null
84
+ new: ReviewedVersion
85
+ status: ReviewVerdict
86
+ coverage: 'full' | 'partial'
87
+ comment: string
88
+ files: { path: string; status: ReviewVerdict | null; comment: string }[]
89
+ reviewer: string
90
+ publishedAt: number
91
+ }
92
+ // What `formatDependencyReviews` formats: one's own reviews, never another's,
93
+ // and the pull request whose versions they are of, where its copy asks.
94
+ export interface FormatDependencyReviewsInput { reviews: DependencyReviewEntry[]; pullRequest?: { repository: string; number: number } }
95
+ // A version to review a dependency against: of its package or another.
96
+ export interface ReviewedBase { name: string; version: string }
97
+ export interface ReviewedDependencies {
98
+ lookup(dependency: ReviewedDependency): Promise<boolean>
99
+ // The reviewed version to review it against; none for its whole package.
100
+ base?(dependency: ReviewedDependency): Promise<ReviewedBase | null | undefined>
101
+ parseComments?(input: ParseCommentsInput): Promise<CommentReview[]>
102
+ // The comment to copy, none where it is empty, null or undefined.
103
+ formatDependencyReviews?(input: FormatDependencyReviewsInput): Promise<string | null | undefined>
104
+ }
105
+
106
+ const ASK_AT_ONCE = 16
107
+ const KEPT_MS = 60_000
108
+
109
+ let registered: ReviewedDependencies | null = null
110
+ let assembled = false
111
+ // Each method's answers, apart.
112
+ const answers = new WeakMap<object, Lru<{ at: number; value: unknown }>>()
113
+
114
+ // Registers the host's reviewed dependencies, once, before the server is
115
+ // assembled (init()): a server already assembled keeps what it was given.
116
+ export function registerReviewedDependencies(reviewed: ReviewedDependencies): void {
117
+ const optional = (method: unknown) => method === undefined || typeof method === 'function'
118
+ if (typeof reviewed?.lookup !== 'function' || !optional(reviewed.base) || !optional(reviewed.parseComments) || !optional(reviewed.formatDependencyReviews)) {
119
+ throw new TypeError('registerReviewedDependencies: expected { lookup, base?, parseComments?, formatDependencyReviews? }, async methods')
120
+ }
121
+ if (assembled) throw new Error('registerReviewedDependencies: call it before init(), as the server takes them as it is assembled')
122
+ if (registered) throw new Error('registerReviewedDependencies: reviewed dependencies are registered already')
123
+ registered = { lookup: reviewed.lookup.bind(reviewed), ...reviewed.base ? { base: reviewed.base.bind(reviewed) } : {},
124
+ ...reviewed.parseComments ? { parseComments: reviewed.parseComments.bind(reviewed) } : {},
125
+ ...reviewed.formatDependencyReviews ? { formatDependencyReviews: reviewed.formatDependencyReviews.bind(reviewed) } : {} }
126
+ }
127
+
128
+ // The reviewed dependencies registered, as a server takes them once it is
129
+ // assembled; none registers after.
130
+ export function assembledReviewedDependencies(): ReviewedDependencies | null {
131
+ assembled = true
132
+ return registered
133
+ }
134
+
135
+ // What `method` answers for each of `dependencies`, by their keys; one it
136
+ // fails to answer for left out, and logged, as failing to `what`.
137
+ async function askEach<T>(method: (dependency: ReviewedDependency) => Promise<T>, dependencies: Map<string, ReviewedDependency>, what: string): Promise<Map<string, T>> {
138
+ const told = new Map<string, T>()
139
+ const pending = [...dependencies]
140
+ const kept = answers.get(method) ?? answers.set(method, lru(100_000)).get(method)!
141
+ await Promise.all(Array.from({ length: Math.min(ASK_AT_ONCE, pending.length) }, async () => {
142
+ for (let next = pending.pop(); next; next = pending.pop()) {
143
+ const [key, dependency] = next
144
+ const known = kept.get(key)
145
+ if (known && Date.now() - known.at < KEPT_MS) { told.set(key, known.value as T); continue }
146
+ try {
147
+ const value = await method({ ...dependency })
148
+ kept.set(key, { at: Date.now(), value })
149
+ told.set(key, value)
150
+ } catch (error) {
151
+ console.warn(`reviewed dependencies: failed to ${what}`, `${dependency.name}@${dependency.version}`, error instanceof Error ? error.message : error)
152
+ }
153
+ }
154
+ }))
155
+ return told
156
+ }
157
+
158
+ // Which of `dependencies`, by their keys, `lookup` passes, and how many it
159
+ // failed to answer.
160
+ export async function askReviewed(lookup: ReviewedDependencies['lookup'], dependencies: Map<string, ReviewedDependency>): Promise<{ passed: Set<string>; unasked: number }> {
161
+ const told = await askEach(lookup, dependencies, 'answer')
162
+ return { passed: new Set([...told].flatMap(([key, reviewed]) => reviewed === true ? [key] : [])), unasked: dependencies.size - told.size }
163
+ }
164
+
165
+ // The version `base` names to review each of `dependencies` against, by
166
+ // their keys: none where it names no exact version of an npm package.
167
+ export async function askBases(base: NonNullable<ReviewedDependencies['base']>, dependencies: Map<string, ReviewedDependency>): Promise<Map<string, ReviewedBase>> {
168
+ return new Map([...await askEach(base, dependencies, 'name a base')].flatMap(([key, one]) => isNpmPackageName(one?.name) && typeof one?.version === 'string'
169
+ && isExactVersion(one.version) ? [[key, { name: one.name, version: one.version }] as const] : []))
170
+ }
@@ -0,0 +1,35 @@
1
+ // Internal invalidation counters. Never expose these global values to clients:
2
+ // feeds still publish only the existing user/visibility-scoped revisions.
3
+ const catalogTables = ['managed_link_report', 'managed_team', 'managed_team_user', 'managed_team_repo', 'managed_report', 'managed_bundle', 'managed_selected_repo']
4
+ const annotationTables = ['managed_finding_triage', 'managed_finding_triage_event', 'managed_finding_comment', 'managed_finding_issue']
5
+ export function revisionSchema(postgres = false): string {
6
+ let sql = `CREATE TABLE IF NOT EXISTS managed_maintenance_lease (
7
+ id INTEGER PRIMARY KEY, owner TEXT NOT NULL, expires_at INTEGER NOT NULL
8
+ ); CREATE TABLE IF NOT EXISTS managed_change_revision (
9
+ id INTEGER PRIMARY KEY, catalog INTEGER NOT NULL, annotations INTEGER NOT NULL
10
+ ); INSERT INTO managed_change_revision VALUES (1, 0, 0) ON CONFLICT(id) DO NOTHING;`
11
+ for (const [column, tables] of [['catalog', catalogTables], ['annotations', annotationTables]] as const) {
12
+ const update = `UPDATE managed_change_revision SET ${column} = ${column} + 1 WHERE id = 1;`
13
+ if (postgres) {
14
+ sql += `CREATE OR REPLACE FUNCTION managed_${column}_changed() RETURNS trigger LANGUAGE plpgsql AS $$
15
+ BEGIN IF EXISTS (SELECT 1 FROM managed_revision_rows) THEN ${update} END IF; RETURN NULL; END $$;`
16
+ }
17
+ for (const table of tables) {
18
+ if (postgres) {
19
+ sql += `DROP TRIGGER IF EXISTS ${table}_revision ON ${table};`
20
+ for (const event of ['INSERT', 'UPDATE', 'DELETE']) {
21
+ sql += `DROP TRIGGER IF EXISTS ${table}_revision_${event} ON ${table};
22
+ CREATE TRIGGER ${table}_revision_${event} AFTER ${event} ON ${table}
23
+ REFERENCING ${event === 'DELETE' ? 'OLD' : 'NEW'} TABLE AS managed_revision_rows
24
+ FOR EACH STATEMENT EXECUTE FUNCTION managed_${column}_changed();`
25
+ }
26
+ } else {
27
+ for (const event of ['INSERT', 'UPDATE', 'DELETE']) {
28
+ sql += `CREATE TRIGGER IF NOT EXISTS ${table}_revision_${event}
29
+ AFTER ${event} ON ${table} BEGIN ${update} END;`
30
+ }
31
+ }
32
+ }
33
+ }
34
+ return sql
35
+ }
@@ -0,0 +1,121 @@
1
+ // A scan's packages' downloads, as risk asks them, readied before the
2
+ // packages are assessed (repository-risk.ts), so that no assessment waits on
3
+ // npm's downloads API, which answers some 40 lookups a minute: a package is
4
+ // given to the assessors once its downloads are kept (npm-risk.ts
5
+ // npmReadyScanDownloads), those that can be readied at once (kept already,
6
+ // and unscoped ones, asked in bulk) first, each lockfile's as it is read, and
7
+ // the rest (scoped ones, which npm answers only one by one) one at a time,
8
+ // at the pace npm allows, while the assessors go on with the others. In
9
+ // each, those of packages given `first` (a scan's Stasis's) go before the
10
+ // others, and so do those hurried once given.
11
+ import { setTimeout as delay } from 'node:timers/promises'
12
+ import { type Queue, queue } from './queue.ts'
13
+
14
+ export interface DownloadsSource {
15
+ // Readies those of `names` that can be at once, `ready` told each.
16
+ atOnce(names: string[], ready: (name: string) => void, signal: AbortSignal): Promise<void>
17
+ // Readies one on its own.
18
+ one(name: string, signal: AbortSignal): Promise<void>
19
+ }
20
+
21
+ // How npm asking to be asked later is told (`busy`), and waited on: asked
22
+ // again after a wait, up to `retries` times running.
23
+ export interface DownloadsPacing { busy(error: unknown): boolean; retries: number; waitMs: number }
24
+
25
+ export interface ReadyingDownloads<T> {
26
+ // Packages to give once their downloads are ready, those `first` readied
27
+ // before the rest.
28
+ add(items: T[], first?: boolean): void
29
+ // Those of `names` still waiting readied before the rest from now on.
30
+ hurry(names: string[]): void
31
+ // Once all added are given, or the scan stops.
32
+ close(): Promise<void>
33
+ }
34
+
35
+ // Readies the downloads of the packages added, each given (`give`) once its
36
+ // name's are, or once readying them fails otherwise than npm asking to wait,
37
+ // or npm keeps asking past `retries`: its assessment then asks its own.
38
+ export function readyingDownloads<T extends { name: string }>(source: DownloadsSource, signal: AbortSignal, give: (item: T) => void,
39
+ { busy, retries, waitMs }: DownloadsPacing): ReadyingDownloads<T> {
40
+ const waiting = new Map<string, T[]>()
41
+ // Those of them left to ready one by one, and those readied before the
42
+ // rest: a name hurried is in line twice, readied once.
43
+ const alone = new Set<string>(), hurried = new Set<string>()
44
+ const atOnce: Queue<string[]> = queue(signal), oneByOne: Queue<string> = queue(signal)
45
+ const release = (name: string) => {
46
+ for (const item of waiting.get(name) ?? []) give(item)
47
+ waiting.delete(name)
48
+ hurried.delete(name)
49
+ alone.delete(name)
50
+ }
51
+ const wait = async (attempt: number) => { try { await delay(waitMs * Math.min(attempt + 1, 5), undefined, { signal }); return true } catch { return false } }
52
+
53
+ // A lockfile's names, those that can be readied at once, again after a wait
54
+ // where npm asks: false once the scan stops.
55
+ const readyNow = async (names: string[]) => {
56
+ for (let attempt = 0; attempt <= retries; attempt++) {
57
+ const left = names.filter(name => waiting.has(name) && !alone.has(name))
58
+ if (left.length === 0) return true
59
+ try { await source.atOnce(left, release, signal); return true } catch (error) {
60
+ if (signal.aborted) return false
61
+ if (!busy(error)) { for (const name of left) release(name); return true }
62
+ if (!await wait(attempt)) return false
63
+ }
64
+ }
65
+ return true
66
+ }
67
+ // Each lockfile's, the rest left to oneByOne.
68
+ const readyAtOnce = async () => {
69
+ for (let names = await atOnce.take(); names !== undefined; names = await atOnce.take()) {
70
+ if (!await readyNow(names)) return
71
+ for (const name of names) {
72
+ if (!waiting.has(name) || alone.has(name)) continue
73
+ alone.add(name)
74
+ oneByOne.add(name, hurried.has(name))
75
+ }
76
+ }
77
+ }
78
+ const readyOneByOne = async () => {
79
+ for (let name = await oneByOne.take(); name !== undefined; name = await oneByOne.take()) {
80
+ if (!alone.has(name)) continue
81
+ for (let attempt = 0; attempt <= retries; attempt++) {
82
+ try { await source.one(name, signal); break } catch (error) {
83
+ if (signal.aborted) return
84
+ if (!busy(error) || !await wait(attempt)) break
85
+ }
86
+ }
87
+ release(name)
88
+ }
89
+ }
90
+ const lanes = [readyAtOnce().finally(() => { oneByOne.close() }), readyOneByOne()]
91
+ // Those still waiting put in line again, first: those not yet asked at once
92
+ // asked together.
93
+ const hurry = (names: string[]) => {
94
+ const now: string[] = []
95
+ for (const name of names) {
96
+ if (!waiting.has(name) || hurried.has(name)) continue
97
+ hurried.add(name)
98
+ if (alone.has(name)) oneByOne.add(name, true)
99
+ else now.push(name)
100
+ }
101
+ if (now.length > 0) atOnce.add(now, true)
102
+ }
103
+ return {
104
+ add(items, first = false) {
105
+ const names: string[] = [], waited: string[] = []
106
+ for (const item of items) {
107
+ const kept = waiting.get(item.name)
108
+ if (kept) { kept.push(item); waited.push(item.name) }
109
+ else { waiting.set(item.name, [item]); names.push(item.name) }
110
+ }
111
+ if (first) for (const name of names) hurried.add(name)
112
+ if (names.length > 0) atOnce.add(names, first)
113
+ if (first) hurry(waited)
114
+ },
115
+ hurry,
116
+ async close() {
117
+ atOnce.close()
118
+ await Promise.all(lanes)
119
+ },
120
+ }
121
+ }