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

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 (409) 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 +36 -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 +43 -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-2XUEZHIP.js +28 -0
  92. package/out/chunk-4EMM6UCD.js +1 -0
  93. package/out/chunk-4ISO5F7Y.js +7 -0
  94. package/out/chunk-4XIH7YTX.js +1 -0
  95. package/out/chunk-6CCSTJWB.js +1 -0
  96. package/out/chunk-74AEKRES.js +10 -0
  97. package/out/chunk-7BKKYVWR.js +7 -0
  98. package/out/chunk-7C7DWL7I.js +1 -0
  99. package/out/chunk-B3FNMHOE.js +1 -0
  100. package/out/chunk-BNH52UHC.js +2 -0
  101. package/out/chunk-BRO77PQY.js +42 -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-G3LY2FV4.js +1 -0
  106. package/out/chunk-GO7FT4OD.js +1 -0
  107. package/out/chunk-GRGIZOTP.js +4 -0
  108. package/out/chunk-HAZKDK4M.js +4 -0
  109. package/out/chunk-HOB3YPS5.js +1 -0
  110. package/out/chunk-IYPY47MC.js +1 -0
  111. package/out/chunk-IZ6MYRYB.js +3 -0
  112. package/out/chunk-J2FWBXFV.js +1 -0
  113. package/out/chunk-JCIIBLKR.js +1 -0
  114. package/out/chunk-JFL7WLRV.js +1 -0
  115. package/out/chunk-JJK5OZG2.js +15 -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-OFZYEWBH.js +244 -0
  123. package/out/chunk-OIERSXON.js +1 -0
  124. package/out/chunk-OOJM4CTU.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-QCOGVL37.js +52 -0
  131. package/out/chunk-QMVOEBWC.js +13 -0
  132. package/out/chunk-QRKFPLA4.js +80 -0
  133. package/out/chunk-R3NZFXVR.js +1 -0
  134. package/out/chunk-R5O6FAW4.js +2 -0
  135. package/out/chunk-RRBIJL2B.js +1 -0
  136. package/out/chunk-SYXT3SFP.js +2 -0
  137. package/out/chunk-TOXMUOIW.js +5 -0
  138. package/out/chunk-TUII34K2.js +1 -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-W3QFV4SP.js +3 -0
  143. package/out/chunk-W6VOKW2N.js +12 -0
  144. package/out/chunk-WCPJDAYA.js +10 -0
  145. package/out/chunk-WMFDQS2L.js +11 -0
  146. package/out/chunk-WREU7JAG.js +1 -0
  147. package/out/chunk-Y5ZHFNBD.js +2 -0
  148. package/out/chunk-YF4M5OCI.js +1 -0
  149. package/out/chunk-Z667U2UJ.js +1 -0
  150. package/out/chunk-ZQHLECTI.js +1 -0
  151. package/out/chunk-ZQNEWVGG.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 +40 -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 +383 -63
  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 +238 -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 +26 -0
  249. package/server-managed/brotli.ts +10 -0
  250. package/server-managed/bundle-advisories.ts +103 -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 +238 -0
  256. package/server-managed/bundle-build.ts +240 -0
  257. package/server-managed/bundle-cache.ts +199 -0
  258. package/server-managed/bundle-catalog.ts +29 -0
  259. package/server-managed/bundle-commits.ts +133 -0
  260. package/server-managed/bundle-dependency-reviews.ts +68 -0
  261. package/server-managed/bundle-store.ts +24 -0
  262. package/server-managed/bundle-summary-cache.ts +139 -0
  263. package/server-managed/bundle-validation.ts +33 -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 +43 -0
  268. package/server-managed/comments.ts +138 -0
  269. package/server-managed/commit-coauthors.ts +105 -0
  270. package/server-managed/commit-lockfiles.ts +77 -0
  271. package/server-managed/comparison.ts +50 -0
  272. package/server-managed/config.ts +163 -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 +1877 -0
  276. package/server-managed/db-neon.ts +388 -0
  277. package/server-managed/db-schema.ts +253 -0
  278. package/server-managed/db-table-names.ts +22 -0
  279. package/server-managed/db.ts +146 -0
  280. package/server-managed/dependabot-access.ts +61 -0
  281. package/server-managed/dependabot-alerts.ts +180 -0
  282. package/server-managed/dependency-review-comments.ts +92 -0
  283. package/server-managed/dependency-reviews.ts +363 -0
  284. package/server-managed/github-accounts.ts +59 -0
  285. package/server-managed/github-actions.ts +71 -0
  286. package/server-managed/github-app.ts +347 -0
  287. package/server-managed/github-errors.ts +70 -0
  288. package/server-managed/github-graphql.ts +42 -0
  289. package/server-managed/github-issue-links.ts +264 -0
  290. package/server-managed/github-issue-oauth.ts +30 -0
  291. package/server-managed/github-issues.ts +157 -0
  292. package/server-managed/github-link-oauth.ts +56 -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 +264 -0
  296. package/server-managed/github-pulls.ts +257 -0
  297. package/server-managed/github-requests.ts +179 -0
  298. package/server-managed/github-users.ts +30 -0
  299. package/server-managed/github-values.ts +26 -0
  300. package/server-managed/history-windows.ts +172 -0
  301. package/server-managed/http-response.ts +76 -0
  302. package/server-managed/http.ts +5796 -0
  303. package/server-managed/import-triage.ts +51 -0
  304. package/server-managed/index.ts +204 -0
  305. package/server-managed/kept-briefly.ts +37 -0
  306. package/server-managed/kept.ts +28 -0
  307. package/server-managed/link-reports.ts +149 -0
  308. package/server-managed/listed-activity.ts +39 -0
  309. package/server-managed/locked-packages.ts +152 -0
  310. package/server-managed/lockfile-scope.ts +49 -0
  311. package/server-managed/lru.ts +30 -0
  312. package/server-managed/managed-issues.ts +92 -0
  313. package/server-managed/management-catalog.ts +45 -0
  314. package/server-managed/management.ts +110 -0
  315. package/server-managed/npm-delta-worker.js +23 -0
  316. package/server-managed/npm-delta.ts +159 -0
  317. package/server-managed/npm-insights.ts +455 -0
  318. package/server-managed/npm-kept.ts +234 -0
  319. package/server-managed/npm-loads.ts +259 -0
  320. package/server-managed/npm-manifest.ts +117 -0
  321. package/server-managed/npm-packages.ts +462 -0
  322. package/server-managed/npm-patch.ts +317 -0
  323. package/server-managed/npm-provenance.ts +127 -0
  324. package/server-managed/npm-risk.ts +287 -0
  325. package/server-managed/object-storage-disk.ts +147 -0
  326. package/server-managed/object-storage-vercel.ts +71 -0
  327. package/server-managed/object-storage.ts +82 -0
  328. package/server-managed/package-entry-points.ts +79 -0
  329. package/server-managed/pretty-print.ts +425 -0
  330. package/server-managed/public-workspace.ts +242 -0
  331. package/server-managed/pull-comment-reviews.ts +161 -0
  332. package/server-managed/pull-dependencies.ts +340 -0
  333. package/server-managed/pull-dependency-reviews.ts +327 -0
  334. package/server-managed/pull-reviews.ts +202 -0
  335. package/server-managed/queue.ts +53 -0
  336. package/server-managed/release-commits.ts +85 -0
  337. package/server-managed/rename-diff-worker.js +26 -0
  338. package/server-managed/rename-diff.ts +236 -0
  339. package/server-managed/repo-path.ts +21 -0
  340. package/server-managed/report-migration.ts +32 -0
  341. package/server-managed/report-query.ts +10 -0
  342. package/server-managed/report-response.ts +16 -0
  343. package/server-managed/report-sources.ts +181 -0
  344. package/server-managed/report-store.ts +77 -0
  345. package/server-managed/repository-actions.ts +220 -0
  346. package/server-managed/repository-agents.ts +422 -0
  347. package/server-managed/repository-aliases.ts +85 -0
  348. package/server-managed/repository-browser.ts +303 -0
  349. package/server-managed/repository-changes.ts +280 -0
  350. package/server-managed/repository-code.ts +215 -0
  351. package/server-managed/repository-dependency-reviews.ts +159 -0
  352. package/server-managed/repository-discovery.ts +83 -0
  353. package/server-managed/repository-history.ts +428 -0
  354. package/server-managed/repository-issues.ts +224 -0
  355. package/server-managed/repository-policy.ts +27 -0
  356. package/server-managed/repository-pulls.ts +207 -0
  357. package/server-managed/repository-pulse.ts +477 -0
  358. package/server-managed/repository-risk-assess.ts +108 -0
  359. package/server-managed/repository-risk-audit.ts +78 -0
  360. package/server-managed/repository-risk-read.ts +170 -0
  361. package/server-managed/repository-risk.ts +483 -0
  362. package/server-managed/repository-squashes.ts +160 -0
  363. package/server-managed/repository-stamp.ts +41 -0
  364. package/server-managed/request-timing.ts +63 -0
  365. package/server-managed/reviewed-dependencies.ts +149 -0
  366. package/server-managed/revisions.ts +35 -0
  367. package/server-managed/scan-downloads.ts +87 -0
  368. package/server-managed/session.ts +132 -0
  369. package/server-managed/slugs.ts +38 -0
  370. package/server-managed/solidity-entry-points.ts +71 -0
  371. package/server-managed/sql-postgres.ts +34 -0
  372. package/server-managed/sql.ts +107 -0
  373. package/server-managed/stasis-config.ts +55 -0
  374. package/server-managed/static.ts +28 -0
  375. package/server-managed/storage-command.ts +16 -0
  376. package/server-managed/storage-db.ts +183 -0
  377. package/server-managed/storage-encryption.ts +288 -0
  378. package/server-managed/storage-maintenance.ts +259 -0
  379. package/server-managed/storage-payload.ts +121 -0
  380. package/server-managed/storage-stores.ts +91 -0
  381. package/server-managed/storage.ts +82 -0
  382. package/server-managed/team-app-summaries.ts +54 -0
  383. package/server-managed/team-app.ts +154 -0
  384. package/server-managed/team-catalog.ts +7 -0
  385. package/server-managed/team-feed.ts +180 -0
  386. package/server-managed/team-npm-scopes.ts +103 -0
  387. package/server-managed/team-reports.ts +351 -0
  388. package/server-managed/triage-response.ts +16 -0
  389. package/server-managed/type-only-proof.js +108 -0
  390. package/server-managed/type-only-worker.js +31 -0
  391. package/server-managed/type-only.ts +115 -0
  392. package/server-managed/uploads.ts +106 -0
  393. package/server-managed/upstream-cache.ts +250 -0
  394. package/server-managed/view-as.ts +58 -0
  395. package/server-managed/worker-turns.ts +76 -0
  396. package/server-managed/workspace-shares.ts +170 -0
  397. package/server.ts +70 -0
  398. package/server/index.ts +0 -480
  399. package/server/lifecycle.ts +0 -208
  400. /package/{LICENSE → LICENSE-MIT} +0 -0
  401. /package/{server → server-e2e}/auth.ts +0 -0
  402. /package/{server → server-e2e}/config.example.json +0 -0
  403. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  404. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  405. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  406. /package/{server → server-e2e}/peer.ts +0 -0
  407. /package/{server → server-e2e}/sse-session.ts +0 -0
  408. /package/{server → server-e2e}/util.ts +0 -0
  409. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,85 @@
1
+ // The commits that release a repository, for its Pulse (repository-pulse.ts
2
+ // commitStats): one a tag names that changes no code, only package.json
3
+ // files (at least one, in any directory), the lockfiles beside them
4
+ // (RELEASE_LOCKFILES) and changelogs written in Markdown (RELEASE_CHANGELOG,
5
+ // a changeset's file among them), as `npm version` and a release's tooling
6
+ // leave one. What each commit changes is read as Replay reads it, kept by
7
+ // the commit (repository-changes.ts repositoryChanges).
8
+ import { type ChangesStore, type CommitChanges, repositoryChanges } from './repository-changes.ts'
9
+ import { githubGraphql } from './github-graphql.ts'
10
+ import { SHA, timeOf } from './github-values.ts'
11
+ import { type Connection, nextCursor } from './repository-history.ts'
12
+
13
+ // The tags read, a page a query, the latest commits' first, as many pages as
14
+ // TAG_PAGES; of the commits they name, as many as RELEASES_READ have their
15
+ // files read.
16
+ const TAG_PAGE = 100
17
+ const TAG_PAGES = 5
18
+ const RELEASES_READ = 200
19
+ // An annotated tag's target, its own target in turn, through as many as
20
+ // TAG_DEPTH annotated tags.
21
+ const TAG_DEPTH = 3
22
+ const RELEASE_LOCKFILES = new Set(['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock', 'bun.lockb'])
23
+ const RELEASE_CHANGELOG = /^(?:changelog|changes|history|news|releases?)(?:[._-][^/]*)?\.(?:md|markdown)$/iu
24
+ const CHANGESET = /(?:^|\/)\.changeset\/[^/]+\.md$/iu
25
+
26
+ const tagTarget = (depth: number): string => `target { __typename oid ... on Commit { committedDate }${depth > 0 ? ` ... on Tag { ${tagTarget(depth - 1)} }` : ''} }`
27
+ const TAGS_QUERY = `query($owner: String!, $name: String!, $after: String) {
28
+ repository(owner: $owner, name: $name) {
29
+ refs(refPrefix: "refs/tags/", first: ${TAG_PAGE}, after: $after, orderBy: { field: TAG_COMMIT_DATE, direction: DESC }) {
30
+ pageInfo { hasNextPage endCursor }
31
+ nodes { ${tagTarget(TAG_DEPTH)} }
32
+ }
33
+ }
34
+ }`
35
+ type TagTarget = { __typename?: unknown; oid?: unknown; committedDate?: unknown; target?: TagTarget | null } | null | undefined
36
+ type TagsPage = { repository?: { refs?: Connection<{ target?: TagTarget }> | null } | null }
37
+
38
+ // The commit a tag names, through its annotated tags, and when it was
39
+ // committed; null for one naming no commit (a tree, a blob).
40
+ function taggedCommit(target: TagTarget, depth = TAG_DEPTH): { oid: string; at: number } | null {
41
+ if (target?.__typename === 'Tag' && depth > 0) return taggedCommit(target.target, depth - 1)
42
+ const at = timeOf(target?.committedDate)
43
+ return target?.__typename === 'Commit' && typeof target.oid === 'string' && SHA.test(target.oid) && at !== null ? { oid: target.oid, at } : null
44
+ }
45
+
46
+ // The commits the repository's tags name committed since `since`, the
47
+ // latest first, as many pages of them as TAG_PAGES.
48
+ async function taggedCommits(fullName: string, token: string, since: number, fetchImpl: typeof fetch = globalThis.fetch): Promise<Set<string>> {
49
+ const [owner, name] = fullName.split('/') as [string, string]
50
+ const tagged = new Set<string>()
51
+ let after: string | null = null
52
+ for (let pages = 0; pages < TAG_PAGES; pages++) {
53
+ const page = await githubGraphql(TAGS_QUERY, { owner, name, after }, token, fetchImpl) as TagsPage | null
54
+ const refs = page?.repository?.refs
55
+ const commits = (refs?.nodes ?? []).flatMap(node => taggedCommit(node?.target) ?? [])
56
+ for (const commit of commits) if (commit.at >= since) tagged.add(commit.oid)
57
+ after = nextCursor(refs?.pageInfo)
58
+ if (after === null || commits.some(commit => commit.at < since)) break
59
+ }
60
+ return tagged
61
+ }
62
+
63
+ // Whether a path is one a release changes: a package.json, a lockfile beside
64
+ // one, or a changelog in Markdown.
65
+ const releaseFile = (path: string) => {
66
+ const base = path.slice(path.lastIndexOf('/') + 1)
67
+ return base === 'package.json' || RELEASE_LOCKFILES.has(base) || RELEASE_CHANGELOG.test(base) || CHANGESET.test(path)
68
+ }
69
+
70
+ // Whether what a commit changes is a release's: a package.json at least, and
71
+ // nothing a release changes none of, a rename's both paths alike; one
72
+ // GitHub listed only some files of, not.
73
+ export function releaseChanges({ files, more }: CommitChanges): boolean {
74
+ const paths = files.flatMap(([path, status, from]) => status === 'R' ? [path, from] : [path])
75
+ return !more && paths.some(path => path.slice(path.lastIndexOf('/') + 1) === 'package.json') && paths.every(releaseFile)
76
+ }
77
+
78
+ // The commits since `since` that release the repository: those its tags
79
+ // name whose changes are a release's, each read as Replay reads it (`kept`),
80
+ // as many as RELEASES_READ, sorted.
81
+ export async function releaseCommits(fullName: string, token: string, since: number, kept: ChangesStore, fetchImpl: typeof fetch = globalThis.fetch): Promise<string[]> {
82
+ const tagged = [...await taggedCommits(fullName, token, since, fetchImpl)].slice(0, RELEASES_READ)
83
+ const changes = await repositoryChanges(fullName, token, tagged, kept, fetchImpl)
84
+ return tagged.filter(sha => { const read = changes.get(sha); return read ? releaseChanges(read) : false }).toSorted()
85
+ }
@@ -0,0 +1,26 @@
1
+ // Compare's diff with renamed names hidden (rename-diff.ts), worked out off the
2
+ // server's event loop by @preventive/compare's renamedDiffs: the old side given
3
+ // the new side's names, not formatted again (each line where the old side's was),
4
+ // diffed with whitespace changes shown and hidden, and the blocks checked to
5
+ // take it to the new side. `{ before, blocks, reason, reads, marks,
6
+ // ignoringWhitespace }`: the old side as diffed, the change blocks, why the
7
+ // old side is as it was where its names could not be given safely, the
8
+ // properties through which either side reads names (a view marks renamed
9
+ // lines rather than hiding them where any are read, as a rename may then
10
+ // change what the code does), and the blocks of the diff of the files as they
11
+ // are that differ in renamed names alone; `ignoringWhitespace` the blocks and
12
+ // those marked with whitespace changes hidden, as diff -b hides them. Blocks
13
+ // that would not take the old side to the new are thrown, and so answer
14
+ // nothing.
15
+ import { parentPort, workerData } from 'node:worker_threads'
16
+ import { renamedDiffs } from '@preventive/compare/names.js'
17
+
18
+ const { before, after, extension, otherExtension } = workerData
19
+ const diff = await renamedDiffs(before, after, { extension, otherExtension, whitespace: ['none', 'change'] })
20
+ // A check that should never fail did, or a step gave way: told, the file shown with its names.
21
+ for (const warning of diff.warnings) console.warn(`managed: rename diff: ${warning}`)
22
+ const [shown, hidden] = diff.diffs
23
+ const answer = { before: diff.before, blocks: shown.blocks, reason: diff.reason, reads: diff.reads, marks: shown.marks, ignoringWhitespace: { blocks: hidden.blocks, marks: hidden.marks } }
24
+ // Node worker messages have no browser target origin.
25
+ // oxlint-disable-next-line unicorn/require-post-message-target-origin
26
+ parentPort.postMessage(answer)
@@ -0,0 +1,236 @@
1
+ // Compare's diff of a JavaScript file minified on both sides with the names a
2
+ // minifier renamed alike hidden (GET /api/bundles/:id/rename-diff, GET
3
+ // /api/npm/rename-diff): both sides pretty-printed, as the pretty-print toggle
4
+ // has them (pretty-print.ts), then diffed by @preventive/compare's
5
+ // renamedDiffs in a worker, off the event loop and two at a time per process,
6
+ // with whitespace changes shown and hidden both. Answered as Brotli-encoded
7
+ // JSON, `{ before, blocks, reason, reads, marks, ignoringWhitespace }`
8
+ // (rename-diff-worker.js), the two files' hashes, `hash` and `otherHash`, and
9
+ // those of the two copies diffed, `prettyHash` and `otherPrettyHash`, which
10
+ // the viewer checks are those it asked about and draws: one file's asked for
11
+ // by both its sides' paths and hashes, or every pair a comparison's viewer
12
+ // diffs so, a line each (renamedPairs). The last few answers are kept in
13
+ // memory by both files' hashes, a private npm version's never, each side read
14
+ // again through the pretty-print cache first, which checks that its source
15
+ // holds a file of that hash. Access is the caller's to check.
16
+ import { Buffer } from 'node:buffer'
17
+ import { promisify } from 'node:util'
18
+ import { brotliDecompress } from 'node:zlib'
19
+ import { layoutPackageDirs, treeLayout } from '@preventive/compare'
20
+ import { computeFileHash } from '@preventive/report'
21
+ import { FILE_HASH } from '../common/bundle-metadata.js'
22
+ import { computeBundleDiff } from '../common/bundle-compare-diff.js'
23
+ import { bundlePkgOf } from '../common/bundle-pkg-of.js'
24
+ import { needsPrettyPrint, prettyExtension } from '../common/pretty-print.js'
25
+ import { type ChangeBlock, blocksHold, textLines } from '../common/line-diff.js'
26
+ import type { OpenedBlob } from './blob-store.ts'
27
+ import { encodeBrotli } from './brotli.ts'
28
+ import { pathOrder } from './npm-packages.ts'
29
+ import { type ComparedSide, PrettyError, type PrettyRequest, opened, prettyText } from './pretty-print.ts'
30
+ import { workerTurns } from './worker-turns.ts'
31
+
32
+ // What a minifier renames: JavaScript, as the viewer offers it for.
33
+ const RENAMABLE = new Set(['js', 'mjs', 'cjs'])
34
+ // Diffs worked out at once per process, each in a worker of its own, and
35
+ // those waiting their turn past them (a Diff view asks for all it shows at
36
+ // once), any more refused.
37
+ const MAX_ACTIVE_DIFFS = 2
38
+ const MAX_WAITING_DIFFS = 16
39
+ // The longest a diff may take, its wait for a worker included, and the most
40
+ // text it is asked of: both sides pretty-printed, which the largest files
41
+ // formatted (MAX_PRETTY_BYTES) stay under.
42
+ const DIFF_TIMEOUT_MS = 60_000
43
+ const MAX_DIFF_CHARS = 64 * 1024 * 1024
44
+ // Answers kept, the one read last last: each holds the old side as diffed.
45
+ // As many as a comparison's viewer may ask for beside the pairs it has come
46
+ // (renamedPairs), so that neither is worked out twice.
47
+ const KEPT_DIFFS = 32
48
+
49
+ // `blocks` and `marks` with whitespace changes shown, `ignoringWhitespace`'s
50
+ // hidden as diff -b hides them.
51
+ export interface RenameDiff {
52
+ before: string; blocks: ChangeBlock[]; reason: string | null; reads: string[]; marks: ChangeBlock[]
53
+ ignoringWhitespace: { blocks: ChangeBlock[]; marks: ChangeBlock[] }
54
+ }
55
+
56
+ export interface RenameDiffRequest { base: PrettyRequest; other: PrettyRequest }
57
+
58
+ // The two files a request names, a base's `path` and `hash` and the other
59
+ // side's `otherPath` and `otherHash`, or null where either is no JavaScript
60
+ // file named by its hash.
61
+ export function renameDiffRequest(params: URLSearchParams): RenameDiffRequest | null {
62
+ const side = (path: string, hash: string): PrettyRequest | null => {
63
+ const extension = prettyExtension(path)
64
+ return extension !== null && RENAMABLE.has(extension) && FILE_HASH.test(hash) ? { path, hash, extension } : null
65
+ }
66
+ const base = side(params.get('path') ?? '', params.get('hash') ?? ''), other = side(params.get('otherPath') ?? '', params.get('otherHash') ?? '')
67
+ return base && other ? { base, other } : null
68
+ }
69
+
70
+ const workers = workerTurns({ what: 'rename diff', active: MAX_ACTIVE_DIFFS, waiting: MAX_WAITING_DIFFS, error: PrettyError,
71
+ busy: 'diff-busy', timeout: 'diff-timeout', failed: 'undiffable' })
72
+ const kept = new Map<string, Buffer>()
73
+ const pending = new Map<string, Promise<Buffer>>()
74
+
75
+ // Whether a worker's answer is one as rename-diff-worker.js gives it, its
76
+ // blocks taking the old side it answered to the new one asked of, whitespace
77
+ // changes shown and hidden: checked again here, apart from the worker, as an
78
+ // answer that is not would hide a change.
79
+ function answers(diff: unknown, original: string, after: string): diff is RenameDiff {
80
+ const { before, blocks, reason, reads, marks, ignoringWhitespace } = (diff ?? {}) as Partial<RenameDiff>
81
+ return typeof before === 'string' && (reason === null || typeof reason === 'string') && Array.isArray(reads) && reads.every(read => typeof read === 'string')
82
+ && blocksHold(before, after, blocks, false) && marksFit(original, after, marks)
83
+ && blocksHold(before, after, ignoringWhitespace?.blocks, true) && marksFit(original, after, ignoringWhitespace?.marks)
84
+ }
85
+
86
+ // Whether marked blocks (rename-diff-worker.js) are blocks of the diff of the
87
+ // two files as they are: in order, apart, within both, each as many lines on
88
+ // either side.
89
+ function marksFit(before: string, after: string, marks: unknown): boolean {
90
+ if (!Array.isArray(marks)) return false
91
+ const [olds, news] = [textLines(before).length, textLines(after).length]
92
+ let i = 0, j = 0
93
+ for (const mark of marks as Partial<ChangeBlock>[]) {
94
+ const { a0, a1, b0, b1 } = mark ?? {}
95
+ if (![a0, a1, b0, b1].every(Number.isInteger)) return false
96
+ const [x0, x1, y0, y1] = [a0, a1, b0, b1] as [number, number, number, number]
97
+ if (x0 < i || y0 < j || x1 <= x0 || x1 - x0 !== y1 - y0 || x1 > olds || y1 > news) return false
98
+ i = x1
99
+ j = y1
100
+ }
101
+ return true
102
+ }
103
+
104
+ // The two sides diffed in a worker, its answer checked (answers).
105
+ function inWorker(before: string, after: string, { base, other }: RenameDiffRequest, deadline: number): Promise<RenameDiff> {
106
+ if (before.length + after.length > MAX_DIFF_CHARS) throw new PrettyError(413, 'diff-too-large')
107
+ return workers.run(new URL('./rename-diff-worker.js', import.meta.url), {
108
+ workerData: { before, after, extension: base.extension, otherExtension: other.extension }, execArgv: [],
109
+ resourceLimits: { maxOldGenerationSizeMb: 1024 },
110
+ }, answer => {
111
+ if (answers(answer, before, after)) return answer
112
+ console.warn('managed: a rename diff answered what does not take its old side to the new')
113
+ return null
114
+ }, deadline)
115
+ }
116
+
117
+ // `work` given until `deadline`: past it, answered 504 and left to finish on its own.
118
+ function byDeadline<T>(work: Promise<T>, deadline: number): Promise<T> {
119
+ let timer: ReturnType<typeof setTimeout> | undefined
120
+ const late = new Promise<never>((_, reject) => { timer = setTimeout(() => { reject(new PrettyError(504, 'diff-timeout')) }, deadline - Date.now()) })
121
+ return Promise.race([work, late]).finally(() => { clearTimeout(timer) })
122
+ }
123
+
124
+ // An answer as sent, naming the files asked about and the pretty-printed
125
+ // copies of them it was worked out from.
126
+ async function encoded(diff: RenameDiff, { base, other }: RenameDiffRequest, [before, after]: [string, string]): Promise<Buffer> {
127
+ const [prettyHash, otherPrettyHash] = await Promise.all([computeFileHash(before), computeFileHash(after)])
128
+ return encodeBrotli(Buffer.from(JSON.stringify({ ...diff, hash: base.hash, otherHash: other.hash, prettyHash, otherPrettyHash })))
129
+ }
130
+
131
+ // The answer for the two files a request names, Brotli-encoded, `texts`
132
+ // reading both sides pretty-printed (and so checking each is its source's):
133
+ // kept by their hashes where `keep`, readers asking for one meanwhile sharing
134
+ // it. A minute for it, its wait for a worker included.
135
+ export async function renameDiffOf(request: RenameDiffRequest, texts: () => Promise<[string, string]>, keep = true): Promise<OpenedBlob> {
136
+ return opened(await answerOf(request, texts, keep))
137
+ }
138
+
139
+ // Sides `verified` to be the files the request names (renamedPairs) are read
140
+ // only where no answer is kept or on its way; others are read first, as
141
+ // reading them checks they are.
142
+ async function answerOf(request: RenameDiffRequest, texts: () => Promise<[string, string]>, keep: boolean, verified = false): Promise<Buffer> {
143
+ // Sides not kept are formatted again for each diff (pretty-print.ts), so
144
+ // they are read in its turn: the files a Diff view asks for at once wait
145
+ // here rather than being refused by the formats running. Within its minute
146
+ // too, its turn not held past it by a version's files still downloading.
147
+ if (!keep) {
148
+ const deadline = Date.now() + DIFF_TIMEOUT_MS
149
+ let sides: [string, string] = ['', '']
150
+ const diff = await workers.inTurn(deadline, async () => {
151
+ sides = await byDeadline(texts(), deadline)
152
+ return inWorker(sides[0], sides[1], request, deadline)
153
+ })
154
+ return encoded(diff, request, sides)
155
+ }
156
+ // A file's type is part of how it is read: the same text as a script and as a module differ.
157
+ const key = `${request.base.hash}\0${request.base.extension}\0${request.other.hash}\0${request.other.extension}`
158
+ const held = () => {
159
+ const found = kept.get(key)
160
+ if (found) {
161
+ kept.delete(key)
162
+ kept.set(key, found)
163
+ }
164
+ return found ?? pending.get(key)
165
+ }
166
+ let answer = verified ? held() : undefined
167
+ if (!answer) {
168
+ const [before, after] = await texts()
169
+ answer = held()
170
+ if (!answer) {
171
+ const deadline = Date.now() + DIFF_TIMEOUT_MS
172
+ const job = workers.inTurn(deadline, () => inWorker(before, after, request, deadline)).then(diff => encoded(diff, request, [before, after])).finally(() => pending.delete(key))
173
+ pending.set(key, answer = job)
174
+ }
175
+ }
176
+ const body = await answer
177
+ kept.set(key, body)
178
+ if (kept.size > KEPT_DIFFS) kept.delete(kept.keys().next().value!)
179
+ return body
180
+ }
181
+
182
+ const decompress = promisify(brotliDecompress)
183
+
184
+ // What a minifier renames, by its path's extension.
185
+ const renamable = ({ extension }: PrettyRequest) => RENAMABLE.has(extension)
186
+
187
+ // One of a comparison's pairs of files (renamedPairs), its sides named as a
188
+ // request names them, with its answer as renameDiffOf sends it, or why it has
189
+ // none, as a PrettyError tells it.
190
+ export type RenamedLine = { path: string; hash: string; otherPath: string; otherHash: string } & (Partial<RenameDiff> | { error: string; status: number })
191
+
192
+ // The files that changed between a comparison's two sides, as its viewer
193
+ // pairs them (ui/view/bundle-comparison.js prepareComparison): at one path as
194
+ // the other side lays them out, or renamed within a package, as the bundles
195
+ // record their packages; every file there, those that can be formatted by
196
+ // their texts and the rest by their hashes. A file the viewer pairs otherwise
197
+ // (its files are its resources too) it asks about alone.
198
+ export function comparedFiles(sides: readonly [ComparedSide, ComparedSide]) {
199
+ const [olds, news] = sides.map(({ files, hashes }) => {
200
+ const texts = new Map(files.map(file => [file.path, file.text]))
201
+ return new Map<string, unknown>([...hashes].map(([path, hash]) => [path, texts.get(path) ?? { format: 'digest', digest: hash }]))
202
+ }) as [Map<string, unknown>, Map<string, unknown>]
203
+ const layout = treeLayout(olds.keys(), news.keys())
204
+ const packageDirs = layoutPackageDirs(sides[0].packageDirs, sides[1].packageDirs, layout)
205
+ return computeBundleDiff(olds, news, path => bundlePkgOf(path, { packageDir: packageDirs?.get(path) }), layout).files
206
+ }
207
+
208
+ // The pairs of JavaScript files minified on both sides that changed between a
209
+ // comparison's two sides, paired as its viewer pairs them (comparedFiles),
210
+ // each diffed as renameDiffOf diffs it, from both sides' copies, kept or
211
+ // made, as they are iterated: in path order, one after another, leaving a
212
+ // worker to the files a viewer asks for alone (a pair it reads otherwise, one
213
+ // it shows first).
214
+ export function renamedPairs([base, other]: readonly [ComparedSide, ComparedSide], keep = true): AsyncGenerator<RenamedLine> {
215
+ const formattable = ({ files }: ComparedSide) => new Map(files.map(file => [file.path, file]))
216
+ const [olds, news] = [formattable(base), formattable(other)]
217
+ const pairs = comparedFiles([base, other]).changed.flatMap(({ path, basePath = path }) => {
218
+ const [from, to] = [olds.get(basePath), news.get(path)]
219
+ return from && to && from.hash !== to.hash && [from, to].every(file => renamable(file) && needsPrettyPrint(file.path, file.text)) ? [[from, to] as const] : []
220
+ }).toSorted(([, a], [, b]) => pathOrder(a.path, b.path))
221
+ return (async function* () {
222
+ for (const [from, to] of pairs) {
223
+ const request = { base: { path: from.path, hash: from.hash, extension: from.extension }, other: { path: to.path, hash: to.hash, extension: to.extension } }
224
+ const named = { path: from.path, hash: from.hash, otherPath: to.path, otherHash: to.hash }
225
+ const copy = async (side: ComparedSide, { text, ...file }: typeof from) => prettyText(await side.kept(file) ?? await side.made(file, text))
226
+ let body
227
+ try { body = await answerOf(request, async () => [await copy(base, from), await copy(other, to)], keep, true) }
228
+ catch (err) {
229
+ if (!(err instanceof PrettyError)) throw err
230
+ yield { ...named, error: err.message, status: err.status }
231
+ continue
232
+ }
233
+ yield { ...JSON.parse((await decompress(body)).toString('utf8')) as Partial<RenameDiff>, ...named }
234
+ }
235
+ })()
236
+ }
@@ -0,0 +1,21 @@
1
+ const MAX_TEAM_PATH = 500
2
+
3
+ // Canonicalize only equivalent Git paths: '/' separates components and empty
4
+ // or '.' components do not change the directory. Reject ambiguous input rather
5
+ // than deleting characters from directory names used for authorization.
6
+ // `{ ok:false }` makes the handler 400; `{ path:null }` means the whole repo.
7
+ export function normalizeTeamPath(raw: unknown): { ok: true; path: string | null } | { ok: false } {
8
+ if (typeof raw !== 'string') return { ok: true, path: null }
9
+ // Spaces and backslashes can be literal parts of Git directory names.
10
+ // Neither trimming nor treating '\\' as a separator preserves that identity.
11
+ if (/\p{Cc}/u.test(raw) || raw.includes('\\') || raw !== raw.trim()) return { ok: false }
12
+ const segments: string[] = []
13
+ for (const seg of raw.split('/')) {
14
+ if (seg === '' || seg === '.') continue
15
+ if (seg === '..' || seg !== seg.trim()) return { ok: false }
16
+ segments.push(seg)
17
+ }
18
+ const path = segments.join('/')
19
+ if (path.length > MAX_TEAM_PATH) return { ok: false }
20
+ return { ok: true, path: path === '' ? null : path }
21
+ }
@@ -0,0 +1,32 @@
1
+ // SQLite deployments store report blobs beside the database. Recover location
2
+ // metadata before introducing directory-based team access. Schema and data move
3
+ // together so a missing/corrupt blob leaves the migration retryable after repair.
4
+ import { readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import type { DatabaseSync } from 'node:sqlite'
7
+ import { reportRepoGithub } from '@preventive/report'
8
+ import { readManagedReport } from '../common/managed/report-content.ts'
9
+ import { normalizeTeamPath } from './repo-path.ts'
10
+ import { isBlobId } from './object-storage.ts'
11
+ import { sqliteTransaction } from './sql.ts'
12
+
13
+ export function migrateReportLocations(db: DatabaseSync, reportDir: string): void {
14
+ const columns = db.prepare('PRAGMA table_info(managed_report)').all() as { name: string }[]
15
+ if (columns.some((column) => column.name === 'repo_directory')) return
16
+ sqliteTransaction(db, 'BEGIN IMMEDIATE', () => {
17
+ db.exec("ALTER TABLE managed_report ADD COLUMN repo_directory TEXT NOT NULL DEFAULT ''")
18
+ const update = db.prepare('UPDATE managed_report SET repo_directory = ?, repo_embedded = ? WHERE id = ?')
19
+ const reports = db.prepare('SELECT id, filename FROM managed_report').all() as { id: string, filename: string }[]
20
+ for (const { id, filename } of reports) {
21
+ // Same opaque UUID boundary as the blob store; never splice arbitrary
22
+ // database text into a filesystem path during an upgrade.
23
+ if (!isBlobId(id)) throw new Error(`Invalid legacy report id: ${id}`)
24
+ const { data } = readManagedReport(readFileSync(join(reportDir, id), 'utf8'), filename)
25
+ if (data == null) throw new Error(`Cannot migrate location of unreadable report ${id}`)
26
+ const embedded = reportRepoGithub(data) != null
27
+ const directory = normalizeTeamPath(data.repo?.directory)
28
+ if (!directory.ok) throw new Error(`Cannot migrate invalid directory of report ${id}`)
29
+ update.run(directory.path ?? '', embedded ? 1 : 0, id)
30
+ }
31
+ })
32
+ }
@@ -0,0 +1,10 @@
1
+ // Large workspaces remain a single request. Bound both the stored input and
2
+ // the encoded response, independently of the per-upload size limit.
3
+ export const MAX_REPORT_QUERY_COUNT = 4096
4
+ export const MAX_REPORT_QUERY_BYTES = 1024 * 1024 * 1024
5
+
6
+ // The import catalog scans a bounded page, not the whole installation. A
7
+ // report larger than the byte target occupies a page by itself; upload limits
8
+ // still bound that single report and the cursor must always make progress.
9
+ export const FINDING_CATALOG_PAGE_COUNT = 128
10
+ export const FINDING_CATALOG_PAGE_BYTES = 32 * 1024 * 1024
@@ -0,0 +1,16 @@
1
+ import { MIMEType } from 'node:util'
2
+
3
+ // The metadata envelope is opt-in. Wildcards keep the legacy raw report;
4
+ // an explicit, acceptable application/json range requests the envelope.
5
+ export function acceptsReportMetadata(accept: string | undefined): boolean {
6
+ // Commas inside quoted media-type parameters do not separate ranges.
7
+ for (const range of accept?.match(/(?:[^",]|"(?:\\.|[^"\\])*")+/gu) ?? []) {
8
+ try {
9
+ const media = new MIMEType(range.trim())
10
+ if (media.essence !== 'application/json') continue
11
+ const quality = media.params.get('q') ?? '1'
12
+ if (/^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u.test(quality) && Number(quality) > 0) return true
13
+ } catch { /* Ignore malformed media ranges. */ }
14
+ }
15
+ return false
16
+ }
@@ -0,0 +1,181 @@
1
+ import { Buffer } from 'node:buffer'
2
+ import { createHash } from 'node:crypto'
3
+ import { extname } from 'node:path'
4
+ import { promisify } from 'node:util'
5
+ import { gzip } from 'node:zlib'
6
+ import { bundlePackageDirs, bundleSourcesAsMap } from '../common/bundle-sources.js'
7
+ import { bundleSourceLinkImports } from '../common/bundle-source-links.js'
8
+ import type { BundleDetails } from '../common/bundle-metadata.js'
9
+ import { loadManagedFindings, managedFindingSourcePaths } from '../common/managed/report-content.ts'
10
+ import { type ViewerPermissions, filterReportContent } from '../common/managed/report-filter.ts'
11
+ import { ourRepoSlugs } from '../common/finding-repo.js'
12
+ import { CacheMissError, type CacheStorage } from './cache-storage.ts'
13
+ import { readBundleDetails } from './bundle-cache.ts'
14
+ import type { BlobStore } from './blob-store.ts'
15
+ import type { BundleStore } from './bundle-store.ts'
16
+ import type { ManagedBundle, ManagedDb, ReportRecord } from './db.ts'
17
+ import { inTurns } from './queue.ts'
18
+
19
+ const compress = promisify(gzip)
20
+ const reportFormat = (filename: string) => extname(filename).toLowerCase()
21
+
22
+ function bundleDirectory(id: string) {
23
+ if (!/^[a-f\d-]{36}$/iu.test(id)) throw new Error('Invalid bundle id')
24
+ return id
25
+ }
26
+ function reportDirectory(bundleId: string, sha256: string) {
27
+ return `${bundleDirectory(bundleId)}/v1-${createHash('sha256').update(sha256).digest('hex')}`
28
+ }
29
+ function formatDirectory(bundleId: string, sha256: string, name: string) {
30
+ return `${reportDirectory(bundleId, sha256)}/${createHash('sha256').update(reportFormat(name)).digest('hex')}`
31
+ }
32
+ function sourceCacheFilename(report: ReportRecord, bundle: ManagedBundle, permissions: ViewerPermissions, repo: { github: string | null }, sourcePaths?: Set<string>) {
33
+ const key = createHash('sha256').update(JSON.stringify([
34
+ 'finding-access-v10', sourcePaths ? [...sourcePaths].toSorted() : null, bundle.integrity, bundle.kind, permissions.dependencies, permissions.security, repo,
35
+ ])).digest('hex')
36
+ return `${formatDirectory(bundle.id, report.sha256, report.filename)}/${key}.json.gz`
37
+ }
38
+
39
+ // Match the report's spelling exactly, then an unambiguous path suffix. Never
40
+ // guess between duplicate basenames or treat a bundle path as a disk pathname.
41
+ function selectSources(sourcePaths: Set<string>, sources: Map<string, string>) {
42
+ const byBasename = new Map<string, string[]>()
43
+ for (const file of sources.keys()) {
44
+ const basename = file.split('/').at(-1)!
45
+ const candidates = byBasename.get(basename) ?? []
46
+ candidates.push(file)
47
+ byBasename.set(basename, candidates)
48
+ }
49
+ const files = new Map<string, string>(), paths = new Map<string, string>()
50
+ function add(path: unknown) {
51
+ if (typeof path !== 'string' || !path || paths.has(path)) return
52
+ let file = sources.has(path) ? path : null
53
+ if (file === null) {
54
+ const suffix = path.startsWith('/') ? path : `/${path}`
55
+ const matches = byBasename.get(path.split('/').at(-1)!)?.filter(candidate => candidate.endsWith(suffix)) ?? []
56
+ if (matches.length === 1) file = matches[0]!
57
+ }
58
+ if (file === null) return
59
+ paths.set(path, file)
60
+ files.set(file, sources.get(file)!)
61
+ }
62
+ for (const path of sourcePaths) add(path)
63
+ return { files: [...files], paths: [...paths] }
64
+ }
65
+
66
+ function encodeSources(integrity: string, details: BundleDetails, selection: ReturnType<typeof selectSources>) {
67
+ const sources = new Map(selection.files)
68
+ const imports = [...bundleSourceLinkImports(details, sources)].map(([parent, targets]) => [parent, [...targets]])
69
+ const bundle = details.kind === 'stasis' ? details.bundle as { formats: Map<string, string> } : null
70
+ const formats = [...(bundle?.formats ?? [])].filter(([file]) => sources.has(file))
71
+ const packageDirs = [...(bundlePackageDirs(details) ?? [])].filter(([file]) => sources.has(file))
72
+ return compress(Buffer.from(JSON.stringify({ integrity, ...selection, imports, formats, packageDirs })), { level: 6 })
73
+ }
74
+
75
+ type SourcemapEdges = (bundle: ManagedBundle) => Promise<BundleDetails['edges']>
76
+
77
+ // A sourcemap's imports follow the edges its metadata keeps (the bundle
78
+ // cache's `sourcemapEdges`), read with the parser, else what edges-lite.js reads.
79
+ async function lendSourcemapEdges(details: BundleDetails, bundle: ManagedBundle, sourcemapEdges?: SourcemapEdges) {
80
+ if (details.kind !== 'sourcemap' || !sourcemapEdges) return
81
+ const edges = await sourcemapEdges(bundle).catch(() => undefined)
82
+ if (edges) details.edges = edges
83
+ }
84
+
85
+ // The repositories that are ours, so that a finding's `repo` none of them is
86
+ // left out (common/finding-repo.js isStrayRepo).
87
+ async function oursFor(db: ManagedDb, repo: { github: string | null }): Promise<Set<string>> {
88
+ return ourRepoSlugs([...(await db.listSelectedRepos()).map(selected => selected.fullName), repo.github])
89
+ }
90
+
91
+ // Immutable report hashes share a derivative across duplicate uploads. Bundle
92
+ // identity and visibility are part of the key: a broader viewer's sources must
93
+ // never populate a restricted response. Group derivatives by hash and filename
94
+ // format so each format's permissions can be removed after its last deletion.
95
+ export function createReportSourcesCache(storage: CacheStorage, db: ManagedDb, reports: BlobStore, bundles: BundleStore, sourcemapEdges?: SourcemapEdges) {
96
+ const pending = new Map<string, { reportId: string; job: Promise<boolean> }>()
97
+ const enqueue = inTurns(1)
98
+ async function referenced(report: ReportRecord, bundle: ManagedBundle) {
99
+ const names = await db.listReportFilenamesWithBundleHash(bundle.id, report.sha256)
100
+ return names.some(name => reportFormat(name) === reportFormat(report.filename)) && await db.getBundle(bundle.id) != null
101
+ }
102
+ async function build(target: string, report: ReportRecord, bundle: ManagedBundle, permissions: ViewerPermissions, repo: { github: string | null }, sourcePaths?: Set<string>) {
103
+ // Team requests supply paths from their already-filtered members. Reopening
104
+ // the original report by ID would conflate visible and hidden occurrences.
105
+ if (!sourcePaths) {
106
+ const bytes = await reports.get(report.id)
107
+ if (!bytes) return false
108
+ const parsed = await loadManagedFindings(filterReportContent(bytes.toString('utf8'), permissions, report.filename, repo, await oursFor(db, repo)), report.filename)
109
+ if (!parsed) return false
110
+ sourcePaths = managedFindingSourcePaths(parsed.findings)
111
+ }
112
+ const details = await readBundleDetails(bundle, bundles)
113
+ if (!details) return false
114
+ await lendSourcemapEdges(details, bundle, sourcemapEdges)
115
+ const selection = selectSources(sourcePaths, bundleSourcesAsMap(details))
116
+ const body = await encodeSources(bundle.integrity, details, selection)
117
+ // A duplicate with the same hash AND format can use these parsed bytes.
118
+ // Another format must not keep a deleted variant's late build alive.
119
+ if (!(await referenced(report, bundle))) return false
120
+ await storage.put(target, body)
121
+ // Another instance may finish deletion while this write is in flight.
122
+ // Recheck after publishing so a late builder cannot resurrect its cache.
123
+ if (!(await referenced(report, bundle))) {
124
+ await storage.delete(formatDirectory(bundle.id, report.sha256, report.filename))
125
+ return false
126
+ }
127
+ return true
128
+ }
129
+ async function ensure(target: string, report: ReportRecord, bundle: ManagedBundle, permissions: ViewerPermissions, repo: { github: string | null }, sourcePaths?: Set<string>): Promise<boolean> {
130
+ const existing = pending.get(target)
131
+ if (existing) {
132
+ const ready = await existing.job
133
+ if (ready || existing.reportId === report.id) return ready
134
+ // Deletion can also win before the initiator reads its blob. Retry with
135
+ // this request's row instead of caching that other row's miss as 204.
136
+ const initiator = await db.getReport(existing.reportId)
137
+ if (initiator?.bundleId === bundle.id && initiator.sha256 === report.sha256) return false
138
+ if (pending.get(target) === existing) pending.delete(target)
139
+ return ensure(target, report, bundle, permissions, repo, sourcePaths)
140
+ }
141
+ const job = (async () => {
142
+ if (await storage.exists(target)) return true
143
+ // Serial cold builds bound peak decompression/parsing memory.
144
+ return enqueue(() => build(target, report, bundle, permissions, repo, sourcePaths))
145
+ })()
146
+ const entry = { reportId: report.id, job }
147
+ pending.set(target, entry)
148
+ try { return await job } finally { if (pending.get(target) === entry) pending.delete(target) }
149
+ }
150
+ return {
151
+ async open(report: ReportRecord, bundle: ManagedBundle, permissions: ViewerPermissions, sourcePaths?: Set<string>) {
152
+ const repo = { github: report.repoId == null ? null : await db.getRepoFullName(report.repoId) }
153
+ const target = sourceCacheFilename(report, bundle, permissions, repo, sourcePaths)
154
+ try { return { ...await storage.open(target), repo } }
155
+ catch (error) { if (!(error instanceof CacheMissError)) throw error }
156
+ if (!(await ensure(target, report, bundle, permissions, repo, sourcePaths))) return null
157
+ const opened = await storage.open(target)
158
+ return { ...opened, repo }
159
+ },
160
+ async deleteBundle(id: string) {
161
+ const prefix = `${bundleDirectory(id)}/`
162
+ await Promise.allSettled([...pending].filter(([key]) => key.startsWith(prefix)).map(([, entry]) => entry.job))
163
+ await storage.delete(bundleDirectory(id))
164
+ },
165
+ async deleteReport(report: Pick<ReportRecord, 'bundleId' | 'sha256' | 'filename'>) {
166
+ const { bundleId, sha256 } = report
167
+ if (bundleId === null) return
168
+ // Called after metadata deletion. Serialize with builders so a cold
169
+ // request cannot recreate a derivative after its cleanup has finished.
170
+ await enqueue(async () => {
171
+ const names = await db.listReportFilenamesWithBundleHash(bundleId, sha256)
172
+ if (names.length === 0) {
173
+ await storage.delete(reportDirectory(bundleId, sha256))
174
+ } else if (!names.some(name => reportFormat(name) === reportFormat(report.filename))) {
175
+ await storage.delete(formatDirectory(bundleId, sha256, report.filename))
176
+ }
177
+ })
178
+ },
179
+ }
180
+ }
181
+ export type ReportSourcesCache = ReturnType<typeof createReportSourcesCache>