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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (442) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +16 -78
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +6 -0
  13. package/common/bundle-compare-diff.js +377 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-imports.js +20 -0
  20. package/common/bundle-metadata.d.ts +15 -0
  21. package/common/bundle-metadata.js +226 -0
  22. package/common/bundle-pkg-of.d.ts +1 -0
  23. package/common/bundle-pkg-of.js +90 -0
  24. package/common/bundle-reasons.d.ts +6 -0
  25. package/common/bundle-reasons.js +58 -0
  26. package/common/bundle-source-links.d.ts +6 -0
  27. package/common/bundle-source-links.js +216 -0
  28. package/common/bundle-sourcemap.d.ts +10 -0
  29. package/common/bundle-sourcemap.js +100 -0
  30. package/common/bundle-sources.d.ts +10 -0
  31. package/common/bundle-sources.js +374 -0
  32. package/common/bundle-stats.js +41 -0
  33. package/common/bundle-tabs.js +1 -0
  34. package/common/code-language.js +66 -0
  35. package/common/default-scan-models.ts +36 -0
  36. package/common/dependency-reviews.d.ts +18 -0
  37. package/common/dependency-reviews.js +64 -0
  38. package/common/finding-duplicates.js +63 -0
  39. package/common/finding-filters.js +313 -0
  40. package/common/finding-id.js +47 -0
  41. package/common/finding-repo.d.ts +5 -0
  42. package/common/finding-repo.js +67 -0
  43. package/common/github-issue-labels.d.ts +1 -0
  44. package/common/github-issue-labels.js +11 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +14 -0
  48. package/common/line-diff.js +181 -0
  49. package/common/linked-workspace-groups.js +63 -0
  50. package/common/managed/agent-tasks.ts +292 -0
  51. package/common/managed/comments.ts +43 -0
  52. package/common/managed/dependency-routes.js +25 -0
  53. package/common/managed/directory-packages.ts +28 -0
  54. package/common/managed/finding-detail.d.ts +5 -0
  55. package/common/managed/finding-detail.js +75 -0
  56. package/common/managed/finding-values.d.ts +2 -0
  57. package/common/managed/finding-values.js +138 -0
  58. package/common/managed/github-agents.ts +114 -0
  59. package/common/managed/github-logins.ts +49 -0
  60. package/common/managed/lite-name.d.ts +2 -0
  61. package/common/managed/lite-name.js +20 -0
  62. package/common/managed/npm-packages.d.ts +9 -0
  63. package/common/managed/npm-packages.js +63 -0
  64. package/common/managed/permissions.ts +31 -0
  65. package/common/managed/report-content.ts +72 -0
  66. package/common/managed/report-filter.ts +120 -0
  67. package/common/managed/repository-alias.ts +65 -0
  68. package/common/managed/review-view-routes.js +23 -0
  69. package/common/managed/risk-routes.js +30 -0
  70. package/common/managed/roles.ts +41 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +385 -0
  73. package/common/managed/scan-models.ts +6 -0
  74. package/common/managed/stasis-config.ts +7 -0
  75. package/common/managed/team-app.d.ts +19 -0
  76. package/common/managed/team-app.js +129 -0
  77. package/common/managed/team-filters.js +26 -0
  78. package/common/managed/triage.ts +83 -0
  79. package/common/managed/upload-seal.ts +126 -0
  80. package/common/pretty-json.js +98 -0
  81. package/common/pretty-kinds.js +20 -0
  82. package/common/pretty-print.d.ts +6 -0
  83. package/common/pretty-print.js +36 -0
  84. package/common/pretty-sourcemap.js +70 -0
  85. package/common/repo-commit.d.ts +4 -0
  86. package/common/repo-commit.js +30 -0
  87. package/common/revalidation-conflicts.js +48 -0
  88. package/common/revalidation-input-groups.js +56 -0
  89. package/common/save-error-reason.ts +20 -7
  90. package/common/scan-server.ts +13 -0
  91. package/common/security-links.d.ts +5 -0
  92. package/common/security-links.js +33 -0
  93. package/common/server-info.ts +46 -0
  94. package/common/sourcemap-listing.js +78 -0
  95. package/common/sourcemap-mappings.js +136 -0
  96. package/common/sourcemap-unlist.js +85 -0
  97. package/common/stasis-files.d.ts +5 -0
  98. package/common/stasis-files.js +20 -0
  99. package/common/stasis-tgz.d.ts +6 -0
  100. package/common/stasis-tgz.js +27 -0
  101. package/common/utf8.d.ts +3 -0
  102. package/common/utf8.js +45 -0
  103. package/common/whitespace-insensitive.js +19 -0
  104. package/common/workspace-app.js +91 -0
  105. package/common/workspace-groups.js +176 -0
  106. package/out/activity.js +2 -0
  107. package/out/brotli-fallback.js +3 -3
  108. package/out/chunk-2XUEZHIP.js +28 -0
  109. package/out/chunk-55YIWY3H.js +5 -0
  110. package/out/chunk-5AVGKFMR.js +1 -0
  111. package/out/chunk-5CJKUV53.js +1 -0
  112. package/out/chunk-5EAVJAD2.js +3 -0
  113. package/out/chunk-5M2X3QPK.js +6 -0
  114. package/out/chunk-5QWPKTCE.js +40 -0
  115. package/out/chunk-6CCSTJWB.js +1 -0
  116. package/out/chunk-6VOB5WXX.js +2 -0
  117. package/out/chunk-6Y6PZ2BU.js +9 -0
  118. package/out/chunk-74JZTGTO.js +11 -0
  119. package/out/chunk-7BKKYVWR.js +7 -0
  120. package/out/chunk-7C7DWL7I.js +1 -0
  121. package/out/chunk-7HP2VYIC.js +2 -0
  122. package/out/chunk-7YFJUT2P.js +1 -0
  123. package/out/chunk-7YO4QV5P.js +1 -0
  124. package/out/chunk-A4BBBHQU.js +1 -0
  125. package/out/chunk-B64CTMVU.js +4 -0
  126. package/out/chunk-BEKYZCPX.js +14 -0
  127. package/out/chunk-C4Z6ZBXV.js +10 -0
  128. package/out/chunk-CU3FPB3P.js +1 -0
  129. package/out/chunk-DEVAORP2.js +1 -0
  130. package/out/chunk-DUASGS2O.js +8 -0
  131. package/out/chunk-DUS5ARE2.js +53 -0
  132. package/out/chunk-EEJA7JBI.js +13 -0
  133. package/out/chunk-FSU2PLJL.js +1 -0
  134. package/out/chunk-GBMAXAYK.js +3 -0
  135. package/out/chunk-GO7FT4OD.js +1 -0
  136. package/out/chunk-GX5UXWT4.js +1 -0
  137. package/out/chunk-ITUKKCCK.js +10 -0
  138. package/out/chunk-IYPY47MC.js +1 -0
  139. package/out/chunk-JXBRWLMA.js +4 -0
  140. package/out/chunk-K4XJHM2T.js +1 -0
  141. package/out/chunk-LBD3M3J6.js +1 -0
  142. package/out/chunk-LVSLM7HB.js +1 -0
  143. package/out/chunk-LVW7WWV4.js +1 -0
  144. package/out/chunk-MV66NL3G.js +3 -0
  145. package/out/chunk-N57OWFKY.js +15 -0
  146. package/out/chunk-NRPC74AM.js +1 -0
  147. package/out/chunk-OOJM4CTU.js +1 -0
  148. package/out/chunk-OWSEQOL5.js +1 -0
  149. package/out/chunk-PKLVXUEI.js +11 -0
  150. package/out/chunk-PLGH63UC.js +2 -0
  151. package/out/chunk-PNHBZGDD.js +1 -0
  152. package/out/chunk-PTFYDJUP.js +1 -0
  153. package/out/chunk-PWFUOLZK.js +17 -0
  154. package/out/chunk-PXK7EU4V.js +1 -0
  155. package/out/chunk-QD3IBSF4.js +7 -0
  156. package/out/chunk-QI66YA4F.js +1 -0
  157. package/out/chunk-QRKFPLA4.js +80 -0
  158. package/out/chunk-R3NZFXVR.js +1 -0
  159. package/out/chunk-R5O6FAW4.js +2 -0
  160. package/out/chunk-RPNO56H2.js +1 -0
  161. package/out/chunk-SSPDMA6D.js +1 -0
  162. package/out/chunk-SZWPYLPC.js +1 -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-VHEXSGGP.js +1 -0
  168. package/out/chunk-VYYUMYVW.js +9 -0
  169. package/out/chunk-VZPPX6MV.js +1 -0
  170. package/out/chunk-WCDYSIKG.js +1 -0
  171. package/out/chunk-XM4RLC4A.js +2 -0
  172. package/out/chunk-YKCRCNYZ.js +266 -0
  173. package/out/chunk-ZQHLECTI.js +1 -0
  174. package/out/client-managed-import.js +4 -0
  175. package/out/client-managed.js +37 -0
  176. package/out/client-sync.js +11 -17
  177. package/out/compare.js +26 -0
  178. package/out/dialogs.js +40 -0
  179. package/out/github-issue-authorized.html +3 -0
  180. package/out/github-issue-authorized.js +1 -0
  181. package/out/graph.js +19 -4
  182. package/out/index.html +104 -24
  183. package/out/prism.js +14 -10
  184. package/out/scan.js +2 -0
  185. package/out/stasis.svg +20 -0
  186. package/out/terminal.js +367 -39
  187. package/out/view.css +1 -1
  188. package/out/view.js +19 -147
  189. package/package.json +409 -64
  190. package/risk/actions/findings.js +161 -0
  191. package/risk/actions/resolve.js +287 -0
  192. package/risk/actions/scripts/commands.js +182 -0
  193. package/risk/actions/scripts/grade.js +113 -0
  194. package/risk/actions/scripts/packages.js +123 -0
  195. package/risk/actions/scripts/shell.js +169 -0
  196. package/risk/actions/uses.js +94 -0
  197. package/risk/actions/workflow.js +183 -0
  198. package/risk/files/characters.js +341 -0
  199. package/risk/files/hosts.js +206 -0
  200. package/risk/files/readability.js +185 -0
  201. package/risk/files/runs-code.js +563 -0
  202. package/risk/files/script.js +402 -0
  203. package/risk/files/source-map-link.js +43 -0
  204. package/risk/files/stamps.js +47 -0
  205. package/risk/index.d.ts +294 -0
  206. package/risk/index.js +12 -0
  207. package/risk/npm/assess.js +285 -0
  208. package/risk/npm/combined.js +68 -0
  209. package/risk/npm/compare.js +236 -0
  210. package/risk/npm/dependencies.js +172 -0
  211. package/risk/npm/diff.js +79 -0
  212. package/risk/npm/downloads.js +84 -0
  213. package/risk/npm/files.js +445 -0
  214. package/risk/npm/held.js +67 -0
  215. package/risk/npm/install-scripts.js +34 -0
  216. package/risk/npm/malware.js +38 -0
  217. package/risk/npm/manifest.js +65 -0
  218. package/risk/npm/new-dependency.js +60 -0
  219. package/risk/npm/old-version.js +108 -0
  220. package/risk/npm/registry.js +393 -0
  221. package/risk/npm/release.js +85 -0
  222. package/risk/npm/score.js +59 -0
  223. package/risk/npm/specs.js +124 -0
  224. package/risk/npm/tarball.js +169 -0
  225. package/server-common/database-config.ts +16 -0
  226. package/server-common/initialize.ts +18 -0
  227. package/server-common/npm-advisories.ts +101 -0
  228. package/{server → server-common}/origin.ts +5 -5
  229. package/server-common/reap.ts +48 -0
  230. package/server-common/scan-config.ts +19 -0
  231. package/server-common/standalone.ts +29 -0
  232. package/server-common/storage-crypto.ts +182 -0
  233. package/server-common/storage-log.ts +38 -0
  234. package/server-common/vercel-blob.ts +103 -0
  235. package/server-e2e/app.ts +487 -0
  236. package/{server → server-e2e}/bus-receiver.ts +2 -1
  237. package/{server → server-e2e}/cli.js +9 -4
  238. package/{server → server-e2e}/config.ts +50 -42
  239. package/{server → server-e2e}/db-neon.ts +2 -2
  240. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  241. package/{server → server-e2e}/db-stmt.ts +2 -2
  242. package/{server → server-e2e}/db.ts +7 -7
  243. package/{server → server-e2e}/http.ts +44 -13
  244. package/{server → server-e2e}/hub.ts +40 -9
  245. package/server-e2e/index.ts +17 -0
  246. package/server-e2e/lifecycle.ts +95 -0
  247. package/{server → server-e2e}/neon-driver.ts +2 -2
  248. package/{server → server-e2e}/npm-proxy.ts +12 -145
  249. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  250. package/{server → server-e2e}/objstore/blob.ts +1 -1
  251. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  252. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  253. package/{server → server-e2e}/objstore/init.ts +19 -27
  254. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  255. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  257. package/{server → server-e2e}/objstore/rest.ts +3 -3
  258. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  259. package/{server → server-e2e}/objstore/store.ts +7 -7
  260. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  261. package/{server → server-e2e}/pubsub.ts +12 -9
  262. package/{server → server-e2e}/sign.ts +4 -4
  263. package/{server → server-e2e}/sse-server.ts +60 -33
  264. package/{server → server-e2e}/static.ts +18 -17
  265. package/{server → server-e2e}/sync-handlers.ts +64 -30
  266. package/{server → server-e2e}/ws-server.ts +20 -9
  267. package/server-managed/activity.ts +247 -0
  268. package/server-managed/agent-merges.ts +109 -0
  269. package/server-managed/app-agents.ts +23 -0
  270. package/server-managed/avatar-store.ts +13 -0
  271. package/server-managed/blob-store.ts +26 -0
  272. package/server-managed/brotli.ts +10 -0
  273. package/server-managed/bundle-advisories.ts +79 -0
  274. package/server-managed/bundle-advisory-inventory.ts +85 -0
  275. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  276. package/server-managed/bundle-build-diagnostics.js +23 -0
  277. package/server-managed/bundle-build-leases.ts +41 -0
  278. package/server-managed/bundle-build-worker.js +380 -0
  279. package/server-managed/bundle-build.ts +326 -0
  280. package/server-managed/bundle-cache.ts +261 -0
  281. package/server-managed/bundle-catalog.ts +29 -0
  282. package/server-managed/bundle-commits.ts +133 -0
  283. package/server-managed/bundle-dependency-reviews.ts +91 -0
  284. package/server-managed/bundle-store.ts +24 -0
  285. package/server-managed/bundle-summary-cache.ts +139 -0
  286. package/server-managed/bundle-validation.ts +33 -0
  287. package/server-managed/bundle.ts +151 -0
  288. package/server-managed/cache-storage.ts +20 -0
  289. package/server-managed/cli.js +21 -0
  290. package/server-managed/combined.ts +43 -0
  291. package/server-managed/comments.ts +138 -0
  292. package/server-managed/commit-coauthors.ts +105 -0
  293. package/server-managed/commit-lockfiles.ts +78 -0
  294. package/server-managed/comparison.ts +51 -0
  295. package/server-managed/config.ts +163 -0
  296. package/server-managed/content-access.ts +15 -0
  297. package/server-managed/crypto.ts +25 -0
  298. package/server-managed/db-methods.ts +1914 -0
  299. package/server-managed/db-neon.ts +398 -0
  300. package/server-managed/db-schema.ts +263 -0
  301. package/server-managed/db-table-names.ts +22 -0
  302. package/server-managed/db.ts +149 -0
  303. package/server-managed/dependabot-access.ts +61 -0
  304. package/server-managed/dependabot-alerts.ts +180 -0
  305. package/server-managed/dependency-review-comments.ts +143 -0
  306. package/server-managed/dependency-reviews.ts +369 -0
  307. package/server-managed/github-accounts.ts +59 -0
  308. package/server-managed/github-actions.ts +71 -0
  309. package/server-managed/github-app.ts +347 -0
  310. package/server-managed/github-errors.ts +92 -0
  311. package/server-managed/github-graphql.ts +42 -0
  312. package/server-managed/github-issue-links.ts +264 -0
  313. package/server-managed/github-issue-oauth.ts +30 -0
  314. package/server-managed/github-issues.ts +157 -0
  315. package/server-managed/github-link-oauth.ts +56 -0
  316. package/server-managed/github-links.ts +204 -0
  317. package/server-managed/github-metadata.ts +213 -0
  318. package/server-managed/github-oauth.ts +264 -0
  319. package/server-managed/github-pulls.ts +257 -0
  320. package/server-managed/github-requests.ts +181 -0
  321. package/server-managed/github-users.ts +30 -0
  322. package/server-managed/github-values.ts +26 -0
  323. package/server-managed/history-windows.ts +172 -0
  324. package/server-managed/http-response.ts +76 -0
  325. package/server-managed/http.ts +6324 -0
  326. package/server-managed/import-triage.ts +51 -0
  327. package/server-managed/index.ts +204 -0
  328. package/server-managed/kept-briefly.ts +37 -0
  329. package/server-managed/kept.ts +28 -0
  330. package/server-managed/link-reports.ts +149 -0
  331. package/server-managed/listed-activity.ts +39 -0
  332. package/server-managed/locked-packages.ts +234 -0
  333. package/server-managed/lockfile-scope.ts +58 -0
  334. package/server-managed/lru.ts +30 -0
  335. package/server-managed/managed-issues.ts +92 -0
  336. package/server-managed/management-catalog.ts +45 -0
  337. package/server-managed/management.ts +116 -0
  338. package/server-managed/npm-delta-worker.js +142 -0
  339. package/server-managed/npm-delta.ts +277 -0
  340. package/server-managed/npm-insights.ts +455 -0
  341. package/server-managed/npm-kept.ts +265 -0
  342. package/server-managed/npm-loads.ts +259 -0
  343. package/server-managed/npm-manifest.ts +117 -0
  344. package/server-managed/npm-packages.ts +469 -0
  345. package/server-managed/npm-patch-paths.ts +86 -0
  346. package/server-managed/npm-patch.ts +455 -0
  347. package/server-managed/npm-provenance.ts +127 -0
  348. package/server-managed/npm-risk.ts +287 -0
  349. package/server-managed/object-storage-disk.ts +147 -0
  350. package/server-managed/object-storage-vercel.ts +71 -0
  351. package/server-managed/object-storage.ts +82 -0
  352. package/server-managed/package-entry-points.ts +127 -0
  353. package/server-managed/pretty-copies.ts +22 -0
  354. package/server-managed/pretty-format.d.ts +3 -0
  355. package/server-managed/pretty-format.js +13 -0
  356. package/server-managed/pretty-print.ts +442 -0
  357. package/server-managed/public-workspace.ts +243 -0
  358. package/server-managed/pull-comment-reviews.ts +161 -0
  359. package/server-managed/pull-dependencies.ts +370 -0
  360. package/server-managed/pull-dependency-reviews.ts +407 -0
  361. package/server-managed/pull-reviews.ts +202 -0
  362. package/server-managed/queue.ts +54 -0
  363. package/server-managed/release-commits.ts +85 -0
  364. package/server-managed/rename-diff-worker.js +30 -0
  365. package/server-managed/rename-diff.ts +237 -0
  366. package/server-managed/repo-path.ts +21 -0
  367. package/server-managed/report-migration.ts +32 -0
  368. package/server-managed/report-opening.ts +77 -0
  369. package/server-managed/report-query.ts +10 -0
  370. package/server-managed/report-response.ts +16 -0
  371. package/server-managed/report-sources.ts +185 -0
  372. package/server-managed/report-store.ts +77 -0
  373. package/server-managed/repository-actions.ts +220 -0
  374. package/server-managed/repository-agents.ts +422 -0
  375. package/server-managed/repository-aliases.ts +119 -0
  376. package/server-managed/repository-browser.ts +361 -0
  377. package/server-managed/repository-changes.ts +280 -0
  378. package/server-managed/repository-code.ts +222 -0
  379. package/server-managed/repository-dependency-reviews.ts +182 -0
  380. package/server-managed/repository-discovery.ts +83 -0
  381. package/server-managed/repository-history.ts +428 -0
  382. package/server-managed/repository-issues.ts +293 -0
  383. package/server-managed/repository-policy.ts +27 -0
  384. package/server-managed/repository-pulls.ts +207 -0
  385. package/server-managed/repository-pulse.ts +477 -0
  386. package/server-managed/repository-risk-assess.ts +108 -0
  387. package/server-managed/repository-risk-audit.ts +78 -0
  388. package/server-managed/repository-risk-caches.ts +37 -0
  389. package/server-managed/repository-risk-read.ts +260 -0
  390. package/server-managed/repository-risk-stasis.ts +61 -0
  391. package/server-managed/repository-risk-turn.ts +97 -0
  392. package/server-managed/repository-risk.ts +516 -0
  393. package/server-managed/repository-squashes.ts +160 -0
  394. package/server-managed/repository-stamp.ts +41 -0
  395. package/server-managed/request-timing.ts +63 -0
  396. package/server-managed/reviewed-dependencies.ts +170 -0
  397. package/server-managed/revisions.ts +35 -0
  398. package/server-managed/scan-downloads.ts +121 -0
  399. package/server-managed/session.ts +132 -0
  400. package/server-managed/slugs.ts +38 -0
  401. package/server-managed/solidity-entry-points.ts +71 -0
  402. package/server-managed/sql-postgres.ts +34 -0
  403. package/server-managed/sql.ts +107 -0
  404. package/server-managed/stasis-config.ts +147 -0
  405. package/server-managed/stasis-dependencies.ts +221 -0
  406. package/server-managed/static.ts +28 -0
  407. package/server-managed/storage-command.ts +16 -0
  408. package/server-managed/storage-db.ts +183 -0
  409. package/server-managed/storage-encryption.ts +288 -0
  410. package/server-managed/storage-maintenance.ts +259 -0
  411. package/server-managed/storage-payload.ts +121 -0
  412. package/server-managed/storage-stores.ts +91 -0
  413. package/server-managed/storage.ts +82 -0
  414. package/server-managed/team-app-summaries.ts +56 -0
  415. package/server-managed/team-app.ts +156 -0
  416. package/server-managed/team-catalog.ts +7 -0
  417. package/server-managed/team-feed.ts +180 -0
  418. package/server-managed/team-npm-scopes.ts +103 -0
  419. package/server-managed/team-reports.ts +368 -0
  420. package/server-managed/triage-response.ts +16 -0
  421. package/server-managed/type-only-proof.js +161 -0
  422. package/server-managed/type-only-worker.js +31 -0
  423. package/server-managed/type-only.ts +135 -0
  424. package/server-managed/uploads.ts +106 -0
  425. package/server-managed/upstream-cache.ts +256 -0
  426. package/server-managed/view-as.ts +58 -0
  427. package/server-managed/worker-turns.ts +76 -0
  428. package/server-managed/workspace-shares.ts +170 -0
  429. package/server.ts +70 -0
  430. package/strip-types-loader.js +13 -10
  431. package/server/index.ts +0 -480
  432. package/server/lifecycle.ts +0 -208
  433. /package/{LICENSE → LICENSE-MIT} +0 -0
  434. /package/{server → server-e2e}/auth.ts +0 -0
  435. /package/{server → server-e2e}/config.example.json +0 -0
  436. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  437. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  438. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  439. /package/{server → server-e2e}/peer.ts +0 -0
  440. /package/{server → server-e2e}/sse-session.ts +0 -0
  441. /package/{server → server-e2e}/util.ts +0 -0
  442. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,347 @@
1
+ // Repository discovery uses the signed-in user token and App installation
2
+ // tokens. Login and repository installation can use one GitHub App: user
3
+ // authorization requests account permissions, installation grants repository
4
+ // permissions. Discovery itself is read-only and skips archived repositories.
5
+ import { Buffer } from 'node:buffer'
6
+ import { createHash, createSign } from 'node:crypto'
7
+ import { createClient } from '@preventive/upstream/github.js'
8
+ import type { ManagedConfig } from './config.ts'
9
+ import { GithubApiError, upstreamGithub } from './github-errors.ts'
10
+ import { GITHUB_API, USER_AGENT, githubJson, onTokenRejected, repoApi } from './github-requests.ts'
11
+ import { isId } from './github-values.ts'
12
+ import { eachOf } from './queue.ts'
13
+
14
+ const PER_PAGE = 100
15
+ // Bound fan-out while keeping independent installations/permission checks off
16
+ // one long serial critical path. eachOf preserves input order for
17
+ // deterministic merges.
18
+ const GITHUB_REQUESTS_AT_ONCE = 4
19
+ const INSTALLATION_TOKEN_TTL_MS = 5 * 60_000
20
+ const INSTALLATION_TOKEN_EXPIRY_MARGIN_MS = 60_000
21
+ const MAX_INSTALLATION_TOKENS = 256
22
+ interface InstallationTokenEntry { token: string | null; expiresAt: number; pending: Promise<string> | null }
23
+ // Credentials only: visibility, user identities, and permissions are never
24
+ // cached here. Bound memory per transport and separate App/key/install scopes.
25
+ const installationTokens = new WeakMap<typeof fetch, Map<string, InstallationTokenEntry>>()
26
+
27
+ // A token GitHub rejected (401): an installation's no longer reused.
28
+ onTokenRejected((token, fetchImpl) => {
29
+ const cache = installationTokens.get(fetchImpl)
30
+ if (!cache) return
31
+ for (const [key, entry] of cache) if (entry.token === token) cache.delete(key)
32
+ })
33
+
34
+ // One listed repository. Carries the context to read its contents later:
35
+ // `installationId` mints an App installation token (Contents: Read) for a repo
36
+ // reached through an installation — null for a public repo listed off the user
37
+ // token, readable without the App — and `defaultBranch` is the ref to read.
38
+ export interface ConnectedRepo {
39
+ id: number
40
+ fullName: string
41
+ private: boolean
42
+ visibility: 'public' | 'private' | 'internal' | null
43
+ htmlUrl: string
44
+ defaultBranch: string
45
+ installationId: number | null
46
+ }
47
+
48
+ // App installation credentials are configured (id + private key present) →
49
+ // private repos can be listed via its installation tokens.
50
+ export function githubAppConfigured(config: ManagedConfig): boolean {
51
+ return config.githubAppId != null && config.githubAppPrivateKey != null
52
+ }
53
+
54
+ // The install URL for the repositories App ("Connect a repository"), or null
55
+ // when no slug is set.
56
+ export function installUrl(config: ManagedConfig): string | null {
57
+ if (config.githubAppSlug == null) return null
58
+ return `https://github.com/apps/${encodeURIComponent(config.githubAppSlug)}/installations/new`
59
+ }
60
+
61
+ // Merge repo lists from every source, deduped by full name and sorted. Later
62
+ // sources win a collision (the handler lists private after public).
63
+ export function mergeRepos(...lists: ConnectedRepo[][]): ConnectedRepo[] {
64
+ const byName = new Map<string, ConnectedRepo>()
65
+ for (const list of lists) {
66
+ for (const repo of list) byName.set(repo.fullName, repo)
67
+ }
68
+ return [...byName.values()].toSorted((a, b) => a.fullName.localeCompare(b.fullName))
69
+ }
70
+
71
+ // Validate one repo object into a ConnectedRepo (or null to skip), tagging it
72
+ // with the installation it was reached through (null for the user-token path). A
73
+ // missing numeric id or full name → skip (can't key/locate it). Archived repos
74
+ // are skipped — read-only history, not triage targets.
75
+ function parseRepo(raw: unknown, installationId: number | null): ConnectedRepo | null {
76
+ if (raw == null || typeof raw !== 'object') return null
77
+ if ((raw as { archived?: unknown }).archived === true) return null
78
+ const id = (raw as { id?: unknown }).id
79
+ const fullName = (raw as { full_name?: unknown }).full_name
80
+ if (!isId(id)) return null
81
+ if (typeof fullName !== 'string' || fullName === '') return null
82
+ const htmlUrl = (raw as { html_url?: unknown }).html_url
83
+ const branch = (raw as { default_branch?: unknown }).default_branch
84
+ const visibility = (raw as { visibility?: unknown }).visibility
85
+ return {
86
+ id,
87
+ fullName,
88
+ private: (raw as { private?: unknown }).private === true,
89
+ visibility: visibility === 'public' || visibility === 'private' || visibility === 'internal' ? visibility : null,
90
+ htmlUrl: typeof htmlUrl === 'string' ? htmlUrl : '',
91
+ defaultBranch: typeof branch === 'string' ? branch : '',
92
+ installationId,
93
+ }
94
+ }
95
+
96
+ // Accept an owner/repo or exact GitHub repository URL, never an arbitrary API
97
+ // path. Reject traversal and encoded separators before constructing a fixed URL.
98
+ export function publicRepositoryName(raw: unknown): string | null {
99
+ if (typeof raw !== 'string') return null
100
+ const name = raw.trim().replace(/^https:\/\/github\.com\//iu, '').replace(/\/$/u, '')
101
+ if (!/^[a-z\d](?:[a-z\d-]{0,38})\/[a-z\d_.-]{1,100}$/iu.test(name)) return null
102
+ if (['.', '..'].includes(name.split('/')[1]!)) return null
103
+ return name
104
+ }
105
+
106
+ // Public additions must be readable by the server without the acting user's
107
+ // credentials. Require explicit public visibility and use GitHub's canonical
108
+ // metadata, never client-supplied ids, installation ids, or branches.
109
+ export async function fetchPublicRepository(fullName: string): Promise<ConnectedRepo> {
110
+ if (publicRepositoryName(fullName) !== fullName) throw new GithubApiError(400, 'bad-repository')
111
+ const repo = parseRepo(await upstreamGithub(() => createClient({ token: null, userAgent: USER_AGENT }).getRepo({ repo: fullName })), null)
112
+ if (repo == null || repo.private || repo.visibility !== 'public') throw new GithubApiError(409, 'repo-not-public')
113
+ if (publicRepositoryName(repo.fullName) !== repo.fullName || repo.fullName.toLowerCase() !== fullName.toLowerCase()) throw new GithubApiError(502, 'github-malformed')
114
+ return { ...repo, htmlUrl: `https://github.com/${repo.fullName}` }
115
+ }
116
+
117
+ // ── PUBLIC: the user's own repos via their login token ──
118
+
119
+ // List the authenticated user's repositories (GET /user/repos), paginated until
120
+ // a short page, deduped + sorted. With an identity-only token this returns the
121
+ // user's PUBLIC repos. READ-ONLY.
122
+ export async function listUserRepos(accessToken: string): Promise<ConnectedRepo[]> {
123
+ const body = await upstreamGithub(() => createClient({ token: accessToken, userAgent: USER_AGENT }).listUserRepos())
124
+ return mergeRepos(body.flatMap(r => parseRepo(r, null) ?? []))
125
+ }
126
+
127
+ // ── PRIVATE: App installations via installation tokens ──
128
+
129
+ function base64url(input: Buffer | string): string {
130
+ return Buffer.from(input).toString('base64url')
131
+ }
132
+
133
+ // Mint a short-lived App JWT (RS256) for the repositories App. iat backdated 60s
134
+ // for clock skew; exp 8 min out (within GitHub's 10-min cap); iss = the App id.
135
+ export function appJwt(appId: string, privateKeyPem: string, now: number = Date.now()): string {
136
+ const seconds = Math.floor(now / 1000)
137
+ const iat = seconds - 60
138
+ const header = base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }))
139
+ const payload = base64url(JSON.stringify({ iat, exp: seconds + 480, iss: appId }))
140
+ const signingInput = `${header}.${payload}`
141
+ return `${signingInput}.${base64url(createSign('RSA-SHA256').update(signingInput).sign(privateKeyPem))}`
142
+ }
143
+
144
+ // The repositories App's installation ids (one per org/user that installed it).
145
+ async function listInstallationIds(jwt: string, fetchImpl: typeof fetch): Promise<number[]> {
146
+ const ids: number[] = []
147
+ for (let page = 1; ; page++) {
148
+ const body = await githubJson(`${GITHUB_API}/app/installations?per_page=${PER_PAGE}&page=${page}`, jwt, fetchImpl)
149
+ if (!Array.isArray(body)) throw new GithubApiError(502, 'github-malformed')
150
+ for (const inst of body) {
151
+ const id = (inst as { id?: unknown }).id
152
+ if (isId(id)) ids.push(id)
153
+ }
154
+ if (body.length < PER_PAGE) break
155
+ }
156
+ return ids
157
+ }
158
+
159
+ // Reuse installation credentials only in this process. Refresh well before
160
+ // expiry and coalesce concurrent mints; failed or undated tokens are not cached.
161
+ async function installationAccessToken(appId: string, privateKey: string, installId: number, fetchImpl: typeof fetch): Promise<string> {
162
+ let cache = installationTokens.get(fetchImpl)
163
+ if (!cache) { cache = new Map(); installationTokens.set(fetchImpl, cache) }
164
+ const now = Date.now()
165
+ for (const [key, entry] of cache) if (!entry.pending && entry.expiresAt <= now) cache.delete(key)
166
+ const key = JSON.stringify([appId, createHash('sha256').update(privateKey).digest('hex'), installId])
167
+ const cached = cache.get(key)
168
+ if (cached) {
169
+ cache.delete(key)
170
+ cache.set(key, cached)
171
+ if (cached.pending) return cached.pending
172
+ return cached.token!
173
+ }
174
+ const entry: InstallationTokenEntry = { token: null, expiresAt: 0, pending: null }
175
+ const pending = Promise.resolve().then(async () => {
176
+ try {
177
+ const jwt = appJwt(appId, privateKey)
178
+ const body = await githubJson(`${GITHUB_API}/app/installations/${installId}/access_tokens`, jwt, fetchImpl, 'POST') as { token?: unknown; expires_at?: unknown }
179
+ if (typeof body?.token !== 'string' || body.token === '') throw new GithubApiError(502, 'github-install-token-denied')
180
+ entry.token = body.token
181
+ const expiresAt = typeof body.expires_at === 'string' ? Date.parse(body.expires_at) : NaN
182
+ entry.expiresAt = Number.isFinite(expiresAt) ? Math.min(now + INSTALLATION_TOKEN_TTL_MS, expiresAt - INSTALLATION_TOKEN_EXPIRY_MARGIN_MS) : 0
183
+ if (entry.expiresAt <= Date.now() && cache.get(key) === entry) cache.delete(key)
184
+ return body.token
185
+ } catch (err) {
186
+ if (cache.get(key) === entry) cache.delete(key)
187
+ throw err
188
+ } finally { entry.pending = null }
189
+ })
190
+ entry.pending = pending
191
+ cache.set(key, entry)
192
+ if (cache.size > MAX_INSTALLATION_TOKENS) cache.delete(cache.keys().next().value!)
193
+ return await pending
194
+ }
195
+
196
+ // Resolve this exact repository with the App's identity, then confirm the
197
+ // installation token reaches the same numeric repository. A missing grant is
198
+ // actionable through installation; transport/auth/rate errors must stay errors.
199
+ export async function repositoryInstallation(config: ManagedConfig, repoId: number, fullName: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<number | null> {
200
+ const { githubAppId, githubAppPrivateKey } = config
201
+ if (githubAppId == null || githubAppPrivateKey == null) throw new GithubApiError(503, 'github-app-not-configured')
202
+ if (publicRepositoryName(fullName) !== fullName) throw new GithubApiError(409, 'repo-identity-changed')
203
+ const jwt = appJwt(githubAppId, githubAppPrivateKey)
204
+ let raw
205
+ try { raw = await githubJson(`${repoApi(fullName)}/installation`, jwt, fetchImpl) } catch (err) {
206
+ if (err instanceof GithubApiError && err.status === 404) return null
207
+ throw err
208
+ }
209
+ const installation = raw as { id?: unknown; suspended_at?: unknown; permissions?: { contents?: unknown } } | null
210
+ const id = installation?.id
211
+ if (!isId(id)) throw new GithubApiError(502, 'github-malformed')
212
+ if (installation?.suspended_at != null || !['read', 'write'].includes(String(installation?.permissions?.contents))) return null
213
+ const token = await installationAccessToken(githubAppId, githubAppPrivateKey, id, fetchImpl)
214
+ const repo = parseRepo(await githubJson(repoApi(fullName), token, fetchImpl), id)
215
+ if (repo == null || repo.id !== repoId || repo.fullName.toLowerCase() !== fullName.toLowerCase()) throw new GithubApiError(409, 'repo-identity-changed')
216
+ return id
217
+ }
218
+
219
+ // The `repositories` array of one /installation/repositories page → ConnectedRepo[],
220
+ // each tagged with the installation id that can read it.
221
+ function repoPage(body: unknown, installationId: number): ConnectedRepo[] {
222
+ const repositories = (body as { repositories?: unknown }).repositories
223
+ return Array.isArray(repositories) ? repositories.flatMap(r => parseRepo(r, installationId) ?? []) : []
224
+ }
225
+
226
+ // Every repository one installation can read, paginated by the page count from
227
+ // `total_count` (avoids Link-header parsing).
228
+ async function listInstallationRepos(token: string, installationId: number, fetchImpl: typeof fetch): Promise<ConnectedRepo[]> {
229
+ const pageUrl = (page: number): string => `${GITHUB_API}/installation/repositories?per_page=${PER_PAGE}&page=${page}`
230
+ const first = await githubJson(pageUrl(1), token, fetchImpl) as { total_count?: unknown }
231
+ const repos = repoPage(first, installationId)
232
+ const total = typeof first.total_count === 'number' ? first.total_count : repos.length
233
+ const pages = Math.ceil(total / PER_PAGE)
234
+ for (let page = 2; page <= pages; page++) {
235
+ repos.push(...repoPage(await githubJson(pageUrl(page), token, fetchImpl), installationId))
236
+ }
237
+ return repos
238
+ }
239
+
240
+ // List every repo the repositories App is installed on, across installations
241
+ // (public + PRIVATE within those installs), deduped + sorted. Empty when the App
242
+ // isn't configured. READ-ONLY.
243
+ export async function listInstalledRepos(config: ManagedConfig, fetchImpl: typeof fetch = globalThis.fetch): Promise<ConnectedRepo[]> {
244
+ const { githubAppId, githubAppPrivateKey } = config
245
+ if (githubAppId == null || githubAppPrivateKey == null) return []
246
+ const jwt = appJwt(githubAppId, githubAppPrivateKey)
247
+ const lists = await eachOf(await listInstallationIds(jwt, fetchImpl), GITHUB_REQUESTS_AT_ONCE, async (id) => {
248
+ const token = await installationAccessToken(githubAppId, githubAppPrivateKey, id, fetchImpl)
249
+ return listInstallationRepos(token, id, fetchImpl)
250
+ })
251
+ return mergeRepos(...lists)
252
+ }
253
+
254
+ // A GitHub account, as GitHub's /user tells it.
255
+ export interface GithubIdentity { id: number; login: string }
256
+
257
+ // The login App and repository App are separate: /user/repos with the login
258
+ // token is not evidence of private-repo access. Ask the repository App for the
259
+ // user's effective GitHub permission (including teams/org/enterprise grants).
260
+ // This endpoint accepts installation tokens with Metadata: read; it does NOT
261
+ // require Administration permission (unlike collaborator mutation endpoints).
262
+ // https://docs.github.com/en/rest/collaborators/collaborators#get-repository-permissions-for-a-user
263
+ // Resolve the current login from /user so renamed handles cannot check someone
264
+ // else's access. All repo paths come from GitHub's installation catalogue.
265
+ export async function githubUserIdentity(userToken: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<GithubIdentity> {
266
+ const identity = await githubJson(`${GITHUB_API}/user`, userToken, fetchImpl) as { id?: unknown; login?: unknown }
267
+ if (typeof identity?.login !== 'string' || !identity.login || !isId(identity.id)) throw new GithubApiError(502, 'github-malformed')
268
+ return { id: identity.id, login: identity.login }
269
+ }
270
+
271
+ // The permission's level (`admin`, `write`, `read`), as GitHub tells it of
272
+ // `identity` alone; `none` where it tells of none, or of another account.
273
+ export async function githubRepoPermission(fullName: string, token: string, identity: GithubIdentity, fetchImpl: typeof fetch = globalThis.fetch): Promise<string> {
274
+ try {
275
+ const body = await githubJson(`${repoApi(fullName)}/collaborators/${encodeURIComponent(identity.login)}/permission`, token, fetchImpl) as { permission?: unknown; user?: { id?: unknown } }
276
+ return body?.user?.id === identity.id && typeof body.permission === 'string' ? body.permission : 'none'
277
+ } catch (err) {
278
+ if (err instanceof GithubApiError && err.status === 404) return 'none'
279
+ throw err // Never broaden access when GitHub cannot verify permission.
280
+ }
281
+ }
282
+
283
+ // The levels that read a repository.
284
+ export const READ_PERMISSIONS: ReadonlySet<string> = new Set(['read', 'write', 'admin'])
285
+
286
+ export async function filterInstalledRepos(config: ManagedConfig, repositories: ConnectedRepo[], userToken: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<ConnectedRepo[]> {
287
+ const identity = await githubUserIdentity(userToken, fetchImpl)
288
+ const tokens = new Map<number, Promise<string | null>>()
289
+ const allowed = await eachOf(repositories, GITHUB_REQUESTS_AT_ONCE, async (repo) => {
290
+ // Internal repos may have private=false; missing visibility is not proof
291
+ // of public access either. Only explicitly public repositories skip checks.
292
+ if (repo.visibility === 'public') return true
293
+ if (repo.installationId == null) return false
294
+ let token = tokens.get(repo.installationId)
295
+ if (!token) {
296
+ token = repoAccessToken(config, repo.installationId, fetchImpl)
297
+ tokens.set(repo.installationId, token)
298
+ }
299
+ const accessToken = await token
300
+ if (!accessToken) return false
301
+ return READ_PERMISSIONS.has(await githubRepoPermission(repo.fullName, accessToken, identity, fetchImpl))
302
+ })
303
+ return repositories.filter((_, index) => allowed[index])
304
+ }
305
+
306
+ // Get a token to READ a selected repo's contents: an installation token (the
307
+ // App's Contents: Read) when the repo was reached through an installation, or
308
+ // null for a public repo readable unauthenticated. This is the whole point of
309
+ // persisting `installationId` — the stored context is enough to read.
310
+ export async function repoAccessToken(config: ManagedConfig, installationId: number | null, fetchImpl: typeof fetch = globalThis.fetch): Promise<string | null> {
311
+ const { githubAppId, githubAppPrivateKey } = config
312
+ if (installationId == null || githubAppId == null || githubAppPrivateKey == null) return null
313
+ return await installationAccessToken(githubAppId, githubAppPrivateKey, installationId, fetchImpl)
314
+ }
315
+
316
+ // ── merged listing ──
317
+
318
+ export interface RepoListing {
319
+ repositories: ConnectedRepo[]
320
+ tokenMissing: boolean
321
+ }
322
+
323
+ // Every repo a user can reach, merged (deduped + sorted): PUBLIC via their login
324
+ // token + PRIVATE via the App's installations. Each source is best-effort so one
325
+ // failing never blanks the other; `tokenMissing` flags a missing/stale user
326
+ // token (→ the page prompts re-login). A repo seen on both sides keeps the
327
+ // installation tag (private listed last → wins the merge).
328
+ export async function collectRepos(config: ManagedConfig, userToken: string | null, fetchImpl: typeof fetch = globalThis.fetch): Promise<RepoListing> {
329
+ let tokenMissing = userToken == null
330
+ const lists: ConnectedRepo[][] = []
331
+ if (userToken != null) {
332
+ try {
333
+ lists.push(await listUserRepos(userToken))
334
+ } catch (err) {
335
+ if (err instanceof GithubApiError && err.status === 401) tokenMissing = true
336
+ else console.warn('managed: public repo list failed:', err)
337
+ }
338
+ }
339
+ if (githubAppConfigured(config)) {
340
+ try {
341
+ lists.push(await listInstalledRepos(config, fetchImpl))
342
+ } catch (err) {
343
+ console.warn('managed: private repo list failed:', err)
344
+ }
345
+ }
346
+ return { repositories: mergeRepos(...lists), tokenMissing }
347
+ }
@@ -0,0 +1,92 @@
1
+ import { HttpError } from '@preventive/upstream/github.js'
2
+
3
+ // A failure carrying the HTTP status the router should surface. 401 passes
4
+ // through so the user-token path can map it to "log in again".
5
+ export class GithubApiError extends Error {
6
+ status: number
7
+ retryAfter: number | null
8
+ // What failed, where GitHub wasn't reached (githubUnreachable).
9
+ detail: string | null
10
+ // The repository GitHub's redirect sends one asked of to, by its id, where
11
+ // it moved (githubMoved).
12
+ movedTo: number | null = null
13
+ constructor(status: number, message: string, retryAfter: number | null = null, detail: string | null = null) {
14
+ super(message)
15
+ this.name = 'GithubApiError'
16
+ this.status = status
17
+ this.retryAfter = retryAfter
18
+ this.detail = detail
19
+ }
20
+ }
21
+
22
+ // GitHub not reached, or its answer not read whole, `started` ms since the
23
+ // epoch: as `github-unreachable`, with what failed as the error and its causes
24
+ // tell it (a timeout, a connection closed, an answer too large) and after how
25
+ // long, for an admin's page to show (repository-risk.ts). Only the errors'
26
+ // names, codes and messages, never GitHub's text nor a request's headers.
27
+ export function githubUnreachable(error: unknown, started: number): GithubApiError {
28
+ const told: string[] = []
29
+ for (let at = error, depth = 0; at instanceof Error && depth < 4; at = at.cause, depth++) {
30
+ const code = 'code' in at && typeof at.code === 'string' && at.code !== at.name ? ` ${at.code}` : ''
31
+ told.push(`${at.name}${code}${at.message ? `: ${at.message.slice(0, 200)}` : ''}`)
32
+ }
33
+ const failed = told.length > 0 ? told.join('; ') : String(error).slice(0, 200)
34
+ return new GithubApiError(502, 'github-unreachable', null, `${failed}, after ${((Date.now() - started) / 1000).toFixed(1)}s`)
35
+ }
36
+
37
+ // The statuses of a redirect, and where GitHub's API sends a repository
38
+ // renamed or transferred: to that repository by its id, then the rest of
39
+ // what was asked of it.
40
+ const REDIRECTS = new Set([301, 302, 303, 307, 308])
41
+ const REPOSITORY_BY_ID = /^https:\/\/api\.github\.com\/repositories\/([1-9]\d{0,14})(?:[/?]|$)/u
42
+
43
+ // A redirect GitHub answered, never followed, as it answers of a repository
44
+ // renamed or transferred since it was named so: `github-moved`, with the id of
45
+ // the repository it sends it to (`movedTo`), null where it names none.
46
+ function githubMoved(location: string | null | undefined): GithubApiError {
47
+ const error = new GithubApiError(502, 'github-moved')
48
+ const id = REPOSITORY_BY_ID.exec(location ?? '')?.[1]
49
+ error.movedTo = id === undefined ? null : Number(id)
50
+ return error
51
+ }
52
+ export const isGithubMoved = (error: unknown): error is GithubApiError => error instanceof GithubApiError && error.message === 'github-moved'
53
+
54
+ export async function throwGithubResponseError(res: Response): Promise<never> {
55
+ if (REDIRECTS.has(res.status)) throw githubMoved(res.headers?.get('location'))
56
+ if (res.status === 403 || res.status === 429) {
57
+ const body = await res.json().catch(() => null) as { message?: unknown } | null
58
+ if (res.status === 429 || res.headers.get('x-ratelimit-remaining') === '0' || res.headers.has('retry-after')
59
+ || (typeof body?.message === 'string' && /rate limit|abuse detection/iu.test(body.message))) {
60
+ const retry = Number(res.headers.get('retry-after'))
61
+ const reset = Number(res.headers.get('x-ratelimit-reset')) * 1000
62
+ const wait = Math.max(Number.isFinite(retry) ? retry : 0, Number.isFinite(reset) ? (reset - Date.now()) / 1000 : 0)
63
+ throw new GithubApiError(429, 'github-rate-limited', Math.max(60, Math.ceil(wait)))
64
+ }
65
+ }
66
+ if (res.status === 401) throw new GithubApiError(401, 'github-unauthorized')
67
+ if (res.status === 404) throw new GithubApiError(404, 'github-not-found')
68
+ throw new GithubApiError(502, `github-status-${res.status}`)
69
+ }
70
+
71
+ export async function upstreamGithub<T>(request: () => Promise<T>): Promise<T> {
72
+ const started = Date.now()
73
+ try { return await request() } catch (error) {
74
+ // Already told as the router surfaces it.
75
+ if (error instanceof GithubApiError) throw error
76
+ if (error instanceof HttpError) {
77
+ // The upstream error includes GitHub's response text. Retain managed
78
+ // status handling, including rate limits, without exposing that text.
79
+ if (error.status === 401) throw new GithubApiError(401, 'github-unauthorized')
80
+ if (error.status === 404) throw new GithubApiError(404, 'github-not-found')
81
+ if (REDIRECTS.has(error.status)) throw githubMoved((error as { headers?: Headers }).headers?.get('location'))
82
+ if (error.status === 429 || (error.status === 403 && /rate limit|abuse detection/iu.test(error.message))) {
83
+ throw new GithubApiError(429, 'github-rate-limited', 60)
84
+ }
85
+ throw new GithubApiError(502, `github-status-${error.status}`)
86
+ }
87
+ if (error instanceof Error && (error.name === 'AssertionError' || error.cause instanceof SyntaxError)) {
88
+ throw new GithubApiError(502, 'github-malformed')
89
+ }
90
+ throw githubUnreachable(error, started)
91
+ }
92
+ }
@@ -0,0 +1,42 @@
1
+ // GitHub's GraphQL API, a query at a time, as the repository readers ask it
2
+ // (repository-history.ts, repository-agents.ts, repository-pulse.ts and the rest).
3
+ import { GithubApiError } from './github-errors.ts'
4
+ import { GITHUB_API, githubJson } from './github-requests.ts'
5
+
6
+ export type GraphqlError = { type?: unknown; path?: unknown; message?: unknown }
7
+ // An error naming what isn't there, for the queries that read past it.
8
+ export const notFound = (error: GraphqlError) => error?.type === 'NOT_FOUND'
9
+
10
+ const NAMED_ERRORS = new Set(['RATE_LIMITED', 'NOT_FOUND', 'FORBIDDEN'])
11
+ // GitHub's own words for a query it stopped past its time (ten seconds):
12
+ // "Something went wrong while executing your query. This may be the result
13
+ // of a timeout, …", with no type.
14
+ const TIMED_OUT = /\btimeout\b/iu
15
+
16
+ // One GraphQL query with `token`, answered with its `data`: one GitHub answers
17
+ // with errors, but for those the caller reads past (`tolerated`, the fields
18
+ // they name then null), is rate limited, names what isn't there, is refused,
19
+ // as one a GitHub App lacks the permission for is, or a token the scope for
20
+ // (`INSUFFICIENT_SCOPES`, a sign-in's having none), took GitHub too long, or
21
+ // else is malformed, as one GitHub rejects unread is (a field or type its API
22
+ // doesn't know). GitHub's words for errors of none of those first three types
23
+ // are logged, those read past too.
24
+ export async function githubGraphql(query: string, variables: Record<string, unknown>, token: string, fetchImpl: typeof fetch,
25
+ tolerated: (error: GraphqlError) => boolean = () => false) {
26
+ const body = await githubJson(`${GITHUB_API}/graphql`, token, fetchImpl, 'POST', { query, variables }, true) as { data?: unknown; errors?: GraphqlError[] } | null
27
+ const all = Array.isArray(body?.errors) ? body.errors : []
28
+ const unnamed = all.filter(error => !NAMED_ERRORS.has(String(error?.type)))
29
+ if (unnamed.length > 0) {
30
+ console.warn('managed: GitHub answered a query with errors:', JSON.stringify(unnamed.slice(0, 3)
31
+ .map(error => ({ type: error?.type, message: String(error?.message).slice(0, 300), path: error?.path }))))
32
+ }
33
+ const errors = all.filter(error => !tolerated(error))
34
+ if (errors.length > 0) {
35
+ if (errors.some(error => error?.type === 'RATE_LIMITED')) throw new GithubApiError(429, 'github-rate-limited', 60)
36
+ if (errors.some(error => error?.type === 'NOT_FOUND')) throw new GithubApiError(404, 'github-not-found')
37
+ if (errors.some(error => error?.type === 'FORBIDDEN' || error?.type === 'INSUFFICIENT_SCOPES')) throw new GithubApiError(502, 'github-status-403')
38
+ if (errors.some(error => typeof error?.message === 'string' && TIMED_OUT.test(error.message))) throw new GithubApiError(502, 'github-timeout')
39
+ throw new GithubApiError(502, 'github-malformed')
40
+ }
41
+ return body?.data
42
+ }