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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (442) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +16 -78
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +6 -0
  13. package/common/bundle-compare-diff.js +377 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-imports.js +20 -0
  20. package/common/bundle-metadata.d.ts +15 -0
  21. package/common/bundle-metadata.js +226 -0
  22. package/common/bundle-pkg-of.d.ts +1 -0
  23. package/common/bundle-pkg-of.js +90 -0
  24. package/common/bundle-reasons.d.ts +6 -0
  25. package/common/bundle-reasons.js +58 -0
  26. package/common/bundle-source-links.d.ts +6 -0
  27. package/common/bundle-source-links.js +216 -0
  28. package/common/bundle-sourcemap.d.ts +10 -0
  29. package/common/bundle-sourcemap.js +100 -0
  30. package/common/bundle-sources.d.ts +10 -0
  31. package/common/bundle-sources.js +374 -0
  32. package/common/bundle-stats.js +41 -0
  33. package/common/bundle-tabs.js +1 -0
  34. package/common/code-language.js +66 -0
  35. package/common/default-scan-models.ts +36 -0
  36. package/common/dependency-reviews.d.ts +18 -0
  37. package/common/dependency-reviews.js +64 -0
  38. package/common/finding-duplicates.js +63 -0
  39. package/common/finding-filters.js +313 -0
  40. package/common/finding-id.js +47 -0
  41. package/common/finding-repo.d.ts +5 -0
  42. package/common/finding-repo.js +67 -0
  43. package/common/github-issue-labels.d.ts +1 -0
  44. package/common/github-issue-labels.js +11 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +14 -0
  48. package/common/line-diff.js +181 -0
  49. package/common/linked-workspace-groups.js +63 -0
  50. package/common/managed/agent-tasks.ts +292 -0
  51. package/common/managed/comments.ts +43 -0
  52. package/common/managed/dependency-routes.js +25 -0
  53. package/common/managed/directory-packages.ts +28 -0
  54. package/common/managed/finding-detail.d.ts +5 -0
  55. package/common/managed/finding-detail.js +75 -0
  56. package/common/managed/finding-values.d.ts +2 -0
  57. package/common/managed/finding-values.js +138 -0
  58. package/common/managed/github-agents.ts +114 -0
  59. package/common/managed/github-logins.ts +49 -0
  60. package/common/managed/lite-name.d.ts +2 -0
  61. package/common/managed/lite-name.js +20 -0
  62. package/common/managed/npm-packages.d.ts +9 -0
  63. package/common/managed/npm-packages.js +63 -0
  64. package/common/managed/permissions.ts +31 -0
  65. package/common/managed/report-content.ts +72 -0
  66. package/common/managed/report-filter.ts +120 -0
  67. package/common/managed/repository-alias.ts +65 -0
  68. package/common/managed/review-view-routes.js +23 -0
  69. package/common/managed/risk-routes.js +30 -0
  70. package/common/managed/roles.ts +41 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +385 -0
  73. package/common/managed/scan-models.ts +6 -0
  74. package/common/managed/stasis-config.ts +7 -0
  75. package/common/managed/team-app.d.ts +19 -0
  76. package/common/managed/team-app.js +129 -0
  77. package/common/managed/team-filters.js +26 -0
  78. package/common/managed/triage.ts +83 -0
  79. package/common/managed/upload-seal.ts +126 -0
  80. package/common/pretty-json.js +98 -0
  81. package/common/pretty-kinds.js +20 -0
  82. package/common/pretty-print.d.ts +6 -0
  83. package/common/pretty-print.js +36 -0
  84. package/common/pretty-sourcemap.js +70 -0
  85. package/common/repo-commit.d.ts +4 -0
  86. package/common/repo-commit.js +30 -0
  87. package/common/revalidation-conflicts.js +48 -0
  88. package/common/revalidation-input-groups.js +56 -0
  89. package/common/save-error-reason.ts +20 -7
  90. package/common/scan-server.ts +13 -0
  91. package/common/security-links.d.ts +5 -0
  92. package/common/security-links.js +33 -0
  93. package/common/server-info.ts +46 -0
  94. package/common/sourcemap-listing.js +78 -0
  95. package/common/sourcemap-mappings.js +136 -0
  96. package/common/sourcemap-unlist.js +85 -0
  97. package/common/stasis-files.d.ts +5 -0
  98. package/common/stasis-files.js +20 -0
  99. package/common/stasis-tgz.d.ts +6 -0
  100. package/common/stasis-tgz.js +27 -0
  101. package/common/utf8.d.ts +3 -0
  102. package/common/utf8.js +45 -0
  103. package/common/whitespace-insensitive.js +19 -0
  104. package/common/workspace-app.js +91 -0
  105. package/common/workspace-groups.js +176 -0
  106. package/out/activity.js +2 -0
  107. package/out/brotli-fallback.js +3 -3
  108. package/out/chunk-2XUEZHIP.js +28 -0
  109. package/out/chunk-55YIWY3H.js +5 -0
  110. package/out/chunk-563V5VVT.js +266 -0
  111. package/out/chunk-5AVGKFMR.js +1 -0
  112. package/out/chunk-5EAVJAD2.js +3 -0
  113. package/out/chunk-5M2X3QPK.js +6 -0
  114. package/out/chunk-5QWPKTCE.js +40 -0
  115. package/out/chunk-5UJHJWFU.js +4 -0
  116. package/out/chunk-6CCSTJWB.js +1 -0
  117. package/out/chunk-6VOB5WXX.js +2 -0
  118. package/out/chunk-6WMQVUT2.js +3 -0
  119. package/out/chunk-6Y6PZ2BU.js +9 -0
  120. package/out/chunk-74JZTGTO.js +11 -0
  121. package/out/chunk-7BKKYVWR.js +7 -0
  122. package/out/chunk-7C7DWL7I.js +1 -0
  123. package/out/chunk-7HP2VYIC.js +2 -0
  124. package/out/chunk-7YFJUT2P.js +1 -0
  125. package/out/chunk-7YO4QV5P.js +1 -0
  126. package/out/chunk-A4BBBHQU.js +1 -0
  127. package/out/chunk-B64CTMVU.js +4 -0
  128. package/out/chunk-BEKYZCPX.js +14 -0
  129. package/out/chunk-C4Z6ZBXV.js +10 -0
  130. package/out/chunk-CU3FPB3P.js +1 -0
  131. package/out/chunk-DEVAORP2.js +1 -0
  132. package/out/chunk-DOYTKRIR.js +53 -0
  133. package/out/chunk-DUASGS2O.js +8 -0
  134. package/out/chunk-EEJA7JBI.js +13 -0
  135. package/out/chunk-FSU2PLJL.js +1 -0
  136. package/out/chunk-GO7FT4OD.js +1 -0
  137. package/out/chunk-GX5UXWT4.js +1 -0
  138. package/out/chunk-H4FEC57K.js +1 -0
  139. package/out/chunk-ITUKKCCK.js +10 -0
  140. package/out/chunk-IYPY47MC.js +1 -0
  141. package/out/chunk-K4XJHM2T.js +1 -0
  142. package/out/chunk-LBD3M3J6.js +1 -0
  143. package/out/chunk-LVSLM7HB.js +1 -0
  144. package/out/chunk-LVW7WWV4.js +1 -0
  145. package/out/chunk-N57OWFKY.js +15 -0
  146. package/out/chunk-NRPC74AM.js +1 -0
  147. package/out/chunk-OAWQNDAO.js +3 -0
  148. package/out/chunk-OOJM4CTU.js +1 -0
  149. package/out/chunk-PEE47ANR.js +1 -0
  150. package/out/chunk-PKLVXUEI.js +11 -0
  151. package/out/chunk-PLGH63UC.js +2 -0
  152. package/out/chunk-PNHBZGDD.js +1 -0
  153. package/out/chunk-PTFYDJUP.js +1 -0
  154. package/out/chunk-PWFUOLZK.js +17 -0
  155. package/out/chunk-PXK7EU4V.js +1 -0
  156. package/out/chunk-QD3IBSF4.js +7 -0
  157. package/out/chunk-QI66YA4F.js +1 -0
  158. package/out/chunk-QRKFPLA4.js +80 -0
  159. package/out/chunk-R3NZFXVR.js +1 -0
  160. package/out/chunk-R5O6FAW4.js +2 -0
  161. package/out/chunk-RPNO56H2.js +1 -0
  162. package/out/chunk-SSPDMA6D.js +1 -0
  163. package/out/chunk-SZWPYLPC.js +1 -0
  164. package/out/chunk-TUII34K2.js +1 -0
  165. package/out/chunk-UJP4PQJA.js +1 -0
  166. package/out/chunk-UJSJMXEG.js +1 -0
  167. package/out/chunk-UR4WYMIP.js +1 -0
  168. package/out/chunk-VHEXSGGP.js +1 -0
  169. package/out/chunk-VYYUMYVW.js +9 -0
  170. package/out/chunk-WCDYSIKG.js +1 -0
  171. package/out/chunk-WFBVS4QI.js +1 -0
  172. package/out/chunk-XM4RLC4A.js +2 -0
  173. package/out/chunk-ZQHLECTI.js +1 -0
  174. package/out/client-managed-import.js +4 -0
  175. package/out/client-managed.js +37 -0
  176. package/out/client-sync.js +11 -17
  177. package/out/compare.js +26 -0
  178. package/out/dialogs.js +40 -0
  179. package/out/github-issue-authorized.html +3 -0
  180. package/out/github-issue-authorized.js +1 -0
  181. package/out/graph.js +19 -4
  182. package/out/index.html +104 -24
  183. package/out/prism.js +14 -10
  184. package/out/scan.js +2 -0
  185. package/out/stasis.svg +20 -0
  186. package/out/terminal.js +367 -39
  187. package/out/view.css +1 -1
  188. package/out/view.js +19 -147
  189. package/package.json +409 -64
  190. package/risk/actions/findings.js +161 -0
  191. package/risk/actions/resolve.js +287 -0
  192. package/risk/actions/scripts/commands.js +182 -0
  193. package/risk/actions/scripts/grade.js +113 -0
  194. package/risk/actions/scripts/packages.js +123 -0
  195. package/risk/actions/scripts/shell.js +169 -0
  196. package/risk/actions/uses.js +94 -0
  197. package/risk/actions/workflow.js +183 -0
  198. package/risk/files/characters.js +354 -0
  199. package/risk/files/hosts.js +206 -0
  200. package/risk/files/readability.js +185 -0
  201. package/risk/files/runs-code.js +568 -0
  202. package/risk/files/script.js +410 -0
  203. package/risk/files/source-map-link.js +43 -0
  204. package/risk/files/stamps.js +47 -0
  205. package/risk/index.d.ts +294 -0
  206. package/risk/index.js +12 -0
  207. package/risk/npm/assess.js +285 -0
  208. package/risk/npm/combined.js +68 -0
  209. package/risk/npm/compare.js +236 -0
  210. package/risk/npm/dependencies.js +172 -0
  211. package/risk/npm/diff.js +79 -0
  212. package/risk/npm/downloads.js +84 -0
  213. package/risk/npm/files.js +445 -0
  214. package/risk/npm/held.js +67 -0
  215. package/risk/npm/install-scripts.js +34 -0
  216. package/risk/npm/malware.js +38 -0
  217. package/risk/npm/manifest.js +65 -0
  218. package/risk/npm/new-dependency.js +60 -0
  219. package/risk/npm/old-version.js +108 -0
  220. package/risk/npm/registry.js +393 -0
  221. package/risk/npm/release.js +85 -0
  222. package/risk/npm/score.js +59 -0
  223. package/risk/npm/specs.js +124 -0
  224. package/risk/npm/tarball.js +169 -0
  225. package/server-common/database-config.ts +16 -0
  226. package/server-common/initialize.ts +18 -0
  227. package/server-common/npm-advisories.ts +101 -0
  228. package/{server → server-common}/origin.ts +5 -5
  229. package/server-common/reap.ts +48 -0
  230. package/server-common/scan-config.ts +19 -0
  231. package/server-common/standalone.ts +29 -0
  232. package/server-common/storage-crypto.ts +182 -0
  233. package/server-common/storage-log.ts +38 -0
  234. package/server-common/vercel-blob.ts +103 -0
  235. package/server-e2e/app.ts +487 -0
  236. package/{server → server-e2e}/bus-receiver.ts +2 -1
  237. package/{server → server-e2e}/cli.js +9 -4
  238. package/{server → server-e2e}/config.ts +50 -42
  239. package/{server → server-e2e}/db-neon.ts +2 -2
  240. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  241. package/{server → server-e2e}/db-stmt.ts +2 -2
  242. package/{server → server-e2e}/db.ts +7 -7
  243. package/{server → server-e2e}/http.ts +44 -13
  244. package/{server → server-e2e}/hub.ts +40 -9
  245. package/server-e2e/index.ts +17 -0
  246. package/server-e2e/lifecycle.ts +95 -0
  247. package/{server → server-e2e}/neon-driver.ts +2 -2
  248. package/{server → server-e2e}/npm-proxy.ts +12 -145
  249. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  250. package/{server → server-e2e}/objstore/blob.ts +1 -1
  251. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  252. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  253. package/{server → server-e2e}/objstore/init.ts +19 -27
  254. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  255. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  257. package/{server → server-e2e}/objstore/rest.ts +3 -3
  258. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  259. package/{server → server-e2e}/objstore/store.ts +7 -7
  260. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  261. package/{server → server-e2e}/pubsub.ts +12 -9
  262. package/{server → server-e2e}/sign.ts +4 -4
  263. package/{server → server-e2e}/sse-server.ts +60 -33
  264. package/{server → server-e2e}/static.ts +18 -17
  265. package/{server → server-e2e}/sync-handlers.ts +64 -30
  266. package/{server → server-e2e}/ws-server.ts +20 -9
  267. package/server-managed/activity.ts +269 -0
  268. package/server-managed/agent-merges.ts +109 -0
  269. package/server-managed/app-agents.ts +23 -0
  270. package/server-managed/avatar-store.ts +13 -0
  271. package/server-managed/blob-store.ts +26 -0
  272. package/server-managed/brotli.ts +10 -0
  273. package/server-managed/bundle-advisories.ts +79 -0
  274. package/server-managed/bundle-advisory-inventory.ts +85 -0
  275. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  276. package/server-managed/bundle-build-diagnostics.js +23 -0
  277. package/server-managed/bundle-build-leases.ts +41 -0
  278. package/server-managed/bundle-build-worker.js +380 -0
  279. package/server-managed/bundle-build.ts +326 -0
  280. package/server-managed/bundle-cache.ts +261 -0
  281. package/server-managed/bundle-catalog.ts +29 -0
  282. package/server-managed/bundle-commits.ts +133 -0
  283. package/server-managed/bundle-dependency-reviews.ts +91 -0
  284. package/server-managed/bundle-store.ts +24 -0
  285. package/server-managed/bundle-summary-cache.ts +139 -0
  286. package/server-managed/bundle-validation.ts +33 -0
  287. package/server-managed/bundle.ts +151 -0
  288. package/server-managed/cache-storage.ts +20 -0
  289. package/server-managed/cli.js +21 -0
  290. package/server-managed/combined.ts +43 -0
  291. package/server-managed/comments.ts +138 -0
  292. package/server-managed/commit-coauthors.ts +105 -0
  293. package/server-managed/commit-lockfiles.ts +78 -0
  294. package/server-managed/comparison.ts +51 -0
  295. package/server-managed/config.ts +163 -0
  296. package/server-managed/content-access.ts +15 -0
  297. package/server-managed/crypto.ts +25 -0
  298. package/server-managed/db-methods.ts +1915 -0
  299. package/server-managed/db-neon.ts +398 -0
  300. package/server-managed/db-schema.ts +263 -0
  301. package/server-managed/db-table-names.ts +22 -0
  302. package/server-managed/db.ts +149 -0
  303. package/server-managed/dependabot-access.ts +61 -0
  304. package/server-managed/dependabot-alerts.ts +180 -0
  305. package/server-managed/dependency-review-comments.ts +158 -0
  306. package/server-managed/dependency-reviews.ts +369 -0
  307. package/server-managed/github-accounts.ts +59 -0
  308. package/server-managed/github-actions.ts +71 -0
  309. package/server-managed/github-app.ts +347 -0
  310. package/server-managed/github-errors.ts +92 -0
  311. package/server-managed/github-graphql.ts +42 -0
  312. package/server-managed/github-issue-links.ts +264 -0
  313. package/server-managed/github-issue-oauth.ts +30 -0
  314. package/server-managed/github-issues.ts +157 -0
  315. package/server-managed/github-link-oauth.ts +56 -0
  316. package/server-managed/github-links.ts +204 -0
  317. package/server-managed/github-metadata.ts +213 -0
  318. package/server-managed/github-oauth.ts +264 -0
  319. package/server-managed/github-pulls.ts +257 -0
  320. package/server-managed/github-requests.ts +181 -0
  321. package/server-managed/github-users.ts +30 -0
  322. package/server-managed/github-values.ts +26 -0
  323. package/server-managed/history-windows.ts +172 -0
  324. package/server-managed/http-response.ts +76 -0
  325. package/server-managed/http.ts +6327 -0
  326. package/server-managed/import-triage.ts +51 -0
  327. package/server-managed/index.ts +204 -0
  328. package/server-managed/kept-briefly.ts +37 -0
  329. package/server-managed/kept.ts +28 -0
  330. package/server-managed/link-reports.ts +149 -0
  331. package/server-managed/listed-activity.ts +39 -0
  332. package/server-managed/locked-packages.ts +234 -0
  333. package/server-managed/lockfile-scope.ts +58 -0
  334. package/server-managed/lru.ts +30 -0
  335. package/server-managed/managed-issues.ts +92 -0
  336. package/server-managed/management-catalog.ts +45 -0
  337. package/server-managed/management.ts +116 -0
  338. package/server-managed/npm-delta-worker.js +142 -0
  339. package/server-managed/npm-delta.ts +277 -0
  340. package/server-managed/npm-insights.ts +455 -0
  341. package/server-managed/npm-kept.ts +265 -0
  342. package/server-managed/npm-loads.ts +259 -0
  343. package/server-managed/npm-manifest.ts +117 -0
  344. package/server-managed/npm-packages.ts +469 -0
  345. package/server-managed/npm-patch-paths.ts +86 -0
  346. package/server-managed/npm-patch.ts +455 -0
  347. package/server-managed/npm-provenance.ts +127 -0
  348. package/server-managed/npm-risk.ts +287 -0
  349. package/server-managed/object-storage-disk.ts +147 -0
  350. package/server-managed/object-storage-vercel.ts +71 -0
  351. package/server-managed/object-storage.ts +82 -0
  352. package/server-managed/package-entry-points.ts +127 -0
  353. package/server-managed/pretty-copies.ts +22 -0
  354. package/server-managed/pretty-format.d.ts +3 -0
  355. package/server-managed/pretty-format.js +13 -0
  356. package/server-managed/pretty-print.ts +442 -0
  357. package/server-managed/public-workspace.ts +243 -0
  358. package/server-managed/pull-comment-reviews.ts +161 -0
  359. package/server-managed/pull-dependencies.ts +370 -0
  360. package/server-managed/pull-dependency-reviews.ts +407 -0
  361. package/server-managed/pull-reviews.ts +202 -0
  362. package/server-managed/queue.ts +54 -0
  363. package/server-managed/release-commits.ts +85 -0
  364. package/server-managed/rename-diff-worker.js +30 -0
  365. package/server-managed/rename-diff.ts +237 -0
  366. package/server-managed/repo-path.ts +21 -0
  367. package/server-managed/report-migration.ts +32 -0
  368. package/server-managed/report-opening.ts +77 -0
  369. package/server-managed/report-query.ts +10 -0
  370. package/server-managed/report-response.ts +16 -0
  371. package/server-managed/report-sources.ts +185 -0
  372. package/server-managed/report-store.ts +77 -0
  373. package/server-managed/repository-actions.ts +220 -0
  374. package/server-managed/repository-agents.ts +422 -0
  375. package/server-managed/repository-aliases.ts +119 -0
  376. package/server-managed/repository-browser.ts +361 -0
  377. package/server-managed/repository-changes.ts +280 -0
  378. package/server-managed/repository-code.ts +222 -0
  379. package/server-managed/repository-dependency-reviews.ts +182 -0
  380. package/server-managed/repository-discovery.ts +83 -0
  381. package/server-managed/repository-history.ts +428 -0
  382. package/server-managed/repository-issues.ts +293 -0
  383. package/server-managed/repository-policy.ts +27 -0
  384. package/server-managed/repository-pulls.ts +207 -0
  385. package/server-managed/repository-pulse.ts +477 -0
  386. package/server-managed/repository-risk-assess.ts +108 -0
  387. package/server-managed/repository-risk-audit.ts +78 -0
  388. package/server-managed/repository-risk-caches.ts +37 -0
  389. package/server-managed/repository-risk-read.ts +260 -0
  390. package/server-managed/repository-risk-stasis.ts +61 -0
  391. package/server-managed/repository-risk-turn.ts +97 -0
  392. package/server-managed/repository-risk.ts +516 -0
  393. package/server-managed/repository-squashes.ts +160 -0
  394. package/server-managed/repository-stamp.ts +41 -0
  395. package/server-managed/request-timing.ts +63 -0
  396. package/server-managed/reviewed-dependencies.ts +170 -0
  397. package/server-managed/revisions.ts +35 -0
  398. package/server-managed/scan-downloads.ts +121 -0
  399. package/server-managed/session.ts +132 -0
  400. package/server-managed/slugs.ts +38 -0
  401. package/server-managed/solidity-entry-points.ts +71 -0
  402. package/server-managed/sql-postgres.ts +34 -0
  403. package/server-managed/sql.ts +107 -0
  404. package/server-managed/stasis-config.ts +147 -0
  405. package/server-managed/stasis-dependencies.ts +221 -0
  406. package/server-managed/static.ts +28 -0
  407. package/server-managed/storage-command.ts +16 -0
  408. package/server-managed/storage-db.ts +183 -0
  409. package/server-managed/storage-encryption.ts +288 -0
  410. package/server-managed/storage-maintenance.ts +259 -0
  411. package/server-managed/storage-payload.ts +121 -0
  412. package/server-managed/storage-stores.ts +91 -0
  413. package/server-managed/storage.ts +82 -0
  414. package/server-managed/team-app-summaries.ts +56 -0
  415. package/server-managed/team-app.ts +156 -0
  416. package/server-managed/team-catalog.ts +7 -0
  417. package/server-managed/team-feed.ts +180 -0
  418. package/server-managed/team-npm-scopes.ts +103 -0
  419. package/server-managed/team-reports.ts +368 -0
  420. package/server-managed/triage-response.ts +16 -0
  421. package/server-managed/type-only-proof.js +161 -0
  422. package/server-managed/type-only-worker.js +31 -0
  423. package/server-managed/type-only.ts +135 -0
  424. package/server-managed/uploads.ts +106 -0
  425. package/server-managed/upstream-cache.ts +256 -0
  426. package/server-managed/view-as.ts +58 -0
  427. package/server-managed/worker-turns.ts +76 -0
  428. package/server-managed/workspace-shares.ts +170 -0
  429. package/server.ts +70 -0
  430. package/strip-types-loader.js +13 -10
  431. package/server/index.ts +0 -480
  432. package/server/lifecycle.ts +0 -208
  433. /package/{LICENSE → LICENSE-MIT} +0 -0
  434. /package/{server → server-e2e}/auth.ts +0 -0
  435. /package/{server → server-e2e}/config.example.json +0 -0
  436. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  437. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  438. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  439. /package/{server → server-e2e}/peer.ts +0 -0
  440. /package/{server → server-e2e}/sse-session.ts +0 -0
  441. /package/{server → server-e2e}/util.ts +0 -0
  442. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,22 @@
1
+ // Table identifiers are code constants. Renames retain rows and foreign keys;
2
+ // an ambiguous old/new pair must be resolved before the server can start.
3
+ const MANAGED_TABLE_RENAMES = [
4
+ ['selected_repo', 'managed_selected_repo'],
5
+ ['team_repo', 'managed_team_repo'],
6
+ ['team_user', 'managed_team_user'],
7
+ ['finding_triage', 'managed_finding_triage'],
8
+ ['finding_triage_event', 'managed_finding_triage_event'],
9
+ ['finding_comment', 'managed_finding_comment'],
10
+ ['finding_comment_event', 'managed_finding_comment_event'],
11
+ ] as const
12
+
13
+ export function managedTableRenames(tables: Set<string>) {
14
+ // A fresh installation must not claim similarly named unrelated tables in
15
+ // a shared database. managed_user anchors an existing managed installation.
16
+ if (!tables.has('managed_user')) return []
17
+ const renames = MANAGED_TABLE_RENAMES.filter(([from]) => tables.has(from))
18
+ for (const [from, to] of renames) {
19
+ if (tables.has(to)) throw new Error(`Cannot migrate managed tables: both ${from} and ${to} exist`)
20
+ }
21
+ return renames
22
+ }
@@ -0,0 +1,149 @@
1
+ // SQLite bootstrap and legacy upgrades. Runtime methods are shared with Neon.
2
+ import { mkdirSync } from 'node:fs'
3
+ import { dirname, join } from 'node:path'
4
+ import { DatabaseSync } from 'node:sqlite'
5
+ import { migrateSlugs } from './slugs.ts'
6
+ import { migrateReportLocations } from './report-migration.ts'
7
+ import { initCommentMethods } from './comments.ts'
8
+ import { initActivityMethods } from './activity.ts'
9
+ import { revisionSchema } from './revisions.ts'
10
+ import { MANAGED_SCHEMA, REPORT_OPENING_COLUMNS, REPO_UPLOAD_INDEXES, VIEW_SESSION_INDEX } from './db-schema.ts'
11
+ import { GITHUB_LINK_USER_COLUMNS } from './github-links.ts'
12
+ import { REPOSITORY_DEPENDENCY_REVIEW_COLUMNS } from './repository-dependency-reviews.ts'
13
+ import { DEPENDENCY_REVIEW_COLUMNS, DEPENDENCY_REVIEW_INDEXES } from './dependency-reviews.ts'
14
+ import { STORAGE_SCHEMA } from './storage-db.ts'
15
+ import { GITHUB_COMMIT_SCHEMA, GITHUB_METADATA_SCHEMA, GITHUB_STATE_REASON_COLUMN } from './github-metadata.ts'
16
+ import { MANAGED_ISSUE_SCHEMA } from './managed-issues.ts'
17
+ import { BUNDLE_BUILD_LEASE_SCHEMA } from './bundle-build-leases.ts'
18
+ import { UPSTREAM_CACHE_SCHEMA } from './upstream-cache.ts'
19
+ import { TEAM_APP_SUMMARY_SCHEMA } from './team-app-summaries.ts'
20
+ import { managedTableRenames } from './db-table-names.ts'
21
+ import { type ManagedDb, type ManagedDbOptions, createManagedMethods } from './db-methods.ts'
22
+ import { createSqliteDriver, scopeManagedMethods, sqliteTransaction } from './sql.ts'
23
+ export type * from './db-methods.ts'
24
+
25
+ function migrateManagedTableNames(db: DatabaseSync): void {
26
+ sqliteTransaction(db, 'BEGIN IMMEDIATE', () => {
27
+ db.exec('CREATE TABLE IF NOT EXISTS managed_schema_version (version INTEGER PRIMARY KEY) STRICT;')
28
+ if (!db.prepare('SELECT version FROM managed_schema_version WHERE version = 3').get()) {
29
+ const rows = db.prepare("SELECT name FROM sqlite_schema WHERE type = 'table'").all() as { name: string }[]
30
+ for (const [from, to] of managedTableRenames(new Set(rows.map(row => row.name)))) {
31
+ db.exec(`ALTER TABLE ${from} RENAME TO ${to}`)
32
+ }
33
+ db.exec('INSERT INTO managed_schema_version VALUES (3)')
34
+ }
35
+ })
36
+ }
37
+
38
+ // Preserve the legacy single-path links while adding path to their identity.
39
+ function migrateTeamRepoPaths(db: DatabaseSync): void {
40
+ const columns = db.prepare('PRAGMA table_info(managed_team_repo)').all() as { name: string; pk: number }[]
41
+ if (columns.some(column => column.name === 'path' && column.pk === 3)) return
42
+ sqliteTransaction(db, 'BEGIN IMMEDIATE', () => db.exec(`CREATE TABLE managed_team_repo_paths (
43
+ team_id TEXT NOT NULL REFERENCES managed_team(id) ON DELETE CASCADE,
44
+ repo_id INTEGER NOT NULL REFERENCES managed_selected_repo(repo_id) ON DELETE CASCADE,
45
+ path TEXT NOT NULL DEFAULT '', PRIMARY KEY (team_id, repo_id, path)
46
+ ) STRICT;
47
+ INSERT INTO managed_team_repo_paths SELECT team_id, repo_id, COALESCE(path, '') FROM managed_team_repo;
48
+ DROP TABLE managed_team_repo;
49
+ ALTER TABLE managed_team_repo_paths RENAME TO managed_team_repo;
50
+ CREATE INDEX team_repo_repo_idx ON managed_team_repo(repo_id);`))
51
+ }
52
+
53
+ // Add `column` to `table` if it's missing (a lightweight migration for DBs that
54
+ // predate the column; `table`/`column` are code constants, never user input).
55
+ function ensureColumn(db: DatabaseSync, table: string, column: string, type: string): boolean {
56
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]
57
+ if (cols.some((c) => c.name === column)) return false
58
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`)
59
+ return true
60
+ }
61
+
62
+ export function openSqliteManagedDb(path: string, options: ManagedDbOptions = {}): ManagedDb {
63
+ mkdirSync(dirname(path), { recursive: true })
64
+ const db = new DatabaseSync(path)
65
+ try {
66
+ db.exec('PRAGMA journal_mode = WAL;')
67
+ // The bootstrap below commits each schema statement on its own: under
68
+ // FULL, ~120 fsyncs on a new file. Each step checks the schema before
69
+ // changing it and only reads outside the database, so a step lost to a
70
+ // power failure reruns on the next open, and WAL stays consistent under
71
+ // NORMAL. FULL is restored after it; the next commit's fsync of the WAL
72
+ // persists the bootstrap's frames too.
73
+ db.exec('PRAGMA synchronous = NORMAL;')
74
+ db.exec('PRAGMA foreign_keys = ON;')
75
+ migrateManagedTableNames(db)
76
+ db.exec(MANAGED_SCHEMA + GITHUB_METADATA_SCHEMA + GITHUB_COMMIT_SCHEMA + MANAGED_ISSUE_SCHEMA + STORAGE_SCHEMA + BUNDLE_BUILD_LEASE_SCHEMA + UPSTREAM_CACHE_SCHEMA + TEAM_APP_SUMMARY_SCHEMA)
77
+ ensureColumn(db, 'managed_selected_repo', 'cached_default_branch', 'TEXT')
78
+ ensureColumn(db, 'managed_session', 'upload_key', 'TEXT')
79
+ ensureColumn(db, 'managed_session', 'viewer_session', 'TEXT REFERENCES managed_session(id) ON DELETE CASCADE')
80
+ db.exec(VIEW_SESSION_INDEX)
81
+ for (const table of ['managed_report', 'managed_bundle']) {
82
+ ensureColumn(db, table, 'data_key', 'TEXT')
83
+ ensureColumn(db, table, 'storage_encrypted', 'INTEGER NOT NULL DEFAULT 0')
84
+ }
85
+ ensureColumn(db, 'managed_user', 'gh_tokens_encrypted', 'INTEGER NOT NULL DEFAULT 0')
86
+ // Existing names are the sign-in accounts' own: none was chosen yet.
87
+ for (const [column, type] of GITHUB_LINK_USER_COLUMNS) {
88
+ if (ensureColumn(db, 'managed_user', column, type) && column === 'github_name') db.exec('UPDATE managed_user SET github_name = name')
89
+ }
90
+ ensureColumn(db, 'managed_github_metadata', 'state_reason', GITHUB_STATE_REASON_COLUMN)
91
+ ensureColumn(db, 'managed_github_metadata', 'attempted_at', 'INTEGER')
92
+ // Existing public links must opt in too; never preserve an implicit grant.
93
+ ensureColumn(db, 'managed_workspace_share', 'dependencies', 'INTEGER NOT NULL DEFAULT 0')
94
+ ensureColumn(db, 'managed_workspace_share', 'security', 'INTEGER NOT NULL DEFAULT 0')
95
+ migrateTeamRepoPaths(db)
96
+ migrateSlugs(db)
97
+ // Migrate DBs created before a column existed (CREATE TABLE IF NOT EXISTS
98
+ // never alters an already-present table). Idempotent — skipped on fresh DBs.
99
+ const addedLastSeen = ensureColumn(db, 'managed_user', 'last_seen_at', 'INTEGER')
100
+ if (addedLastSeen) {
101
+ // Session creation is known authentication activity. updated_at is not:
102
+ // role changes and token refreshes also wrote it. Keep unknowns NULL.
103
+ db.exec(`UPDATE managed_user SET last_seen_at = (
104
+ SELECT MAX(s.created_at) FROM managed_session s WHERE s.user_id = managed_user.id
105
+ )`)
106
+ }
107
+ ensureColumn(db, 'managed_report', 'uploaded_by_login', 'TEXT')
108
+ ensureColumn(db, 'managed_report', 'repo_embedded', 'INTEGER NOT NULL DEFAULT 0')
109
+ migrateReportLocations(db, join(dirname(path), 'reports'))
110
+ ensureColumn(db, 'managed_report', 'analyzer', 'TEXT')
111
+ // Existing reports are read for it as the reports page lists them
112
+ // (report-opening.ts), and none was switched yet.
113
+ for (const [column, type] of REPORT_OPENING_COLUMNS) ensureColumn(db, 'managed_report', column, type)
114
+ // Existing rows predate publication controls and were already visible.
115
+ // Backfill only when adding the column; newly inserted rows still use the
116
+ // hidden default and must be explicitly published.
117
+ const addedVisible = ensureColumn(db, 'managed_report', 'visible', 'INTEGER NOT NULL DEFAULT 0')
118
+ if (addedVisible) db.prepare('UPDATE managed_report SET visible = 1 WHERE visible = 0').run()
119
+ ensureColumn(db, 'managed_bundle', 'uploaded_by_login', 'TEXT')
120
+ ensureColumn(db, 'managed_bundle', 'repo_directory', "TEXT NOT NULL DEFAULT ''")
121
+ db.exec(REPO_UPLOAD_INDEXES)
122
+ ensureColumn(db, 'managed_bundle', 'visible', 'INTEGER NOT NULL DEFAULT 1')
123
+ // Existing rows stay NULL (unknown): some may have been built on the server.
124
+ ensureColumn(db, 'managed_bundle', 'provenance', 'TEXT')
125
+ ensureColumn(db, 'managed_bundle', 'build_conditions', 'TEXT')
126
+ ensureColumn(db, 'managed_team', 'hidden', 'INTEGER NOT NULL DEFAULT 0')
127
+ ensureColumn(db, 'managed_team', 'dependency_review', 'INTEGER NOT NULL DEFAULT 0')
128
+ ensureColumn(db, 'managed_finding_issue', 'auto_fix_url', 'TEXT')
129
+ ensureColumn(db, 'managed_finding_issue', 'auto_fix_checked_at', 'INTEGER')
130
+ ensureColumn(db, 'managed_finding_issue', 'duplicate_of_url', 'TEXT')
131
+ ensureColumn(db, 'managed_selected_repo', 'active', 'INTEGER NOT NULL DEFAULT 1')
132
+ for (const [column, type] of REPOSITORY_DEPENDENCY_REVIEW_COLUMNS) ensureColumn(db, 'managed_selected_repo', column, type)
133
+ for (const [column, type] of DEPENDENCY_REVIEW_COLUMNS) ensureColumn(db, 'managed_dependency_review', column, type)
134
+ db.exec(DEPENDENCY_REVIEW_INDEXES)
135
+ ensureColumn(db, 'managed_finding_triage_event', 'report_id', 'TEXT')
136
+ ensureColumn(db, 'managed_finding_triage_event', 'report', 'TEXT')
137
+ ensureColumn(db, 'managed_finding_triage_event', 'repo', 'TEXT')
138
+ initCommentMethods(db)
139
+ initActivityMethods(db)
140
+ db.exec(revisionSchema())
141
+ db.exec('PRAGMA synchronous = FULL;')
142
+ } catch (err) {
143
+ try { db.close() } catch {}
144
+ throw err
145
+ }
146
+
147
+ const driver = createSqliteDriver(db)
148
+ return scopeManagedMethods(createManagedMethods(driver, options), driver)
149
+ }
@@ -0,0 +1,61 @@
1
+ // A repository's Dependabot alerts for a repository risk scan, read with the
2
+ // App's installation token where the admin's own access lets them see them on
3
+ // GitHub, as doc/bundles.md's repository risk scan section tells.
4
+ import type { ManagedConfig } from './config.ts'
5
+ import type { SelectedRepo } from './db.ts'
6
+ import { type DependabotAlert, dependabotAlerts } from './dependabot-alerts.ts'
7
+ import { type GithubIdentity, githubRepoPermission, repoAccessToken, repositoryInstallation } from './github-app.ts'
8
+ import { GithubApiError } from './github-errors.ts'
9
+
10
+ // The levels GitHub lets see a repository's Dependabot alerts by default
11
+ // (maintain's reads `write`).
12
+ const SEES_ALERTS: ReadonlySet<string> = new Set(['admin', 'write'])
13
+ // Failures of verifying the sign-in that are the sign-in's own: no token, or
14
+ // one of another account (repository-browser.ts getIdentity), or one GitHub no
15
+ // longer takes. Any other, as GitHub failing to answer, is told as it is.
16
+ const UNVERIFIED: ReadonlySet<string> = new Set(['no-repository', 'github-unauthorized'])
17
+
18
+ // What of a repository's reader (repository-browser.ts) the alerts are asked
19
+ // with: the user's verified identity, and their permission level where its
20
+ // access gate asked GitHub of it already.
21
+ export interface AlertsReader {
22
+ identity(): Promise<GithubIdentity>
23
+ permission(): string | null
24
+ }
25
+
26
+ // Alerts read, and their `recheck`: the user's access to them checked again,
27
+ // asked of GitHub afresh, just before they are told (repository-risk.ts), as
28
+ // access to the repository is, as it may be withdrawn meanwhile.
29
+ export interface AlertsRead { alerts: DependabotAlert[]; recheck(): Promise<void> }
30
+
31
+ // `repo`'s Dependabot alerts (dependabot-alerts.ts), read with the token of
32
+ // the App's installation GitHub tells covers it now, its token checked to read
33
+ // it (github-app.ts repositoryInstallation), never the one its connection
34
+ // keeps, which may no longer cover it, once the user's own permission on it
35
+ // lets them see them; else refused, the alerts not asked:
36
+ // `dependabot-not-installed`, `dependabot-unverified`, or
37
+ // `dependabot-forbidden`, naming their permission. The token is asked each
38
+ // time of repoAccessToken, which renews it before it expires, as the recheck
39
+ // may come long after the alerts are read.
40
+ export async function appDependabotAlerts(config: ManagedConfig, repo: Pick<SelectedRepo, 'repoId' | 'fullName'>, reader: AlertsReader,
41
+ fetchImpl: typeof fetch = globalThis.fetch): Promise<AlertsRead> {
42
+ const id = await repositoryInstallation(config, repo.repoId, repo.fullName, fetchImpl)
43
+ const tokenNow = async () => {
44
+ const token = await repoAccessToken(config, id, fetchImpl)
45
+ if (token == null) throw new GithubApiError(403, 'dependabot-not-installed')
46
+ return token
47
+ }
48
+ const token = await tokenNow()
49
+ let who
50
+ try { who = await reader.identity() } catch (error) {
51
+ throw error instanceof GithubApiError && UNVERIFIED.has(error.message) ? new GithubApiError(403, 'dependabot-unverified') : error
52
+ }
53
+ const seen = (permission: string) => {
54
+ if (!SEES_ALERTS.has(permission)) {
55
+ throw new GithubApiError(403, 'dependabot-forbidden', null, `@${who.login}'s access to this repository (${permission}) doesn't let them see its Dependabot alerts on GitHub`)
56
+ }
57
+ }
58
+ seen(reader.permission() ?? await githubRepoPermission(repo.fullName, token, who, fetchImpl))
59
+ const alerts = await dependabotAlerts(repo.fullName, token, fetchImpl)
60
+ return { alerts, recheck: async () => { seen(await githubRepoPermission(repo.fullName, await tokenNow(), who, fetchImpl)) } }
61
+ }
@@ -0,0 +1,180 @@
1
+ // A repository's Dependabot alerts of npm's ecosystem, open or dismissed, as a
2
+ // repository risk scan blends them into npm's advisories (repository-risk.ts),
3
+ // a dismissed one with who dismissed it, when and why: GitHub's
4
+ // `GET /repos/:repo/dependabot/alerts`, a page of 100 at a time, each found by
5
+ // the cursor the one before's Link header names, MAX_PAGES at most. Asked with
6
+ // the App's installation token, once the admin's own access to the repository
7
+ // is found to let them see the alerts on GitHub (dependabot-access.ts): where
8
+ // the installation hasn't Dependabot alerts: read, or the repository has them
9
+ // off, that is thrown as its code, never GitHub's text, for the scan to tell
10
+ // and go on.
11
+ import { isExactVersion, satisfies, validRange } from '@preventive/upstream/semver.js'
12
+ import { isNpmPackageName } from '../common/managed/npm-packages.js'
13
+ import { GithubApiError, githubUnreachable, throwGithubResponseError } from './github-errors.ts'
14
+ import { GITHUB_API, encodedPath, githubHeaders, repoApi } from './github-requests.ts'
15
+ import { LOGIN, isId } from './github-values.ts'
16
+ import type { LockedPackage } from './locked-packages.ts'
17
+
18
+ // An alert, as GitHub has it: its `number` in its repository and its page
19
+ // there (`url`, built, never fetched), the manifest or lockfile it is of
20
+ // (`manifest`, from the repository's root), its package and advisory, the
21
+ // versions it affects as GitHub writes them (`range`, `>= 1.0.0, < 1.2.6`)
22
+ // and the first that isn't (`patched`), `dev` where GitHub tells the
23
+ // dependency is only for development, and `dismissed` where it is: by whom,
24
+ // when, why and what they said, or by one of the repository's rules (`auto`).
25
+ export interface DependabotAlert {
26
+ number: number
27
+ url: string
28
+ manifest: string
29
+ name: string
30
+ ghsa: string
31
+ // The advisory's other ids, as its CVE.
32
+ aliases: string[]
33
+ title?: string
34
+ // `critical`, `high`, `moderate`, `low`: GitHub's `medium` reads `moderate`.
35
+ severity?: string
36
+ range?: string
37
+ patched?: string
38
+ cwe: string[]
39
+ dev?: true
40
+ dismissed?: AlertDismissal
41
+ }
42
+
43
+ // GitHub's `dismissed_reason`: `fix_started`, `inaccurate`, `no_bandwidth`,
44
+ // `not_used` or `tolerable_risk`; `at` as GitHub writes it (ISO 8601).
45
+ export interface AlertDismissal { auto?: true; reason?: string; at?: string; by?: string; comment?: string }
46
+
47
+ const PER_PAGE = 100
48
+ // Up to how many pages a listing asks: 2,000 alerts of npm's in a repository,
49
+ // past which the rest are left out; where open and dismissed ones are more,
50
+ // the open ones are listed again on their own (dependabotAlerts).
51
+ const MAX_PAGES = 20
52
+ // A page holds each advisory's whole text: given longer than githubJson's.
53
+ const PAGE_TIMEOUT_MS = 20_000
54
+ const GHSA = /^GHSA(?:-[23456789cfghjmpqrvwx]{4}){3}$/u
55
+ const SEVERITIES = new Map([['critical', 'critical'], ['high', 'high'], ['medium', 'moderate'], ['moderate', 'moderate'], ['low', 'low']])
56
+ // A path from a repository's root, as git takes one: no empty, `.` or `..`
57
+ // component, nor a control character.
58
+ const isRepoPath = (path: unknown): path is string => typeof path === 'string' && path.length <= 1024 && !/\p{Cc}/u.test(path)
59
+ && path.split('/').every(part => part !== '' && part !== '.' && part !== '..')
60
+
61
+ // The states asked: a fixed alert's dependency is no longer what it was.
62
+ const STATES = ['open', 'dismissed', 'auto_dismissed']
63
+ const REASONS = new Set(['fix_started', 'inaccurate', 'no_bandwidth', 'not_used', 'tolerable_risk'])
64
+
65
+ const text = (value: unknown, most = 500) => typeof value === 'string' && value.trim() ? value.trim().slice(0, most) : undefined
66
+
67
+ // How a dismissed alert was dismissed, as far as GitHub tells it soundly.
68
+ function dismissalOf(state: string, raw: Record<string, any>): AlertDismissal {
69
+ const at = state === 'auto_dismissed' ? raw['auto_dismissed_at'] : raw['dismissed_at']
70
+ const when = typeof at === 'string' && at.length <= 40 && !Number.isNaN(Date.parse(at)) ? { at } : {}
71
+ if (state === 'auto_dismissed') return { auto: true, ...when }
72
+ const by = raw['dismissed_by']?.login, comment = text(raw['dismissed_comment'], 280), reason = raw['dismissed_reason']
73
+ return { ...REASONS.has(reason) ? { reason } : {}, ...when, ...typeof by === 'string' && LOGIN.test(by) ? { by } : {}, ...comment === undefined ? {} : { comment } }
74
+ }
75
+
76
+ // An alert as GitHub answers it, or null for one that isn't an open or
77
+ // dismissed one of npm's, of a package and GHSA npm and GitHub would name.
78
+ function alertOf(fullName: string, raw: unknown): DependabotAlert | null {
79
+ if (raw == null || typeof raw !== 'object') return null
80
+ const { number, state, dependency, security_advisory: advisory, security_vulnerability: vulnerability } = raw as Record<string, any>
81
+ if (!isId(number) || !STATES.includes(state)) return null
82
+ const ghsa = advisory?.ghsa_id, manifest = dependency?.manifest_path, name = dependency?.package?.name
83
+ if (dependency?.package?.ecosystem !== 'npm' || !isNpmPackageName(name) || !isRepoPath(manifest) || typeof ghsa !== 'string' || !GHSA.test(ghsa)) return null
84
+ const severity = SEVERITIES.get(vulnerability?.severity ?? advisory?.severity)
85
+ const patched = text(vulnerability?.first_patched_version?.identifier, 100), range = text(vulnerability?.vulnerable_version_range, 200), title = text(advisory?.summary)
86
+ const ids = Array.isArray(advisory?.identifiers) ? advisory.identifiers as { value?: unknown }[] : []
87
+ const cwes = Array.isArray(advisory?.cwes) ? advisory.cwes as { cwe_id?: unknown }[] : []
88
+ return {
89
+ number, url: `https://github.com/${encodedPath(fullName)}/security/dependabot/${number}`, manifest, name, ghsa,
90
+ aliases: [...new Set(ids.flatMap(id => typeof id?.value === 'string' && /^[\w.:-]{1,64}$/u.test(id.value) && id.value !== ghsa ? [id.value] : []))],
91
+ ...title === undefined ? {} : { title }, ...severity === undefined ? {} : { severity },
92
+ ...range === undefined ? {} : { range }, ...patched === undefined ? {} : { patched },
93
+ cwe: [...new Set(cwes.flatMap(cwe => typeof cwe?.cwe_id === 'string' && /^CWE-\d{1,6}$/u.test(cwe.cwe_id) ? [cwe.cwe_id] : []))],
94
+ ...dependency.scope === 'development' ? { dev: true as const } : {},
95
+ ...state === 'open' ? {} : { dismissed: dismissalOf(state, raw as Record<string, any>) },
96
+ }
97
+ }
98
+
99
+ // The next page's cursor, as the Link header's `next` names it: its `after`,
100
+ // or its `page`, all that is taken of it, the rest of its URL left as asked.
101
+ function nextPage(link: string | null): [string, string] | null {
102
+ const next = link?.split(',').map(part => /^\s*<([^>]*)>\s*;\s*rel="next"\s*$/u.exec(part)?.[1]).find(Boolean)
103
+ if (!next) return null
104
+ let url
105
+ try { url = new URL(next) } catch { return null }
106
+ if (url.origin !== GITHUB_API) return null
107
+ const after = url.searchParams.get('after'), page = url.searchParams.get('page')
108
+ return after ? ['after', after] : page && /^\d{1,4}$/u.test(page) ? ['page', page] : null
109
+ }
110
+
111
+ // A page asked of GitHub: its alerts and the headers they came with. A 403
112
+ // that isn't a rate limit is told as the alerts being off
113
+ // (`dependabot-disabled`) or not to be read by the App's installation
114
+ // (`dependabot-app-permission`), as a 404 is, the repository found just
115
+ // before; the rest as githubJson tells them.
116
+ async function askPage(url: string, token: string, fetchImpl: typeof fetch): Promise<{ alerts: unknown[]; link: string | null }> {
117
+ const started = Date.now()
118
+ let res: Response
119
+ try {
120
+ res = await fetchImpl(url, { signal: AbortSignal.timeout(PAGE_TIMEOUT_MS), redirect: 'error', headers: githubHeaders(token) })
121
+ } catch (error) { throw githubUnreachable(error, started) }
122
+ if (res.status === 403) {
123
+ const message = (await res.clone().json().catch(() => null) as { message?: unknown } | null)?.message
124
+ const limited = res.headers.get('x-ratelimit-remaining') === '0' || res.headers.has('retry-after')
125
+ || (typeof message === 'string' && /rate limit|abuse detection/iu.test(message))
126
+ if (!limited) throw new GithubApiError(403, typeof message === 'string' && /disabled/iu.test(message) ? 'dependabot-disabled' : 'dependabot-app-permission')
127
+ }
128
+ if (res.status === 404) throw new GithubApiError(403, 'dependabot-app-permission')
129
+ if (!res.ok) await throwGithubResponseError(res)
130
+ let body
131
+ try { body = await res.json() } catch (error) {
132
+ throw error instanceof SyntaxError ? new GithubApiError(502, 'github-malformed') : githubUnreachable(error, started)
133
+ }
134
+ if (!Array.isArray(body)) throw new GithubApiError(502, 'github-malformed')
135
+ return { alerts: body, link: res.headers.get('link') }
136
+ }
137
+
138
+ // `fullName`'s alerts in `states`, MAX_PAGES at most, in GitHub's order (the
139
+ // newest first), and whether that is all of them.
140
+ async function listAlerts(fullName: string, states: readonly string[], token: string, fetchImpl: typeof fetch) {
141
+ const base = `${repoApi(fullName)}/dependabot/alerts`
142
+ const alerts: DependabotAlert[] = []
143
+ const seen = new Set<number>()
144
+ let cursor: [string, string] | null = null
145
+ for (let pages = 0; pages < MAX_PAGES; pages++) {
146
+ const query = new URLSearchParams({ state: states.join(','), ecosystem: 'npm', per_page: String(PER_PAGE), ...cursor ? { [cursor[0]]: cursor[1] } : {} })
147
+ const answer = await askPage(`${base}?${query}`, token, fetchImpl)
148
+ for (const raw of answer.alerts) {
149
+ const alert = alertOf(fullName, raw)
150
+ if (alert && !seen.has(alert.number)) { seen.add(alert.number); alerts.push(alert) }
151
+ }
152
+ cursor = answer.alerts.length === 0 ? null : nextPage(answer.link)
153
+ if (!cursor) return { alerts, whole: true }
154
+ }
155
+ return { alerts, whole: false }
156
+ }
157
+
158
+ // `fullName`'s Dependabot alerts of npm's ecosystem, open or dismissed, as
159
+ // `token`, the App's installation's (dependabot-access.ts), may see them, in
160
+ // GitHub's order. Asked at once, but where they are more than a listing holds,
161
+ // as newer dismissed ones would leave older open ones out, the open ones are
162
+ // listed again on their own, and the dismissed ones had kept after them.
163
+ export async function dependabotAlerts(fullName: string, token: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<DependabotAlert[]> {
164
+ const all = await listAlerts(fullName, STATES, token, fetchImpl)
165
+ if (all.whole) return all.alerts
166
+ const open = await listAlerts(fullName, ['open'], token, fetchImpl)
167
+ const told = new Set(open.alerts.map(alert => alert.number))
168
+ return [...open.alerts, ...all.alerts.filter(alert => alert.dismissed && !told.has(alert.number))]
169
+ }
170
+
171
+ // The versions of an alert's package that a lockfile it is of locks
172
+ // (`packages`) and its range covers, GitHub's read as npm's semver reads its
173
+ // own (`>= 1.0.0, < 1.2.6` as `>= 1.0.0 < 1.2.6`); none where it is of no
174
+ // lockfile read, or its range is none semver reads.
175
+ export function alertVersions(alert: Pick<DependabotAlert, 'name' | 'range'>, packages: readonly LockedPackage[] | undefined): string[] {
176
+ const range = alert.range === undefined ? null : validRange(alert.range.replaceAll(',', ' '))
177
+ if (!packages || range === null) return []
178
+ return [...new Set(packages.flatMap(({ name, version, source }) => name === alert.name && (source === 'registry' || source === 'mirror')
179
+ && isExactVersion(version) && satisfies(version, range) ? [version] : []))]
180
+ }
@@ -0,0 +1,158 @@
1
+ // The comment a host formats of one's own dependency reviews, for a copy
2
+ // button to give (reviewed-dependencies.ts `formatDependencyReviews`): of each
3
+ // of one's reviews, as their lists and the review page show them
4
+ // (`withFormatted`), and of those of the versions an open pull request adds
5
+ // (`formattedPull`), but the versions the host's `lookup` passes already,
6
+ // which want no review there, and those one's own comments there review
7
+ // alike already. It is given one's own published reviews alone, never
8
+ // another's, a draft or a revoked one, however it is asked (`formatOwn`, the
9
+ // only caller of the hook); and is told of none where it answers nothing, or
10
+ // fails, which is logged.
11
+ import type { DependencyReview, DependencyReviewStore } from './dependency-reviews.ts'
12
+ import type { LockedPackage } from './locked-packages.ts'
13
+ import type { PullDependencies } from './pull-dependencies.ts'
14
+ import { ACCEPTING, askedOf, basesOf, comparedWith, latestOf, reviewsByVersion, reviewsOf } from './pull-dependency-reviews.ts'
15
+ import { eachOf } from './queue.ts'
16
+ import type { PublishedReview, RepoReviewState } from './repository-dependency-reviews.ts'
17
+ import { type DependencyReviewEntry, type ReviewVerdict, type ReviewedBase, type ReviewedDependencies, askReviewed } from './reviewed-dependencies.ts'
18
+
19
+ const FORMAT_AT_ONCE = 8
20
+ // The longest comment told, past which none is.
21
+ const MAX_FORMATTED = 1_000_000
22
+ // The reviews of a pull request's versions read at once, those past them
23
+ // read after, every one formatted.
24
+ const REVIEWS_AT_ONCE = 200
25
+
26
+ // `review` as the hook is given it: each version with the integrity and
27
+ // shasum the review keeps of the tarball it read, and the patch it is of,
28
+ // where it is a patched one's.
29
+ function entryOf(review: DependencyReview): DependencyReviewEntry {
30
+ return { ecosystem: 'npm', old: review.basePackage === null ? null : { name: review.basePackage, version: review.baseVersion ?? '', integrity: review.baseIntegrity ?? '',
31
+ ...review.baseShasum ? { shasum: review.baseShasum } : {}, ...review.basePatchHash ? { patchHash: review.basePatchHash } : {} },
32
+ new: { name: review.package, version: review.version, integrity: review.integrity, ...review.shasum ? { shasum: review.shasum } : {},
33
+ ...review.patchHash ? { patchHash: review.patchHash } : {} },
34
+ status: review.status!, coverage: review.coverage === 'full' ? 'full' : 'partial', comment: review.comment,
35
+ files: review.entries.filter(entry => entry.status !== null || entry.comment.trim() !== '').map(entry => ({ path: entry.file, status: entry.status, comment: entry.comment })),
36
+ reviewer: review.userLogin, publishedAt: review.publishedAt! }
37
+ }
38
+
39
+ // Whether `review` is `user`'s own, published, not revoked, with its verdict.
40
+ const ownPublished = (review: DependencyReview, user: string) => review.user === user && review.publishedAt !== null && review.revokedAt === null && review.status !== null
41
+
42
+ // What the host formats of `reviews`, of them `user`'s own published ones
43
+ // alone, and the pull request they are of the versions of, where it is
44
+ // one's; none where it formats none of them.
45
+ async function formatOwn(reviewed: ReviewedDependencies | null, user: string, reviews: DependencyReview[],
46
+ pullRequest?: { repository: string; number: number }): Promise<string | null> {
47
+ const format = reviewed?.formatDependencyReviews
48
+ const own = reviews.filter(review => ownPublished(review, user))
49
+ if (!format || own.length === 0) return null
50
+ try {
51
+ const text = await format({ reviews: own.map(entryOf), ...pullRequest ? { pullRequest } : {} })
52
+ return typeof text === 'string' && text.trim() !== '' && text.length <= MAX_FORMATTED ? text : null
53
+ } catch (error) {
54
+ console.warn('reviewed dependencies: failed to format dependency reviews', error instanceof Error ? error.message : error)
55
+ return null
56
+ }
57
+ }
58
+
59
+ // `reviews`, each of `user`'s own with the comment the host formats of it
60
+ // (`formatted`), where it formats one; another's never asked of.
61
+ export function withFormatted<T extends DependencyReview>(reviewed: ReviewedDependencies | null, user: string, reviews: T[]): Promise<(T & { formatted?: string })[]> {
62
+ if (!reviewed?.formatDependencyReviews) return Promise.resolve(reviews)
63
+ return eachOf(reviews, FORMAT_AT_ONCE, async review => {
64
+ const formatted = ownPublished(review, user) ? await formatOwn(reviewed, user, [review]) : null
65
+ return formatted ? { ...review, formatted } : review
66
+ })
67
+ }
68
+
69
+ // `user`'s review of each version `told` adds that stands for them on it, as
70
+ // its lockfiles lock each, of `reviews` of its version, of an integrity it is
71
+ // locked with and of its patch (pull-dependency-reviews.ts reviewsOf,
72
+ // stancesOf), by their ids, each with the versions it is given of: their
73
+ // latest of it alone, where it is compared with what it may be, whole,
74
+ // compared with another package's version, or compared with a version it was
75
+ // or the base the host names it (`bases`; comparedWith, basesOf), or, `any`,
76
+ // with any version of its package. Else their latest of it that is, where it
77
+ // accepts it as their latest does, which then passes it still; never one
78
+ // before a latest not accepting it, whatever that was compared with, as it
79
+ // holds them all.
80
+ interface Own { review: PublishedReview; pkgs: LockedPackage[] }
81
+ // What a verdict does to a version's review, as pull-dependency-reviews.ts
82
+ // stancesOf counts it: passes it, holds it rejected, or passes it by none.
83
+ const effectOf = (status: ReviewVerdict) => ACCEPTING.has(status) ? 'passes' : status === 'reject' ? 'holds' : 'withholds'
84
+ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string, any: boolean, bases: Map<string, ReviewedBase>): Map<string, Own> {
85
+ // Theirs by the version they are of, each version probed once.
86
+ const theirs = reviewsByVersion(reviews.filter(review => review.id !== undefined && review.reviewer === user))
87
+ const mine = new Map<string, Own>()
88
+ if (theirs.size === 0) return mine
89
+ for (const pkg of told.lockfiles.flatMap(dir => 'added' in dir ? dir.added : [])) {
90
+ const of = reviewsOf(pkg, theirs)
91
+ const against = any ? 'any' : basesOf(pkg, bases.get(askedOf(pkg)[0]) ?? null)
92
+ const compared = of.filter(review => comparedWith(review, pkg, against))
93
+ if (compared.length === 0) continue
94
+ const [latest, review] = [latestOf(of), latestOf(compared)]
95
+ if (review === latest || (ACCEPTING.has(latest.status) && ACCEPTING.has(review.status))) {
96
+ (mine.get(review.id!) ?? mine.set(review.id!, { review, pkgs: [] }).get(review.id!)!).pkgs.push(pkg)
97
+ }
98
+ }
99
+ return mine
100
+ }
101
+
102
+ // The comment the host formats of `user`'s reviews of the versions pull
103
+ // request `number` of `repository` adds (`told`), those its review's state
104
+ // tells of, published to a team counting for it; none where it has none.
105
+ // Of each version, as locked, the one review of `user`'s that stands for
106
+ // them on it is given (ownOfPull), their latest, never those it revises: a
107
+ // comment of them all would tell two verdicts, or comments, of it. A review
108
+ // is left out where every version it is given of wants no comment of it
109
+ // there, as copying it would but repeat what `user` posted there, or undo a
110
+ // later word of theirs holding it: the host's `lookup` passes it already; or
111
+ // `user`'s own comments there (of `commented`, the reviews its comments
112
+ // make) stand on it, by their latest of it, the first of those as late (as
113
+ // pull-dependency-reviews.ts stancesOf reads them), as it does (effectOf):
114
+ // accepting it with nits or without alike, as a host may read one verdict of
115
+ // a comment for each version it tells, which posting it again would but
116
+ // repeat. Or, later than it, they don't accept what it accepts, but where
117
+ // those as late tell its verdict too, posted beside another of an older
118
+ // review, which, standing first, posting it again sets right. A version
119
+ // `lookup` fails to answer of keeps its review. Where the host reads reviews
120
+ // of comments (`parseComments`), what a review was compared with is its to
121
+ // weigh, so one compared with any version is given.
122
+ // With it, the versions it is of (`versions`), as the client tells them:
123
+ // those wanting it, each once, by its name, version and patch, so that one
124
+ // listing them can tell whether it copies any it shows.
125
+ export interface CopiedVersion { name: string; version: string; patch?: { hash: string } }
126
+ export async function formattedPull(reviewed: ReviewedDependencies | null, db: Pick<DependencyReviewStore, 'listOwnDependencyReviewsById'>, user: string,
127
+ told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = [],
128
+ bases: Map<string, ReviewedBase> = new Map()): Promise<{ text: string; versions: CopiedVersion[] } | null> {
129
+ if (!reviewed?.formatDependencyReviews || !state) return null
130
+ const mine = ownOfPull(told, state.reviews, user, reviewed.parseComments !== undefined, bases)
131
+ if (mine.size === 0) return null
132
+ const { passed } = await askReviewed(reviewed.lookup, new Map([...mine.values()].flatMap(({ pkgs }) => pkgs.map(askedOf))))
133
+ const there = reviewsByVersion(commented.filter(review => review.reviewer === user))
134
+ const posted = (review: PublishedReview, pkg: LockedPackage) => {
135
+ const made = reviewsOf(pkg, there)
136
+ if (made.length === 0) return false
137
+ const stance = latestOf(made)
138
+ if (effectOf(stance.status) === effectOf(review.status)) return true
139
+ return stance.time > review.time && !ACCEPTING.has(stance.status) && ACCEPTING.has(review.status)
140
+ && !made.some(one => one.time === stance.time && one.status === review.status)
141
+ }
142
+ // Those wanting a comment of each review given, by its id.
143
+ const wanting = new Map([...mine].map(([id, { review, pkgs }]) => [id, pkgs.filter(pkg => !passed.has(askedOf(pkg)[0]) && !posted(review, pkg))] as const)
144
+ .filter(([, pkgs]) => pkgs.length > 0))
145
+ if (wanting.size === 0) return null
146
+ const ids = [...wanting.keys()]
147
+ const reviews: DependencyReview[] = []
148
+ for (let at = 0; at < ids.length; at += REVIEWS_AT_ONCE) reviews.push(...await db.listOwnDependencyReviewsById(user, ids.slice(at, at + REVIEWS_AT_ONCE)))
149
+ const text = await formatOwn(reviewed, user, reviews, pullRequest)
150
+ if (text === null) return null
151
+ const versions = new Map<string, CopiedVersion>()
152
+ for (const review of reviews.filter(one => ownPublished(one, user))) {
153
+ for (const pkg of wanting.get(review.id) ?? []) {
154
+ versions.set(`${pkg.name}@${pkg.version}\0${pkg.patchHash ?? ''}`, { name: pkg.name, version: pkg.version ?? '', ...pkg.patchHash ? { patch: { hash: pkg.patchHash } } : {} })
155
+ }
156
+ }
157
+ return { text, versions: [...versions.values()] }
158
+ }