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

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 (406) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +17 -0
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +3 -0
  13. package/common/bundle-compare-diff.js +376 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-metadata.d.ts +15 -0
  20. package/common/bundle-metadata.js +226 -0
  21. package/common/bundle-pkg-of.d.ts +1 -0
  22. package/common/bundle-pkg-of.js +90 -0
  23. package/common/bundle-reasons.d.ts +2 -0
  24. package/common/bundle-reasons.js +21 -0
  25. package/common/bundle-source-links.d.ts +6 -0
  26. package/common/bundle-source-links.js +216 -0
  27. package/common/bundle-sourcemap.d.ts +10 -0
  28. package/common/bundle-sourcemap.js +100 -0
  29. package/common/bundle-sources.d.ts +7 -0
  30. package/common/bundle-sources.js +333 -0
  31. package/common/bundle-stats.js +41 -0
  32. package/common/bundle-tabs.js +1 -0
  33. package/common/code-language.js +65 -0
  34. package/common/default-scan-models.ts +35 -0
  35. package/common/dependency-reviews.d.ts +18 -0
  36. package/common/dependency-reviews.js +64 -0
  37. package/common/finding-duplicates.js +58 -0
  38. package/common/finding-filters.js +274 -0
  39. package/common/finding-id.js +47 -0
  40. package/common/finding-repo.d.ts +5 -0
  41. package/common/finding-repo.js +67 -0
  42. package/common/github-issue-labels.d.ts +1 -0
  43. package/common/github-issue-labels.js +11 -0
  44. package/common/github-pr.ts +56 -0
  45. package/common/gzip.js +59 -0
  46. package/common/line-diff.d.ts +8 -0
  47. package/common/line-diff.js +57 -0
  48. package/common/linked-workspace-groups.js +63 -0
  49. package/common/managed/agent-tasks.ts +292 -0
  50. package/common/managed/comments.ts +34 -0
  51. package/common/managed/finding-detail.d.ts +5 -0
  52. package/common/managed/finding-detail.js +75 -0
  53. package/common/managed/finding-values.d.ts +2 -0
  54. package/common/managed/finding-values.js +44 -0
  55. package/common/managed/github-agents.ts +114 -0
  56. package/common/managed/github-logins.ts +49 -0
  57. package/common/managed/lite-name.d.ts +2 -0
  58. package/common/managed/lite-name.js +20 -0
  59. package/common/managed/npm-packages.d.ts +7 -0
  60. package/common/managed/npm-packages.js +51 -0
  61. package/common/managed/permissions.ts +31 -0
  62. package/common/managed/report-content.ts +72 -0
  63. package/common/managed/report-filter.ts +120 -0
  64. package/common/managed/repository-alias.ts +65 -0
  65. package/common/managed/roles.ts +35 -0
  66. package/common/managed/routes.d.ts +2 -0
  67. package/common/managed/routes.js +363 -0
  68. package/common/managed/scan-models.ts +6 -0
  69. package/common/managed/team-app.d.ts +15 -0
  70. package/common/managed/team-app.js +100 -0
  71. package/common/managed/team-filters.js +26 -0
  72. package/common/managed/triage.ts +83 -0
  73. package/common/managed/upload-seal.ts +126 -0
  74. package/common/pretty-print.d.ts +5 -0
  75. package/common/pretty-print.js +24 -0
  76. package/common/repo-commit.d.ts +4 -0
  77. package/common/repo-commit.js +30 -0
  78. package/common/revalidation-conflicts.js +48 -0
  79. package/common/revalidation-input-groups.js +56 -0
  80. package/common/save-error-reason.ts +20 -7
  81. package/common/scan-server.ts +13 -0
  82. package/common/security-links.d.ts +5 -0
  83. package/common/security-links.js +33 -0
  84. package/common/server-info.ts +46 -0
  85. package/common/utf8.d.ts +3 -0
  86. package/common/utf8.js +45 -0
  87. package/common/workspace-app.js +71 -0
  88. package/common/workspace-groups.js +176 -0
  89. package/out/activity.js +4 -0
  90. package/out/brotli-fallback.js +3 -3
  91. package/out/chunk-2SY4PYUQ.js +4 -0
  92. package/out/chunk-2XUEZHIP.js +28 -0
  93. package/out/chunk-4EMM6UCD.js +1 -0
  94. package/out/chunk-4HI2MSAV.js +17 -0
  95. package/out/chunk-4ISO5F7Y.js +7 -0
  96. package/out/chunk-4TQKM3JC.js +42 -0
  97. package/out/chunk-4XIH7YTX.js +1 -0
  98. package/out/chunk-6VDDCFHT.js +3 -0
  99. package/out/chunk-74AEKRES.js +10 -0
  100. package/out/chunk-7BKKYVWR.js +7 -0
  101. package/out/chunk-7C7DWL7I.js +1 -0
  102. package/out/chunk-C4Z6ZBXV.js +10 -0
  103. package/out/chunk-DEVAORP2.js +1 -0
  104. package/out/chunk-E3LFSUDJ.js +9 -0
  105. package/out/chunk-EEQHVKR3.js +1 -0
  106. package/out/chunk-G3LY2FV4.js +1 -0
  107. package/out/chunk-GO7FT4OD.js +1 -0
  108. package/out/chunk-HAZKDK4M.js +4 -0
  109. package/out/chunk-HNQNDNIE.js +12 -0
  110. package/out/chunk-HOB3YPS5.js +1 -0
  111. package/out/chunk-IYPY47MC.js +1 -0
  112. package/out/chunk-IZ6MYRYB.js +3 -0
  113. package/out/chunk-J2FWBXFV.js +1 -0
  114. package/out/chunk-JCIIBLKR.js +1 -0
  115. package/out/chunk-JFL7WLRV.js +1 -0
  116. package/out/chunk-JMG5DXII.js +2 -0
  117. package/out/chunk-JOXLZXMI.js +1 -0
  118. package/out/chunk-M37X4LCF.js +14 -0
  119. package/out/chunk-M3Y6SLC4.js +1 -0
  120. package/out/chunk-NRPC74AM.js +1 -0
  121. package/out/chunk-NXATZJQ2.js +1 -0
  122. package/out/chunk-OFPDMZJF.js +244 -0
  123. package/out/chunk-OOJM4CTU.js +1 -0
  124. package/out/chunk-OQRSIBSC.js +1 -0
  125. package/out/chunk-PAD2JHZT.js +1 -0
  126. package/out/chunk-PNHBZGDD.js +1 -0
  127. package/out/chunk-PTFQKLKO.js +1 -0
  128. package/out/chunk-PWFUOLZK.js +17 -0
  129. package/out/chunk-PXK7EU4V.js +1 -0
  130. package/out/chunk-QMVOEBWC.js +13 -0
  131. package/out/chunk-QRKFPLA4.js +80 -0
  132. package/out/chunk-R3NZFXVR.js +1 -0
  133. package/out/chunk-R5O6FAW4.js +2 -0
  134. package/out/chunk-RRBIJL2B.js +1 -0
  135. package/out/chunk-SYXT3SFP.js +2 -0
  136. package/out/chunk-TOXMUOIW.js +5 -0
  137. package/out/chunk-TUII34K2.js +1 -0
  138. package/out/chunk-TZS7KERJ.js +52 -0
  139. package/out/chunk-UCP3JRE2.js +1 -0
  140. package/out/chunk-VFWMQ3LG.js +2 -0
  141. package/out/chunk-VRX2APNA.js +9 -0
  142. package/out/chunk-VZJIHHTQ.js +1 -0
  143. package/out/chunk-WCPJDAYA.js +10 -0
  144. package/out/chunk-WMFDQS2L.js +11 -0
  145. package/out/chunk-WREU7JAG.js +1 -0
  146. package/out/chunk-Y5ZHFNBD.js +2 -0
  147. package/out/chunk-YF4M5OCI.js +1 -0
  148. package/out/chunk-YGRRXC2L.js +1 -0
  149. package/out/chunk-YTO6AQZM.js +2 -0
  150. package/out/chunk-Z667U2UJ.js +1 -0
  151. package/out/chunk-ZQHLECTI.js +1 -0
  152. package/out/client-managed-import.js +4 -0
  153. package/out/client-managed.js +34 -0
  154. package/out/client-sync.js +11 -17
  155. package/out/compare.js +35 -0
  156. package/out/dialogs.js +40 -0
  157. package/out/github-issue-authorized.html +3 -0
  158. package/out/github-issue-authorized.js +1 -0
  159. package/out/graph.js +19 -4
  160. package/out/index.html +106 -8
  161. package/out/prism.js +14 -10
  162. package/out/scan.js +2 -0
  163. package/out/stasis.svg +20 -0
  164. package/out/terminal.js +366 -39
  165. package/out/view.css +1 -1
  166. package/out/view.js +19 -144
  167. package/package.json +379 -62
  168. package/risk/actions/findings.js +161 -0
  169. package/risk/actions/resolve.js +250 -0
  170. package/risk/actions/scripts/commands.js +182 -0
  171. package/risk/actions/scripts/grade.js +113 -0
  172. package/risk/actions/scripts/packages.js +123 -0
  173. package/risk/actions/scripts/shell.js +169 -0
  174. package/risk/actions/uses.js +76 -0
  175. package/risk/actions/workflow.js +110 -0
  176. package/risk/files/characters.js +196 -0
  177. package/risk/files/hosts.js +205 -0
  178. package/risk/files/readability.js +177 -0
  179. package/risk/files/runs-code.js +615 -0
  180. package/risk/files/script.js +118 -0
  181. package/risk/files/stamps.js +47 -0
  182. package/risk/index.d.ts +272 -0
  183. package/risk/index.js +11 -0
  184. package/risk/npm/assess.js +285 -0
  185. package/risk/npm/combined.js +68 -0
  186. package/risk/npm/compare.js +257 -0
  187. package/risk/npm/dependencies.js +172 -0
  188. package/risk/npm/diff.js +79 -0
  189. package/risk/npm/downloads.js +84 -0
  190. package/risk/npm/files.js +445 -0
  191. package/risk/npm/held.js +63 -0
  192. package/risk/npm/install-scripts.js +34 -0
  193. package/risk/npm/malware.js +38 -0
  194. package/risk/npm/manifest.js +65 -0
  195. package/risk/npm/new-dependency.js +60 -0
  196. package/risk/npm/old-version.js +108 -0
  197. package/risk/npm/registry.js +390 -0
  198. package/risk/npm/release.js +85 -0
  199. package/risk/npm/score.js +59 -0
  200. package/risk/npm/specs.js +124 -0
  201. package/risk/npm/tarball.js +96 -0
  202. package/server-common/database-config.ts +16 -0
  203. package/server-common/initialize.ts +18 -0
  204. package/server-common/npm-advisories.ts +101 -0
  205. package/{server → server-common}/origin.ts +5 -5
  206. package/server-common/reap.ts +48 -0
  207. package/server-common/scan-config.ts +19 -0
  208. package/server-common/standalone.ts +29 -0
  209. package/server-common/storage-crypto.ts +182 -0
  210. package/server-common/storage-log.ts +38 -0
  211. package/server-common/vercel-blob.ts +103 -0
  212. package/server-e2e/app.ts +487 -0
  213. package/{server → server-e2e}/bus-receiver.ts +2 -1
  214. package/{server → server-e2e}/cli.js +9 -4
  215. package/{server → server-e2e}/config.ts +50 -42
  216. package/{server → server-e2e}/db-neon.ts +2 -2
  217. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  218. package/{server → server-e2e}/db-stmt.ts +2 -2
  219. package/{server → server-e2e}/db.ts +7 -7
  220. package/{server → server-e2e}/http.ts +44 -13
  221. package/{server → server-e2e}/hub.ts +40 -9
  222. package/server-e2e/index.ts +17 -0
  223. package/server-e2e/lifecycle.ts +95 -0
  224. package/{server → server-e2e}/neon-driver.ts +2 -2
  225. package/{server → server-e2e}/npm-proxy.ts +12 -145
  226. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  227. package/{server → server-e2e}/objstore/blob.ts +1 -1
  228. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  229. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  230. package/{server → server-e2e}/objstore/init.ts +19 -27
  231. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  232. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  233. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  234. package/{server → server-e2e}/objstore/rest.ts +3 -3
  235. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  236. package/{server → server-e2e}/objstore/store.ts +7 -7
  237. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  238. package/{server → server-e2e}/pubsub.ts +12 -9
  239. package/{server → server-e2e}/sign.ts +4 -4
  240. package/{server → server-e2e}/sse-server.ts +60 -33
  241. package/{server → server-e2e}/static.ts +31 -21
  242. package/{server → server-e2e}/sync-handlers.ts +64 -30
  243. package/{server → server-e2e}/ws-server.ts +20 -9
  244. package/server-managed/activity.ts +258 -0
  245. package/server-managed/agent-merges.ts +109 -0
  246. package/server-managed/app-agents.ts +23 -0
  247. package/server-managed/avatar-store.ts +13 -0
  248. package/server-managed/blob-store.ts +17 -0
  249. package/server-managed/brotli.ts +10 -0
  250. package/server-managed/bundle-advisories.ts +102 -0
  251. package/server-managed/bundle-advisory-inventory.ts +77 -0
  252. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  253. package/server-managed/bundle-build-diagnostics.js +23 -0
  254. package/server-managed/bundle-build-leases.ts +41 -0
  255. package/server-managed/bundle-build-worker.js +203 -0
  256. package/server-managed/bundle-build.ts +232 -0
  257. package/server-managed/bundle-cache.ts +211 -0
  258. package/server-managed/bundle-catalog.ts +29 -0
  259. package/server-managed/bundle-commits.ts +140 -0
  260. package/server-managed/bundle-dependency-reviews.ts +74 -0
  261. package/server-managed/bundle-store.ts +24 -0
  262. package/server-managed/bundle-summary-cache.ts +130 -0
  263. package/server-managed/bundle-validation.ts +32 -0
  264. package/server-managed/bundle.ts +119 -0
  265. package/server-managed/cache-storage.ts +20 -0
  266. package/server-managed/cli.js +21 -0
  267. package/server-managed/combined.ts +47 -0
  268. package/server-managed/comments.ts +151 -0
  269. package/server-managed/commit-coauthors.ts +106 -0
  270. package/server-managed/commit-lockfiles.ts +76 -0
  271. package/server-managed/comparison.ts +52 -0
  272. package/server-managed/config.ts +164 -0
  273. package/server-managed/content-access.ts +15 -0
  274. package/server-managed/crypto.ts +25 -0
  275. package/server-managed/db-methods.ts +1958 -0
  276. package/server-managed/db-neon.ts +484 -0
  277. package/server-managed/db-schema.ts +238 -0
  278. package/server-managed/db-table-names.ts +22 -0
  279. package/server-managed/db.ts +152 -0
  280. package/server-managed/dependabot-access.ts +60 -0
  281. package/server-managed/dependabot-alerts.ts +185 -0
  282. package/server-managed/dependency-review-comments.ts +98 -0
  283. package/server-managed/dependency-reviews.ts +364 -0
  284. package/server-managed/github-accounts.ts +60 -0
  285. package/server-managed/github-actions.ts +71 -0
  286. package/server-managed/github-app.ts +376 -0
  287. package/server-managed/github-errors.ts +70 -0
  288. package/server-managed/github-graphql.ts +39 -0
  289. package/server-managed/github-issue-links.ts +244 -0
  290. package/server-managed/github-issue-oauth.ts +47 -0
  291. package/server-managed/github-issues.ts +155 -0
  292. package/server-managed/github-link-oauth.ts +69 -0
  293. package/server-managed/github-links.ts +204 -0
  294. package/server-managed/github-metadata.ts +213 -0
  295. package/server-managed/github-oauth.ts +238 -0
  296. package/server-managed/github-pulls.ts +246 -0
  297. package/server-managed/github-requests.ts +166 -0
  298. package/server-managed/github-users.ts +30 -0
  299. package/server-managed/history-windows.ts +172 -0
  300. package/server-managed/http-response.ts +76 -0
  301. package/server-managed/http.ts +5855 -0
  302. package/server-managed/import-triage.ts +51 -0
  303. package/server-managed/index.ts +204 -0
  304. package/server-managed/kept-briefly.ts +37 -0
  305. package/server-managed/kept.ts +28 -0
  306. package/server-managed/link-reports.ts +162 -0
  307. package/server-managed/listed-activity.ts +39 -0
  308. package/server-managed/locked-packages.ts +152 -0
  309. package/server-managed/lockfile-scope.ts +49 -0
  310. package/server-managed/lru.ts +30 -0
  311. package/server-managed/managed-issues.ts +92 -0
  312. package/server-managed/management-catalog.ts +45 -0
  313. package/server-managed/management.ts +99 -0
  314. package/server-managed/npm-delta-worker.js +23 -0
  315. package/server-managed/npm-delta.ts +194 -0
  316. package/server-managed/npm-insights.ts +450 -0
  317. package/server-managed/npm-kept.ts +233 -0
  318. package/server-managed/npm-loads.ts +264 -0
  319. package/server-managed/npm-manifest.ts +115 -0
  320. package/server-managed/npm-packages.ts +454 -0
  321. package/server-managed/npm-patch.ts +325 -0
  322. package/server-managed/npm-provenance.ts +123 -0
  323. package/server-managed/npm-risk.ts +285 -0
  324. package/server-managed/object-storage-disk.ts +148 -0
  325. package/server-managed/object-storage-vercel.ts +67 -0
  326. package/server-managed/object-storage.ts +75 -0
  327. package/server-managed/package-entry-points.ts +79 -0
  328. package/server-managed/pretty-print.ts +436 -0
  329. package/server-managed/public-workspace.ts +238 -0
  330. package/server-managed/pull-comment-reviews.ts +161 -0
  331. package/server-managed/pull-dependencies.ts +351 -0
  332. package/server-managed/pull-dependency-reviews.ts +334 -0
  333. package/server-managed/pull-reviews.ts +205 -0
  334. package/server-managed/queue.ts +39 -0
  335. package/server-managed/release-commits.ts +84 -0
  336. package/server-managed/rename-diff-worker.js +26 -0
  337. package/server-managed/rename-diff.ts +279 -0
  338. package/server-managed/repo-path.ts +21 -0
  339. package/server-managed/report-migration.ts +35 -0
  340. package/server-managed/report-query.ts +10 -0
  341. package/server-managed/report-response.ts +16 -0
  342. package/server-managed/report-sources.ts +185 -0
  343. package/server-managed/report-store.ts +85 -0
  344. package/server-managed/repository-actions.ts +221 -0
  345. package/server-managed/repository-agents.ts +448 -0
  346. package/server-managed/repository-aliases.ts +91 -0
  347. package/server-managed/repository-browser.ts +301 -0
  348. package/server-managed/repository-changes.ts +284 -0
  349. package/server-managed/repository-code.ts +215 -0
  350. package/server-managed/repository-dependency-reviews.ts +166 -0
  351. package/server-managed/repository-discovery.ts +82 -0
  352. package/server-managed/repository-history.ts +432 -0
  353. package/server-managed/repository-issues.ts +195 -0
  354. package/server-managed/repository-policy.ts +27 -0
  355. package/server-managed/repository-pulls.ts +212 -0
  356. package/server-managed/repository-pulse.ts +471 -0
  357. package/server-managed/repository-risk-assess.ts +105 -0
  358. package/server-managed/repository-risk-audit.ts +78 -0
  359. package/server-managed/repository-risk-read.ts +170 -0
  360. package/server-managed/repository-risk.ts +491 -0
  361. package/server-managed/repository-squashes.ts +168 -0
  362. package/server-managed/repository-stamp.ts +41 -0
  363. package/server-managed/request-timing.ts +63 -0
  364. package/server-managed/reviewed-dependencies.ts +149 -0
  365. package/server-managed/revisions.ts +35 -0
  366. package/server-managed/scan-downloads.ts +87 -0
  367. package/server-managed/session.ts +132 -0
  368. package/server-managed/slugs.ts +38 -0
  369. package/server-managed/solidity-entry-points.ts +71 -0
  370. package/server-managed/sql-postgres.ts +34 -0
  371. package/server-managed/sql.ts +89 -0
  372. package/server-managed/stasis-config.ts +55 -0
  373. package/server-managed/static.ts +28 -0
  374. package/server-managed/storage-command.ts +16 -0
  375. package/server-managed/storage-db.ts +183 -0
  376. package/server-managed/storage-encryption.ts +290 -0
  377. package/server-managed/storage-maintenance.ts +259 -0
  378. package/server-managed/storage-payload.ts +121 -0
  379. package/server-managed/storage-stores.ts +91 -0
  380. package/server-managed/storage.ts +82 -0
  381. package/server-managed/team-app-summaries.ts +54 -0
  382. package/server-managed/team-app.ts +157 -0
  383. package/server-managed/team-catalog.ts +7 -0
  384. package/server-managed/team-feed.ts +180 -0
  385. package/server-managed/team-npm-scopes.ts +106 -0
  386. package/server-managed/team-reports.ts +351 -0
  387. package/server-managed/triage-response.ts +16 -0
  388. package/server-managed/type-only-worker.js +19 -0
  389. package/server-managed/type-only.ts +105 -0
  390. package/server-managed/uploads.ts +106 -0
  391. package/server-managed/upstream-cache.ts +252 -0
  392. package/server-managed/view-as.ts +58 -0
  393. package/server-managed/workspace-shares.ts +171 -0
  394. package/server.ts +70 -0
  395. package/server/index.ts +0 -480
  396. package/server/lifecycle.ts +0 -208
  397. /package/{LICENSE → LICENSE-MIT} +0 -0
  398. /package/{server → server-e2e}/auth.ts +0 -0
  399. /package/{server → server-e2e}/config.example.json +0 -0
  400. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  401. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  402. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  403. /package/{server → server-e2e}/peer.ts +0 -0
  404. /package/{server → server-e2e}/sse-session.ts +0 -0
  405. /package/{server → server-e2e}/util.ts +0 -0
  406. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,244 @@
1
+ import { type GithubFixResult, githubIssueClosedReason, isGithubRepoName, parseGithubFixUrl, parseGithubIssueUrl } from '../common/github-pr.ts'
2
+ import type { ManagedConfig } from './config.ts'
3
+ import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
4
+ import type { IssueTracking, ManagedIssue } from './managed-issues.ts'
5
+ import { ensureUserAccessToken } from './github-oauth.ts'
6
+ import { lookupFixes } from './github-pulls.ts'
7
+
8
+ export type IssueFixUpdate = { findingId: string; issueUrl: string; previous: IssueTracking; next: IssueTracking; checkedAt: number }
9
+ type Pull = { number: number; title: string; body: string | null; state: string; isDraft: boolean; createdAt: string;
10
+ repository: { databaseId: number; nameWithOwner: string } }
11
+ type Connection = { nodes: Pull[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } }
12
+ type RepositoryReference = { databaseId?: unknown; nameWithOwner?: unknown } | null | undefined
13
+ type IssueReference = { number?: unknown; repository?: RepositoryReference }
14
+ type Issue = { number: number; title: string; body: string | null; state: string; stateReason: string | null; closedByPullRequestsReferences?: Connection
15
+ duplicateOf?: IssueReference | null }
16
+ type Repository = TeamReportAccessSnapshot['repositories'][number]
17
+ // The issue a linked one was closed as a duplicate of, in a workspace
18
+ // repository: null for none (or one outside them, never followed or
19
+ // disclosed, as a pull request outside them isn't).
20
+ type Duplicate = { repo: Repository; number: number } | null
21
+ // `duplicateOf` is a linked issue's, from its last page read: undefined while
22
+ // none is, or where GitHub refused the reference.
23
+ type Job = { repo: Repository; kind: 'pull' | 'issue'; number: number; aliases: string[];
24
+ linked: boolean; cursor: string | null; pulls: Pull[]; complete: boolean; duplicateOf?: Duplicate | undefined }
25
+ type Metadata = Exclude<GithubFixResult, { error: string }>
26
+ const pullFields = 'number title body state isDraft createdAt repository { databaseId nameWithOwner }'
27
+ // A linked issue's: the issue it was closed as a duplicate of, and a page of
28
+ // the pull requests linked to it.
29
+ const linkedFields = (cursor: string | null) => 'duplicateOf { number repository { databaseId nameWithOwner } } '
30
+ + `closedByPullRequestsReferences(first: 100, includeClosedPrs: true, after: ${JSON.stringify(cursor)}) { nodes { ${pullFields} } pageInfo { hasNextPage endCursor } }`
31
+ // How many issues a saved one is followed through, each closed as a
32
+ // duplicate of the next: each is another request after the last.
33
+ const MAX_DUPLICATE_HOPS = 5
34
+ const jobKey = (repoId: number, kind: Job['kind'], number: number) => `${repoId}:${kind}:${number}`
35
+ const issueUrlOf = (repo: Repository, number: number) => `https://github.com/${repo.github}/issues/${number}`
36
+ // Whether GitHub named a repository as one is: by its stable ID and a name.
37
+ const isRepositoryReference = (ref: RepositoryReference): ref is { databaseId: number; nameWithOwner: string } =>
38
+ Number.isSafeInteger(ref?.databaseId) && typeof ref?.nameWithOwner === 'string' && isGithubRepoName(ref.nameWithOwner)
39
+ // The workspace repository GitHub named, matching its name and stable ID
40
+ // both; none for one outside the workspace repository grants.
41
+ const workspaceRepository = (ref: { databaseId: number; nameWithOwner: string }, allowed: Map<string, Repository>) => {
42
+ const repo = allowed.get(ref.nameWithOwner.toLowerCase())
43
+ return repo?.repoId === ref.databaseId ? repo : null
44
+ }
45
+
46
+ function metadataQuery(jobs: Job[]) {
47
+ return `{ ${jobs.map((job, index) => {
48
+ const [owner, name] = job.repo.github.split('/')
49
+ const fields = job.kind === 'pull' ? pullFields : `number title body state stateReason ${job.linked ? linkedFields(job.cursor) : ''}`
50
+ return `r${index}: repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(name)}) { databaseId nameWithOwner item: ${job.kind === 'pull' ? 'pullRequest' : 'issue'}(number: ${job.number}) { ${fields} } }`
51
+ }).join('\n')} }`
52
+ }
53
+
54
+ function itemMetadata(item: Issue | Pull, kind: Job['kind']): Omit<Metadata, 'url'> | null {
55
+ if (!item || typeof item.title !== 'string' || !item.title.trim() || item.title.length > 1024
56
+ || item.body != null && typeof item.body !== 'string' || !['OPEN', 'CLOSED', ...(kind === 'pull' ? ['MERGED'] : [])].includes(item.state)) return null
57
+ const status = item.state === 'MERGED' ? 'merged' : item.state === 'CLOSED' ? 'closed' : 'isDraft' in item && item.isDraft === true ? 'draft' : 'open'
58
+ const stateReason = kind === 'issue' && status === 'closed' ? githubIssueClosedReason(String((item as Issue).stateReason).toLowerCase()) : null
59
+ return { title: item.title, description: item.body ?? null, status, stateReason }
60
+ }
61
+
62
+ // The issue `issue` was closed as a duplicate of, where GitHub names one
63
+ // (Duplicate); undefined for a reference it gave malformed.
64
+ function duplicateOf(issue: Issue, allowed: Map<string, Repository>): Duplicate | undefined {
65
+ if (issue.state !== 'CLOSED' || issue.stateReason !== 'DUPLICATE' || issue.duplicateOf == null) return null
66
+ const { number, repository } = issue.duplicateOf
67
+ if (!Number.isSafeInteger(number) || (number as number) <= 0 || !isRepositoryReference(repository)) return undefined
68
+ const repo = workspaceRepository(repository, allowed)
69
+ return repo ? { repo, number: number as number } : null
70
+ }
71
+
72
+ // `refused`: GitHub answered with an error on the issue's duplicate alone,
73
+ // which, like a malformed one, leaves it shown but what it redirects to
74
+ // unknown.
75
+ function readPage(job: Job, item: Issue | Pull, metadata: Map<string, Metadata>, allowed: Map<string, Repository>, refused: boolean): boolean {
76
+ const details = itemMetadata(item, job.kind)
77
+ if (!details || item.number !== job.number) return false
78
+ for (const url of job.aliases) metadata.set(url, { url, ...details })
79
+ if (!job.linked) return false
80
+ const duplicate = refused ? undefined : duplicateOf(item as Issue, allowed)
81
+ if (duplicate === undefined) return false
82
+ const connection = (item as Issue).closedByPullRequestsReferences
83
+ if (!connection || !Array.isArray(connection.nodes) || typeof connection.pageInfo?.hasNextPage !== 'boolean'
84
+ || connection.nodes.some(pr => !pr || !Number.isSafeInteger(pr.number) || pr.number <= 0 || typeof pr.createdAt !== 'string'
85
+ || !Number.isFinite(Date.parse(pr.createdAt)) || !itemMetadata(pr, 'pull') || typeof pr.isDraft !== 'boolean'
86
+ || !isRepositoryReference(pr.repository))) return false
87
+ job.duplicateOf = duplicate
88
+ job.pulls.push(...connection.nodes)
89
+ if (!connection.pageInfo.hasNextPage) { job.complete = true; return false }
90
+ if (typeof connection.pageInfo.endCursor !== 'string' || !connection.pageInfo.endCursor || connection.pageInfo.endCursor === job.cursor) return false
91
+ job.cursor = connection.pageInfo.endCursor
92
+ return true
93
+ }
94
+
95
+ // A saved issue's job, then those of the issues it was closed as a duplicate
96
+ // of in turn, as far as this lookup has read them, a redirect followed rather
97
+ // than the saved issue replaced. `next` is null where the last names none
98
+ // further to follow (or one already in the chain, or past
99
+ // MAX_DUPLICATE_HOPS); the one it names where this lookup has no linked job
100
+ // for it; undefined where one is yet unread, or what it names unknown.
101
+ function duplicateChain(root: Job, jobs: Map<string, Job>): { chain: Job[]; next: Duplicate | undefined } {
102
+ const chain = [root]
103
+ for (let job = root; ;) {
104
+ const target = job.duplicateOf
105
+ if (!target || chain.length > MAX_DUPLICATE_HOPS) return { chain, next: target && null }
106
+ const next = jobs.get(jobKey(target.repo.repoId, 'issue', target.number))
107
+ if (next && chain.includes(next)) return { chain, next: null }
108
+ if (!next?.linked) return { chain, next: target }
109
+ chain.push(job = next)
110
+ }
111
+ }
112
+
113
+ // The issues saved ones were closed as duplicates of, which this lookup has
114
+ // yet to read with their linked pull requests: each made a linked job, as a
115
+ // saved issue's own is (one read without them never read further).
116
+ function duplicateJobs(jobs: Map<string, Job>, roots: Iterable<string>): Job[] {
117
+ const found: Job[] = []
118
+ for (const key of roots) {
119
+ const root = jobs.get(key)
120
+ const next = root && duplicateChain(root, jobs).next
121
+ if (!next) continue
122
+ const nextKey = jobKey(next.repo.repoId, 'issue', next.number), url = issueUrlOf(next.repo, next.number)
123
+ let job = jobs.get(nextKey)
124
+ if (!job) jobs.set(nextKey, job = { repo: next.repo, kind: 'issue', number: next.number, aliases: [], linked: true, cursor: null, pulls: [], complete: false })
125
+ job.linked = true
126
+ if (!job.aliases.includes(url)) job.aliases.push(url)
127
+ found.push(job)
128
+ }
129
+ return found
130
+ }
131
+
132
+ // `byIssue`: the saved issues each job's issue is, by its key.
133
+ function issueUpdates(jobs: Map<string, Job>, byIssue: Map<string, ManagedIssue[]>, allowed: Map<string, Repository>, checkedAt: number, metadata: Map<string, Metadata>) {
134
+ const updates: IssueFixUpdate[] = []
135
+ for (const [key, saved] of byIssue) {
136
+ const root = jobs.get(key)
137
+ if (!root?.linked) continue
138
+ // The saved issue and every one it was closed as a duplicate of in turn,
139
+ // each read whole: the last is tracked, and the pull requests of all.
140
+ const { chain, next } = duplicateChain(root, jobs)
141
+ if (next !== null || !chain.every(job => job.complete)) continue
142
+ // "Last" means the newest PR by creation time, never its latest comment.
143
+ const latest = chain.flatMap(job => job.pulls).filter(pr => pr.state !== 'CLOSED')
144
+ .toSorted((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt) || b.number - a.number)[0]
145
+ const repo = latest && workspaceRepository(latest.repository, allowed)
146
+ // The viewer's token can have broader access than this workspace. Never
147
+ // persist or disclose a PR from outside the workspace repository grants:
148
+ // where the newest is one, the saved Fix stays. The duplicate, checked
149
+ // against the grants itself, is saved all the same.
150
+ const foreign = Boolean(latest && !repo)
151
+ const autoFix = latest && repo ? `https://github.com/${repo.github}/pull/${latest.number}` : null
152
+ if (latest && autoFix) metadata.set(autoFix, { url: autoFix, ...itemMetadata(latest, 'pull')! })
153
+ const last = chain.at(-1)!
154
+ const duplicate = chain.length > 1 ? issueUrlOf(last.repo, last.number) : null
155
+ // Only a changed derived Fix or duplicate is written: an unchanged one's
156
+ // check time alone would bump the annotations revision that every open
157
+ // team feed polls, for nothing they show. Changes still stamp it, so an
158
+ // older lookup never replaces a newer change (managed-issues.ts). An older
159
+ // lookup that differs can now land after a newer unchanged one, as it
160
+ // could already land before it (whose compare-and-set then fails); either
161
+ // way the next lookup finds the stored values differ, and writes the
162
+ // current ones.
163
+ for (const issue of saved) {
164
+ const tracking = { autoFix: foreign ? issue.autoFixUrl : autoFix, duplicateOf: duplicate }
165
+ if (issue.autoFixUrl !== tracking.autoFix || issue.duplicateOfUrl !== tracking.duplicateOf) {
166
+ updates.push({ findingId: issue.findingId, issueUrl: issue.issueUrl!, checkedAt,
167
+ previous: { autoFix: issue.autoFixUrl, duplicateOf: issue.duplicateOfUrl }, next: tracking })
168
+ }
169
+ }
170
+ }
171
+ return updates
172
+ }
173
+
174
+ // Fetch issue details, linked PR states and manual Fix metadata in one batch.
175
+ // Pagination, workspaces with over 200 distinct links, and issues closed as a
176
+ // duplicate of one not yet read need further batches. A duplicate saved last
177
+ // time is read in the first, as a redirect kept is: its URL among `urls`.
178
+ // Live GraphQL results prove this viewer's access; never publish them into the
179
+ // REST shared cache under an older public-visibility grant.
180
+ export async function lookupIssueLinks(config: ManagedConfig, db: ManagedDb, snapshot: TeamReportAccessSnapshot,
181
+ urls: string[], issues: ManagedIssue[], fetchImpl: typeof fetch = fetch): Promise<{ fixes: GithubFixResult[]; updates: IssueFixUpdate[] }> {
182
+ const checkedAt = Date.now(), signal = AbortSignal.timeout(10_000)
183
+ const allowed = new Map(snapshot.repositories.filter(repo => isGithubRepoName(repo.github)).map(repo => [repo.github.toLowerCase(), repo]))
184
+ const jobs = new Map<string, Job>()
185
+ // The saved issues by their issue's key, and the issues read with their
186
+ // linked pull requests: theirs, and the duplicates they were saved with.
187
+ const byIssue = new Map<string, ManagedIssue[]>(), linked = new Set<string>()
188
+ for (const issue of issues) {
189
+ const ref = parseGithubIssueUrl(issue.issueUrl)
190
+ if (!ref) continue
191
+ const key = jobKey(issue.repoId, 'issue', ref.number)
192
+ byIssue.set(key, [...byIssue.get(key) ?? [], issue])
193
+ linked.add(key)
194
+ const duplicate = parseGithubIssueUrl(issue.duplicateOfUrl), repo = duplicate && allowed.get(duplicate.repo.toLowerCase())
195
+ if (duplicate && repo) linked.add(jobKey(repo.repoId, 'issue', duplicate.number))
196
+ }
197
+ for (const url of urls) {
198
+ const ref = parseGithubFixUrl(url), repo = ref && allowed.get(ref.repo.toLowerCase())
199
+ if (!ref || !repo) continue
200
+ const key = jobKey(repo.repoId, ref.kind, ref.number), previous = jobs.get(key)
201
+ if (previous) { previous.aliases.push(url); continue }
202
+ jobs.set(key, { repo, kind: ref.kind, number: ref.number, aliases: [url], linked: linked.has(key), cursor: null, pulls: [], complete: false })
203
+ }
204
+ if (jobs.size === 0) return { fixes: [], updates: [] }
205
+ const withinDeadline: typeof fetch = (input, init) => { signal.throwIfAborted(); return fetchImpl(input, { ...init, signal }) }
206
+ const token = await ensureUserAccessToken(config, db, snapshot.user.id, checkedAt, withinDeadline)
207
+ if (!token) return { fixes: await lookupFixes(config, db, snapshot, urls, withinDeadline), updates: [] }
208
+ const metadata = new Map<string, Metadata>()
209
+ let pending = [...jobs.values()]
210
+ for (let page = 0; pending.length > 0 && page < 100 && !signal.aborted; page++) {
211
+ const batch = pending.slice(0, 200), query = metadataQuery(batch)
212
+ let data: Record<string, { databaseId: number; nameWithOwner: string; item: Issue | Pull } | null>
213
+ const refused = new Set<string>()
214
+ try {
215
+ const response = await withinDeadline('https://api.github.com/graphql', {
216
+ method: 'POST', redirect: 'error',
217
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': 'deepview-triage' }, body: JSON.stringify({ query }),
218
+ })
219
+ if (!response.ok) break
220
+ const body = await response.json() as { data?: typeof data; errors?: { path?: unknown[] }[] }
221
+ // Errors attached to an alias invalidate that whole job, including its
222
+ // connection. Other aliases can succeed even if one issue was deleted.
223
+ // One on the issue it duplicates alone, which the viewer may be unable
224
+ // to read, leaves its status, and only what it redirects to unknown.
225
+ if (!body?.data || body.errors != null && (!Array.isArray(body.errors)
226
+ || body.errors.some(error => typeof error?.path?.[0] !== 'string' || !/^r\d+$/u.test(error.path[0])))) break
227
+ data = body.data
228
+ for (const error of body.errors ?? []) {
229
+ const [alias, field, reference] = error.path! as string[]
230
+ if (field === 'item' && reference === 'duplicateOf') refused.add(alias!)
231
+ else data[alias!] = null
232
+ }
233
+ } catch { break }
234
+ pending = pending.slice(batch.length)
235
+ for (const [index, job] of batch.entries()) {
236
+ const repository = data[`r${index}`]
237
+ if (repository?.databaseId !== job.repo.repoId || typeof repository.nameWithOwner !== 'string' || repository.nameWithOwner.toLowerCase() !== job.repo.github.toLowerCase()) continue
238
+ if (readPage(job, repository.item, metadata, allowed, refused.has(`r${index}`))) pending.push(job)
239
+ }
240
+ for (const job of duplicateJobs(jobs, byIssue.keys())) if (!pending.includes(job)) pending.push(job)
241
+ }
242
+ const updates = issueUpdates(jobs, byIssue, allowed, checkedAt, metadata)
243
+ return { fixes: [...metadata.values()], updates }
244
+ }
@@ -0,0 +1,47 @@
1
+ import type { ManagedConfig } from './config.ts'
2
+ import type { ManagedDb, ManagedSession } from './db.ts'
3
+ import { randomToken, safeEqual } from './crypto.ts'
4
+ import { ISSUE_STATE_COOKIE, buildCookie, clearCookie, cookieName, parseCookies } from './session.ts'
5
+ import { OAuthError, ensureUserAccessToken, exchangeCode, fetchIdentity } from './github-oauth.ts'
6
+
7
+ export const ISSUE_LOGIN_PATH = '/api/oauth/github/issues/login'
8
+
9
+ export function isIssueOAuthCallback(config: ManagedConfig, query: URLSearchParams, cookie: string | undefined): boolean {
10
+ const expected = parseCookies(cookie).get(cookieName(config, ISSUE_STATE_COOKIE))?.split('.')[0]
11
+ return !!expected && safeEqual(query.get('state') ?? '', expected)
12
+ }
13
+
14
+ export function issueLoginRedirect(config: ManagedConfig, session: ManagedSession, now = Date.now()) {
15
+ const state = randomToken()
16
+ const url = new URL('https://github.com/login/oauth/authorize')
17
+ url.searchParams.set('client_id', config.githubClientId)
18
+ url.searchParams.set('redirect_uri', config.oauthCallbackUrl)
19
+ url.searchParams.set('state', state)
20
+ url.searchParams.set('allow_signup', 'false')
21
+ // Reauthorize the same app for the current account, without replacing the
22
+ // DeepView session or permitting an OAuth account switch during creation.
23
+ const value = `${state}.${session.id}.${now}`
24
+ return { location: url.href, setCookie: buildCookie(cookieName(config, ISSUE_STATE_COOKIE), value,
25
+ { secure: config.cookieSecure, maxAgeS: 600, sameSite: 'Lax' }) }
26
+ }
27
+
28
+ export async function issueOAuthCallback(config: ManagedConfig, db: ManagedDb, session: ManagedSession,
29
+ query: URLSearchParams, cookie: string | undefined, fetchImpl: typeof fetch = fetch, now = Date.now()) {
30
+ const [expected, sessionId, timestamp] = (parseCookies(cookie).get(cookieName(config, ISSUE_STATE_COOKIE)) ?? '').split('.')
31
+ const code = query.get('code'), state = query.get('state')
32
+ if (!code || !state || !expected || !safeEqual(state, expected) || sessionId !== session.id
33
+ || !timestamp || !Number.isFinite(Number(timestamp)) || now < Number(timestamp) || now - Number(timestamp) > 600_000) {
34
+ throw new OAuthError(400, 'invalid-oauth-state')
35
+ }
36
+ const tokens = await exchangeCode(config, code, now, fetchImpl)
37
+ const identity = await fetchIdentity(tokens.accessToken, fetchImpl)
38
+ if (identity.githubUserId !== await db.getUserGithubId(session.userId)) throw new OAuthError(403, 'github-account-mismatch')
39
+ const current = await db.sessionWithUser(session.id, Date.now())
40
+ if (!current || current.user.role === 'none' || current.session.userId !== session.userId) throw new OAuthError(401, 'unauthenticated')
41
+ await db.setUserTokens(session.userId, tokens)
42
+ return { location: '/github-issue-authorized.html', setCookie: clearCookie(cookieName(config, ISSUE_STATE_COOKIE), config.cookieSecure) }
43
+ }
44
+
45
+ export function issueUserToken(config: ManagedConfig, db: ManagedDb, userId: string, fetchImpl: typeof fetch = fetch) {
46
+ return ensureUserAccessToken(config, db, userId, Date.now(), fetchImpl)
47
+ }
@@ -0,0 +1,155 @@
1
+ import type { ManagedConfig } from './config.ts'
2
+ import type { ManagedDb, ManagedSession } from './db.ts'
3
+ import type { BlobStore } from './blob-store.ts'
4
+ import type { ManagedIssue } from './managed-issues.ts'
5
+ import { randomToken } from './crypto.ts'
6
+ import { githubIssueClosedReason } from '../common/github-pr.ts'
7
+ import { reportEntries, reportRepoGithub } from '@preventive/report'
8
+ import { newIssueLabels } from '../common/github-issue-labels.js'
9
+ import { ignoresOwnRepo } from '../common/finding-repo.js'
10
+ import { appJwt, githubAppConfigured, installUrl, publicRepositoryName } from './github-app.ts'
11
+ import { ISSUE_LOGIN_PATH, issueUserToken } from './github-issue-oauth.ts'
12
+ import { TeamReportsError, loadTeamReports, recheckTeam, teamSnapshot } from './team-reports.ts'
13
+
14
+ export const MAX_ISSUE_BODY_BYTES = 512_000
15
+ export class IssueError extends Error {
16
+ status: number
17
+ constructor(status: number, message: string) { super(message); this.status = status }
18
+ }
19
+
20
+ type Context = { reportId: string; findingId: string; repository: string }
21
+ export function parseIssueContext(raw: unknown): Context {
22
+ const value = raw as Partial<Context> | null
23
+ const repository = publicRepositoryName(value?.repository)
24
+ if (!repository || typeof value?.reportId !== 'string' || !value.reportId || value.reportId.length > 200
25
+ || typeof value.findingId !== 'string' || !value.findingId || value.findingId.length > 4096) throw new IssueError(400, 'bad-request')
26
+ return { repository, reportId: value.reportId, findingId: value.findingId }
27
+ }
28
+
29
+ async function github(path: string, token: string, fetchImpl: typeof fetch, payload?: unknown) {
30
+ let response: Response
31
+ try {
32
+ response = await fetchImpl(`https://api.github.com${path}`, {
33
+ method: payload === undefined ? 'GET' : 'POST', redirect: 'error', signal: AbortSignal.timeout(15_000),
34
+ headers: { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json',
35
+ 'user-agent': 'deepview-triage', 'x-github-api-version': '2022-11-28', 'content-type': 'application/json' },
36
+ ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
37
+ })
38
+ } catch { throw new IssueError(502, payload === undefined ? 'github-unavailable' : 'github-create-uncertain') }
39
+ return response
40
+ }
41
+
42
+ function referenceResult(stored: ManagedIssue, repoIds: number[]) {
43
+ // A shared finding ID does not grant access to another team's repository.
44
+ if (!repoIds.includes(stored.repoId)) return { mode: 'unavailable' as const }
45
+ return stored.issueUrl ? { mode: 'existing' as const, url: stored.issueUrl }
46
+ : { mode: 'pending' as const, repositoryUrl: `https://github.com/${stored.repository}/issues` }
47
+ }
48
+
49
+ function issueDetails(raw: unknown, url: string, number: number, fallback: { title: string; body: string; labels: string[] }) {
50
+ const issue = raw as { title?: unknown; body?: unknown; state?: unknown; state_reason?: unknown;
51
+ user?: { login?: unknown }; labels?: ({ name?: unknown } | string)[] } | null
52
+ const status = issue?.state === 'closed' ? 'closed' : 'open'
53
+ return { url, number, title: typeof issue?.title === 'string' ? issue.title : fallback.title,
54
+ description: typeof issue?.body === 'string' ? issue.body : fallback.body, status,
55
+ stateReason: status === 'closed' ? githubIssueClosedReason(issue?.state_reason) : null,
56
+ author: typeof issue?.user?.login === 'string' ? issue.user.login : null,
57
+ labels: Array.isArray(issue?.labels) ? issue.labels.map(label => typeof label === 'string' ? label : label?.name).filter((label): label is string => typeof label === 'string') : fallback.labels }
58
+ }
59
+
60
+ // Authorize before any upstream lookup, including installation/label discovery.
61
+ // Report filtering also supplies the full row/link isSecurity classification.
62
+ export async function prepareGithubIssue(config: ManagedConfig, db: ManagedDb, store: BlobStore,
63
+ session: ManagedSession, teamId: string, context: Context, fetchImpl: typeof fetch = fetch) {
64
+ const snapshot = await teamSnapshot(db, session.id, teamId, context.reportId)
65
+ if (!snapshot.reports.some(report => report.id === context.reportId)) throw new TeamReportsError(404, 'no-report')
66
+ const reports = await loadTeamReports(db, store, snapshot)
67
+ const report = reports.find(item => item.id === context.reportId)!
68
+ const findings = (reportEntries(report.data) ?? []).flat() as Record<string, unknown>[]
69
+ const finding = findings.find(item => item['id'] === context.findingId)
70
+ if (!finding) throw new TeamReportsError(404, 'no-finding')
71
+ const recheck = () => recheckTeam(db, session.id, snapshot)
72
+ await recheck()
73
+ const labels = newIssueLabels(finding['isSecurity'] === true, config.githubNewIssueLabels ?? '')
74
+ const repoIds = snapshot.repositories.map(repo => repo.repoId)
75
+ const stored = await db.getManagedIssue(context.findingId)
76
+ if (stored) return { ...referenceResult(stored, repoIds), labels, recheck }
77
+ // The target comes from this finding's own source, or the report's managed
78
+ // assignment. Team membership alone must not let a caller claim an unrelated
79
+ // repository's issue as the permanent reference for this finding. One on an
80
+ // advisory naming the advised package's repository as its own is the
81
+ // report's (common/finding-repo.js).
82
+ const findingRepo = (ignoresOwnRepo(finding, report.repo.github) ? null : finding['repo']) as { github?: unknown } | null | undefined
83
+ const targetRepository = publicRepositoryName(reportRepoGithub({ repo: { github: findingRepo?.github || report.repo.github } }))
84
+ if (!targetRepository || targetRepository.toLowerCase() !== context.repository.toLowerCase()) throw new IssueError(400, 'bad-issue-repository')
85
+ const repository = snapshot.repositories.find(repo => repo.github.toLowerCase() === targetRepository.toLowerCase())
86
+ if (!repository || !githubAppConfigured(config)) return { mode: 'form' as const, labels, recheck }
87
+ const path = `/repos/${targetRepository.split('/').map(encodeURIComponent).join('/')}`
88
+ const installation = await github(`${path}/installation`, appJwt(config.githubAppId!, config.githubAppPrivateKey!), fetchImpl)
89
+ if (installation.status === 404) return { mode: 'form' as const, labels, recheck }
90
+ if (!installation.ok) throw new IssueError(502, 'github-unavailable')
91
+ let installed: { permissions?: { issues?: string } }
92
+ try { installed = await installation.json() } catch { throw new IssueError(502, 'github-unavailable') }
93
+ if (installed?.permissions?.issues !== 'write') return { mode: 'permissions' as const, authorizationPath: installUrl(config), labels, recheck }
94
+ const token = await issueUserToken(config, db, session.userId, fetchImpl)
95
+ if (!token) return { mode: 'authorize' as const, authorizationPath: ISSUE_LOGIN_PATH, labels, recheck }
96
+ // All requested labels are optional, including security and operator labels.
97
+ // Omit missing names rather than rejecting issue creation or creating labels.
98
+ const existingLabels: string[] = []
99
+ for (const name of labels) {
100
+ const label = await github(`${path}/labels/${encodeURIComponent(name)}`, token, fetchImpl)
101
+ if (label.status === 401) return { mode: 'authorize' as const, authorizationPath: ISSUE_LOGIN_PATH, labels, recheck }
102
+ if (label.status === 404) continue
103
+ if (!label.ok) throw new IssueError(502, 'github-unavailable')
104
+ existingLabels.push(name)
105
+ }
106
+ return { mode: 'api' as const, token, path, labels: existingLabels, recheck,
107
+ db, findingId: context.findingId, repoId: repository.repoId, repository: targetRepository, repoIds, userId: session.userId }
108
+ }
109
+
110
+ export async function createGithubIssue(prepared: Awaited<ReturnType<typeof prepareGithubIssue>>, input: unknown, fetchImpl: typeof fetch = fetch) {
111
+ if (prepared.mode !== 'api') throw new IssueError(409, 'github-authorization-required')
112
+ const { title, body } = input as { title?: unknown; body?: unknown }
113
+ if (typeof title !== 'string' || !title.trim() || title.length > 256 || typeof body !== 'string' || body.length > 65_536) throw new IssueError(400, 'bad-issue')
114
+ const { db, findingId } = prepared
115
+ const requestId = randomToken()
116
+ if (!await db.claimManagedIssue({ findingId, repoId: prepared.repoId, repository: prepared.repository,
117
+ requestId, createdBy: prepared.userId, createdAt: Date.now() })) {
118
+ const stored = await db.getManagedIssue(findingId)
119
+ await prepared.recheck()
120
+ // The competing request may have released its reservation after a definite
121
+ // failure. Still return a listing, never a fresh creation form, for this race.
122
+ return stored ? referenceResult(stored, prepared.repoIds)
123
+ : { mode: 'pending' as const, repositoryUrl: `https://github.com/${prepared.repository}/issues` }
124
+ }
125
+ // The last awaited operation before the external write checks current access.
126
+ // Release only when we know no issue was created; unknown outcomes stay claimed.
127
+ try { await prepared.recheck() }
128
+ catch (error) { await db.releaseManagedIssue(findingId, requestId); throw error }
129
+ const response = await github(`${prepared.path}/issues`, prepared.token, fetchImpl, { title: title.trim(), body, labels: prepared.labels })
130
+ if (response.status >= 400 && response.status < 500) await db.releaseManagedIssue(findingId, requestId)
131
+ if (response.status === 401) throw new IssueError(409, 'github-authorization-required')
132
+ if (response.status === 403) throw new IssueError(403, 'github-issue-forbidden')
133
+ if (!response.ok) throw new IssueError(response.status === 422 ? 422 : 502, response.status >= 500 ? 'github-create-uncertain' : 'github-create-failed')
134
+ let issue: { number?: unknown }
135
+ try { issue = await response.json() } catch { throw new IssueError(502, 'github-create-uncertain') }
136
+ if (!Number.isSafeInteger(issue?.number) || Number(issue.number) <= 0) throw new IssueError(502, 'github-create-uncertain')
137
+ // Construct the URL from validated inputs, never an upstream redirect target.
138
+ const number = Number(issue.number), url = `https://github.com${prepared.path.slice('/repos'.length)}/issues/${issue.number}`
139
+ if (!await db.finishManagedIssue(findingId, requestId, url)) throw new IssueError(502, 'github-create-uncertain')
140
+ let details = issueDetails(issue, url, number, { title, body, labels: prepared.labels }), detailsUnavailable = true
141
+ try {
142
+ const fetched = await github(`${prepared.path}/issues/${number}`, prepared.token, fetchImpl)
143
+ if (fetched.ok) {
144
+ details = issueDetails(await fetched.json(), url, number, { title, body, labels: prepared.labels })
145
+ detailsUnavailable = false
146
+ }
147
+ } catch { /* Creation and its permanent reference succeeded; detail reads are best effort. */ }
148
+ try { await prepared.recheck() }
149
+ catch {
150
+ // The external write and permanent reference succeeded. Withhold details
151
+ // if current access cannot be confirmed, but never advertise a safe retry.
152
+ return { mode: 'created-unavailable' as const }
153
+ }
154
+ return { url, issue: details, detailsUnavailable }
155
+ }
@@ -0,0 +1,69 @@
1
+ // Linking another GitHub account to the signed-in user (github-links.ts): the
2
+ // App's user authorization again, completed by the account to link. GitHub is
3
+ // asked for its account picker, as the browser is usually signed in to the
4
+ // account the user signs in here with. The token GitHub grants reads the
5
+ // account's identity and avatar; it is never stored.
6
+ import type { AvatarStore } from './avatar-store.ts'
7
+ import type { ManagedConfig } from './config.ts'
8
+ import type { ManagedDb, ManagedSession } from './db.ts'
9
+ import { randomToken, safeEqual } from './crypto.ts'
10
+ import { LINK_STATE_COOKIE, buildCookie, clearCookie, cookieName, parseCookies } from './session.ts'
11
+ import { OAuthError, cacheAvatar, exchangeCode, fetchIdentity } from './github-oauth.ts'
12
+ import { ManagedMutationError } from './management.ts'
13
+
14
+ export const LINK_LOGIN_PATH = '/api/oauth/github/link'
15
+ // The profile page, where linking starts and its callback lands.
16
+ const PROFILE_PATH = '/my/profile'
17
+ const STATE_TTL_MS = 600_000
18
+
19
+ export function isLinkOAuthCallback(config: ManagedConfig, query: URLSearchParams, cookie: string | undefined): boolean {
20
+ const expected = parseCookies(cookie).get(cookieName(config, LINK_STATE_COOKIE))?.split('.')[0]
21
+ return !!expected && safeEqual(query.get('state') ?? '', expected)
22
+ }
23
+
24
+ // The state is bound to the session that started linking, so the account
25
+ // links to the user who asked, never to whoever is signed in on return.
26
+ export function linkLoginRedirect(config: ManagedConfig, session: ManagedSession, now = Date.now()): { location: string; setCookie: string } {
27
+ const state = randomToken()
28
+ const url = new URL('https://github.com/login/oauth/authorize')
29
+ url.searchParams.set('client_id', config.githubClientId)
30
+ url.searchParams.set('redirect_uri', config.oauthCallbackUrl)
31
+ url.searchParams.set('state', state)
32
+ url.searchParams.set('allow_signup', 'false')
33
+ url.searchParams.set('prompt', 'select_account')
34
+ return { location: url.href, setCookie: buildCookie(cookieName(config, LINK_STATE_COOKIE), `${state}.${session.id}.${now}`,
35
+ { secure: config.cookieSecure, maxAgeS: STATE_TTL_MS / 1000, sameSite: 'Lax' }) }
36
+ }
37
+
38
+ // Back from GitHub: link the account that authorized, then land on the
39
+ // profile, naming the refusal (`link-error`) when it was refused.
40
+ // `linked` is the login of an account linked anew.
41
+ export async function linkOAuthCallback(config: ManagedConfig, db: ManagedDb, session: ManagedSession,
42
+ query: URLSearchParams, cookie: string | undefined,
43
+ { avatarStore, fetchImpl = fetch, now = Date.now() }: { avatarStore?: AvatarStore; fetchImpl?: typeof fetch; now?: number } = {},
44
+ ): Promise<{ location: string; setCookie: string; linked: string | null }> {
45
+ const setCookie = clearCookie(cookieName(config, LINK_STATE_COOKIE), config.cookieSecure)
46
+ try {
47
+ const [expected, sessionId, timestamp] = (parseCookies(cookie).get(cookieName(config, LINK_STATE_COOKIE)) ?? '').split('.')
48
+ const code = query.get('code'), started = Number(timestamp), state = query.get('state')
49
+ if (!state || !expected || !safeEqual(state, expected) || sessionId !== session.id
50
+ || !timestamp || !Number.isFinite(started) || now < started || now - started > STATE_TTL_MS) {
51
+ throw new OAuthError(400, 'invalid-oauth-state')
52
+ }
53
+ // Declined on GitHub's side, which sends an error in place of a code.
54
+ if (!code) throw new OAuthError(400, query.get('error') ? 'github-authorization-declined' : 'invalid-oauth-state')
55
+ const tokens = await exchangeCode(config, code, now, fetchImpl)
56
+ const account = await fetchIdentity(tokens.accessToken, fetchImpl)
57
+ const link = await db.linkGithubAccount(session.id, account, now)
58
+ // Best-effort, as at sign-in: the avatar falls back to an initial.
59
+ if (avatarStore != null && account.avatarUrl != null) {
60
+ await cacheAvatar(avatarStore, link.id, account.avatarUrl, fetchImpl).catch((err) => {
61
+ console.warn('managed: linked avatar cache failed:', err)
62
+ })
63
+ }
64
+ return { location: PROFILE_PATH, setCookie, linked: link.created ? account.login : null }
65
+ } catch (err) {
66
+ if (!(err instanceof OAuthError || err instanceof ManagedMutationError)) throw err
67
+ return { location: `${PROFILE_PATH}?${new URLSearchParams({ 'link-error': err.message })}`, setCookie, linked: null }
68
+ }
69
+ }