@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,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,150 @@
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, TEAM_ICON_COLUMNS, 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
+ for (const [column, type] of TEAM_ICON_COLUMNS) ensureColumn(db, 'managed_team', column, type)
129
+ ensureColumn(db, 'managed_finding_issue', 'auto_fix_url', 'TEXT')
130
+ ensureColumn(db, 'managed_finding_issue', 'auto_fix_checked_at', 'INTEGER')
131
+ ensureColumn(db, 'managed_finding_issue', 'duplicate_of_url', 'TEXT')
132
+ ensureColumn(db, 'managed_selected_repo', 'active', 'INTEGER NOT NULL DEFAULT 1')
133
+ for (const [column, type] of REPOSITORY_DEPENDENCY_REVIEW_COLUMNS) ensureColumn(db, 'managed_selected_repo', column, type)
134
+ for (const [column, type] of DEPENDENCY_REVIEW_COLUMNS) ensureColumn(db, 'managed_dependency_review', column, type)
135
+ db.exec(DEPENDENCY_REVIEW_INDEXES)
136
+ ensureColumn(db, 'managed_finding_triage_event', 'report_id', 'TEXT')
137
+ ensureColumn(db, 'managed_finding_triage_event', 'report', 'TEXT')
138
+ ensureColumn(db, 'managed_finding_triage_event', 'repo', 'TEXT')
139
+ initCommentMethods(db)
140
+ initActivityMethods(db)
141
+ db.exec(revisionSchema())
142
+ db.exec('PRAGMA synchronous = FULL;')
143
+ } catch (err) {
144
+ try { db.close() } catch {}
145
+ throw err
146
+ }
147
+
148
+ const driver = createSqliteDriver(db)
149
+ return scopeManagedMethods(createManagedMethods(driver, options), driver)
150
+ }
@@ -0,0 +1,85 @@
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, listsAlerts } 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`). Others may see them too, by a role the level
12
+ // doesn't tell, as the security manager's: GitHub is asked of those
13
+ // (appDependabotAlerts).
14
+ const SEES_ALERTS: ReadonlySet<string> = new Set(['admin', 'write'])
15
+ // Failures of verifying the sign-in that are the sign-in's own: no token, or
16
+ // one of another account (repository-browser.ts getIdentity), or one GitHub no
17
+ // longer takes. Any other, as GitHub failing to answer, is told as it is.
18
+ const UNVERIFIED: ReadonlySet<string> = new Set(['no-repository', 'github-unauthorized'])
19
+ const unverified = (error: unknown) => error instanceof GithubApiError && UNVERIFIED.has(error.message) ? new GithubApiError(403, 'dependabot-unverified') : error
20
+
21
+ // What of a repository's reader (repository-browser.ts) the alerts are asked
22
+ // with: the user's verified identity, their permission level where its
23
+ // access gate asked GitHub of it already, and their own token, of the App's
24
+ // user authorization, whose account `identity` verifies (null for none).
25
+ export interface AlertsReader {
26
+ identity(): Promise<GithubIdentity>
27
+ permission(): string | null
28
+ userToken(): string | null
29
+ }
30
+
31
+ // Alerts read, and their `recheck`: the user's access to them checked again,
32
+ // asked of GitHub afresh, just before they are told (repository-risk.ts), as
33
+ // access to the repository is, as it may be withdrawn meanwhile.
34
+ export interface AlertsRead { alerts: DependabotAlert[]; recheck(): Promise<void> }
35
+
36
+ // `repo`'s Dependabot alerts (dependabot-alerts.ts), read with the token of
37
+ // the App's installation GitHub tells covers it now, its token checked to read
38
+ // it (github-app.ts repositoryInstallation), never the one its connection
39
+ // keeps, which may no longer cover it, once the user's own access to it lets
40
+ // them see them: their permission level, or else, as a security manager or a
41
+ // custom role isn't told by it, whether GitHub lists the alerts to their own
42
+ // token (listsAlerts), asked only of those their level refuses; else
43
+ // refused, the alerts not asked: `dependabot-not-installed`,
44
+ // `dependabot-unverified`, or `dependabot-forbidden`, naming their
45
+ // permission. The recheck asks GitHub as access was found, by their level or
46
+ // by their own token alone, one request as before. The installation's token
47
+ // is asked each time of repoAccessToken, which renews it before it expires,
48
+ // as the recheck may come long after the alerts are read.
49
+ export async function appDependabotAlerts(config: ManagedConfig, repo: Pick<SelectedRepo, 'repoId' | 'fullName'>, reader: AlertsReader,
50
+ fetchImpl: typeof fetch = globalThis.fetch): Promise<AlertsRead> {
51
+ const id = await repositoryInstallation(config, repo.repoId, repo.fullName, fetchImpl)
52
+ const tokenNow = async () => {
53
+ const token = await repoAccessToken(config, id, fetchImpl)
54
+ if (token == null) throw new GithubApiError(403, 'dependabot-not-installed')
55
+ return token
56
+ }
57
+ const token = await tokenNow()
58
+ let who
59
+ try { who = await reader.identity() } catch (error) { throw unverified(error) }
60
+ const own = reader.userToken()
61
+ // Whether GitHub lists them to the user's own token, else refused, naming
62
+ // their level.
63
+ const listed = async (permission: string) => {
64
+ let found = false
65
+ if (own != null) {
66
+ try { found = await listsAlerts(repo.fullName, own, fetchImpl) } catch (error) { throw unverified(error) }
67
+ }
68
+ if (!found) {
69
+ 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`)
70
+ }
71
+ }
72
+ // Whether access was found by their own token, the level they had then.
73
+ let byOwnToken: string | null = null
74
+ const seen = async (permission: string) => {
75
+ if (SEES_ALERTS.has(permission)) return
76
+ await listed(permission)
77
+ byOwnToken = permission
78
+ }
79
+ await seen(reader.permission() ?? await githubRepoPermission(repo.fullName, token, who, fetchImpl))
80
+ const alerts = await dependabotAlerts(repo.fullName, token, fetchImpl)
81
+ return { alerts, recheck: async () => {
82
+ if (byOwnToken == null) await seen(await githubRepoPermission(repo.fullName, await tokenNow(), who, fetchImpl))
83
+ else await listed(byOwnToken)
84
+ } }
85
+ }
@@ -0,0 +1,197 @@
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
+ // Whether one is listed (listsAlerts): as long as githubJson gives a read.
55
+ const LISTED_TIMEOUT_MS = 10_000
56
+ const GHSA = /^GHSA(?:-[23456789cfghjmpqrvwx]{4}){3}$/u
57
+ const SEVERITIES = new Map([['critical', 'critical'], ['high', 'high'], ['medium', 'moderate'], ['moderate', 'moderate'], ['low', 'low']])
58
+ // A path from a repository's root, as git takes one: no empty, `.` or `..`
59
+ // component, nor a control character.
60
+ const isRepoPath = (path: unknown): path is string => typeof path === 'string' && path.length <= 1024 && !/\p{Cc}/u.test(path)
61
+ && path.split('/').every(part => part !== '' && part !== '.' && part !== '..')
62
+
63
+ // The states asked: a fixed alert's dependency is no longer what it was.
64
+ const STATES = ['open', 'dismissed', 'auto_dismissed']
65
+ const REASONS = new Set(['fix_started', 'inaccurate', 'no_bandwidth', 'not_used', 'tolerable_risk'])
66
+
67
+ const text = (value: unknown, most = 500) => typeof value === 'string' && value.trim() ? value.trim().slice(0, most) : undefined
68
+
69
+ // How a dismissed alert was dismissed, as far as GitHub tells it soundly.
70
+ function dismissalOf(state: string, raw: Record<string, any>): AlertDismissal {
71
+ const at = state === 'auto_dismissed' ? raw['auto_dismissed_at'] : raw['dismissed_at']
72
+ const when = typeof at === 'string' && at.length <= 40 && !Number.isNaN(Date.parse(at)) ? { at } : {}
73
+ if (state === 'auto_dismissed') return { auto: true, ...when }
74
+ const by = raw['dismissed_by']?.login, comment = text(raw['dismissed_comment'], 280), reason = raw['dismissed_reason']
75
+ return { ...REASONS.has(reason) ? { reason } : {}, ...when, ...typeof by === 'string' && LOGIN.test(by) ? { by } : {}, ...comment === undefined ? {} : { comment } }
76
+ }
77
+
78
+ // An alert as GitHub answers it, or null for one that isn't an open or
79
+ // dismissed one of npm's, of a package and GHSA npm and GitHub would name.
80
+ function alertOf(fullName: string, raw: unknown): DependabotAlert | null {
81
+ if (raw == null || typeof raw !== 'object') return null
82
+ const { number, state, dependency, security_advisory: advisory, security_vulnerability: vulnerability } = raw as Record<string, any>
83
+ if (!isId(number) || !STATES.includes(state)) return null
84
+ const ghsa = advisory?.ghsa_id, manifest = dependency?.manifest_path, name = dependency?.package?.name
85
+ if (dependency?.package?.ecosystem !== 'npm' || !isNpmPackageName(name) || !isRepoPath(manifest) || typeof ghsa !== 'string' || !GHSA.test(ghsa)) return null
86
+ const severity = SEVERITIES.get(vulnerability?.severity ?? advisory?.severity)
87
+ const patched = text(vulnerability?.first_patched_version?.identifier, 100), range = text(vulnerability?.vulnerable_version_range, 200), title = text(advisory?.summary)
88
+ const ids = Array.isArray(advisory?.identifiers) ? advisory.identifiers as { value?: unknown }[] : []
89
+ const cwes = Array.isArray(advisory?.cwes) ? advisory.cwes as { cwe_id?: unknown }[] : []
90
+ return {
91
+ number, url: `https://github.com/${encodedPath(fullName)}/security/dependabot/${number}`, manifest, name, ghsa,
92
+ aliases: [...new Set(ids.flatMap(id => typeof id?.value === 'string' && /^[\w.:-]{1,64}$/u.test(id.value) && id.value !== ghsa ? [id.value] : []))],
93
+ ...title === undefined ? {} : { title }, ...severity === undefined ? {} : { severity },
94
+ ...range === undefined ? {} : { range }, ...patched === undefined ? {} : { patched },
95
+ cwe: [...new Set(cwes.flatMap(cwe => typeof cwe?.cwe_id === 'string' && /^CWE-\d{1,6}$/u.test(cwe.cwe_id) ? [cwe.cwe_id] : []))],
96
+ ...dependency.scope === 'development' ? { dev: true as const } : {},
97
+ ...state === 'open' ? {} : { dismissed: dismissalOf(state, raw as Record<string, any>) },
98
+ }
99
+ }
100
+
101
+ // The next page's cursor, as the Link header's `next` names it: its `after`,
102
+ // or its `page`, all that is taken of it, the rest of its URL left as asked.
103
+ function nextPage(link: string | null): [string, string] | null {
104
+ const next = link?.split(',').map(part => /^\s*<([^>]*)>\s*;\s*rel="next"\s*$/u.exec(part)?.[1]).find(Boolean)
105
+ if (!next) return null
106
+ let url
107
+ try { url = new URL(next) } catch { return null }
108
+ if (url.origin !== GITHUB_API) return null
109
+ const after = url.searchParams.get('after'), page = url.searchParams.get('page')
110
+ return after ? ['after', after] : page && /^\d{1,4}$/u.test(page) ? ['page', page] : null
111
+ }
112
+
113
+ // A page asked of GitHub: its alerts and the headers they came with. A 403
114
+ // that isn't a rate limit is told as the alerts being off
115
+ // (`dependabot-disabled`) or not to be read by the App's installation
116
+ // (`dependabot-app-permission`), as a 404 is, the repository found just
117
+ // before; the rest as githubJson tells them.
118
+ async function askPage(url: string, token: string, fetchImpl: typeof fetch, timeoutMs = PAGE_TIMEOUT_MS): Promise<{ alerts: unknown[]; link: string | null }> {
119
+ const started = Date.now()
120
+ let res: Response
121
+ try {
122
+ res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs), redirect: 'error', headers: githubHeaders(token) })
123
+ } catch (error) { throw githubUnreachable(error, started) }
124
+ if (res.status === 403) {
125
+ const message = (await res.clone().json().catch(() => null) as { message?: unknown } | null)?.message
126
+ const limited = res.headers.get('x-ratelimit-remaining') === '0' || res.headers.has('retry-after')
127
+ || (typeof message === 'string' && /rate limit|abuse detection/iu.test(message))
128
+ if (!limited) throw new GithubApiError(403, typeof message === 'string' && /disabled/iu.test(message) ? 'dependabot-disabled' : 'dependabot-app-permission')
129
+ }
130
+ if (res.status === 404) throw new GithubApiError(403, 'dependabot-app-permission')
131
+ if (!res.ok) await throwGithubResponseError(res)
132
+ let body
133
+ try { body = await res.json() } catch (error) {
134
+ throw error instanceof SyntaxError ? new GithubApiError(502, 'github-malformed') : githubUnreachable(error, started)
135
+ }
136
+ if (!Array.isArray(body)) throw new GithubApiError(502, 'github-malformed')
137
+ return { alerts: body, link: res.headers.get('link') }
138
+ }
139
+
140
+ // Whether GitHub lists `fullName`'s Dependabot alerts to `token`, a signed-in
141
+ // user's own token of the App's user authorization (dependabot-access.ts), as
142
+ // it does to anyone it lets see them: a security manager, or one whose custom
143
+ // or organization role grants it, as well as one with write, where the App
144
+ // may read them too. A 403 or 404 that isn't a rate limit is a no, but that
145
+ // they are off (`dependabot-disabled`); the rest as askPage tells them. One
146
+ // alert asked, never read.
147
+ export async function listsAlerts(fullName: string, token: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<boolean> {
148
+ try { await askPage(`${repoApi(fullName)}/dependabot/alerts?per_page=1`, token, fetchImpl, LISTED_TIMEOUT_MS) } catch (error) {
149
+ if (error instanceof GithubApiError && error.message === 'dependabot-app-permission') return false
150
+ throw error
151
+ }
152
+ return true
153
+ }
154
+
155
+ // `fullName`'s alerts in `states`, MAX_PAGES at most, in GitHub's order (the
156
+ // newest first), and whether that is all of them.
157
+ async function listAlerts(fullName: string, states: readonly string[], token: string, fetchImpl: typeof fetch) {
158
+ const base = `${repoApi(fullName)}/dependabot/alerts`
159
+ const alerts: DependabotAlert[] = []
160
+ const seen = new Set<number>()
161
+ let cursor: [string, string] | null = null
162
+ for (let pages = 0; pages < MAX_PAGES; pages++) {
163
+ const query = new URLSearchParams({ state: states.join(','), ecosystem: 'npm', per_page: String(PER_PAGE), ...cursor ? { [cursor[0]]: cursor[1] } : {} })
164
+ const answer = await askPage(`${base}?${query}`, token, fetchImpl)
165
+ for (const raw of answer.alerts) {
166
+ const alert = alertOf(fullName, raw)
167
+ if (alert && !seen.has(alert.number)) { seen.add(alert.number); alerts.push(alert) }
168
+ }
169
+ cursor = answer.alerts.length === 0 ? null : nextPage(answer.link)
170
+ if (!cursor) return { alerts, whole: true }
171
+ }
172
+ return { alerts, whole: false }
173
+ }
174
+
175
+ // `fullName`'s Dependabot alerts of npm's ecosystem, open or dismissed, as
176
+ // `token`, the App's installation's (dependabot-access.ts), may see them, in
177
+ // GitHub's order. Asked at once, but where they are more than a listing holds,
178
+ // as newer dismissed ones would leave older open ones out, the open ones are
179
+ // listed again on their own, and the dismissed ones had kept after them.
180
+ export async function dependabotAlerts(fullName: string, token: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<DependabotAlert[]> {
181
+ const all = await listAlerts(fullName, STATES, token, fetchImpl)
182
+ if (all.whole) return all.alerts
183
+ const open = await listAlerts(fullName, ['open'], token, fetchImpl)
184
+ const told = new Set(open.alerts.map(alert => alert.number))
185
+ return [...open.alerts, ...all.alerts.filter(alert => alert.dismissed && !told.has(alert.number))]
186
+ }
187
+
188
+ // The versions of an alert's package that a lockfile it is of locks
189
+ // (`packages`) and its range covers, GitHub's read as npm's semver reads its
190
+ // own (`>= 1.0.0, < 1.2.6` as `>= 1.0.0 < 1.2.6`); none where it is of no
191
+ // lockfile read, or its range is none semver reads.
192
+ export function alertVersions(alert: Pick<DependabotAlert, 'name' | 'range'>, packages: readonly LockedPackage[] | undefined): string[] {
193
+ const range = alert.range === undefined ? null : validRange(alert.range.replaceAll(',', ' '))
194
+ if (!packages || range === null) return []
195
+ return [...new Set(packages.flatMap(({ name, version, source }) => name === alert.name && (source === 'registry' || source === 'mirror')
196
+ && isExactVersion(version) && satisfies(version, range) ? [version] : []))]
197
+ }
@@ -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
+ }