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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (442) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +16 -78
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +6 -0
  13. package/common/bundle-compare-diff.js +377 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-imports.js +20 -0
  20. package/common/bundle-metadata.d.ts +15 -0
  21. package/common/bundle-metadata.js +226 -0
  22. package/common/bundle-pkg-of.d.ts +1 -0
  23. package/common/bundle-pkg-of.js +90 -0
  24. package/common/bundle-reasons.d.ts +6 -0
  25. package/common/bundle-reasons.js +58 -0
  26. package/common/bundle-source-links.d.ts +6 -0
  27. package/common/bundle-source-links.js +216 -0
  28. package/common/bundle-sourcemap.d.ts +10 -0
  29. package/common/bundle-sourcemap.js +100 -0
  30. package/common/bundle-sources.d.ts +10 -0
  31. package/common/bundle-sources.js +374 -0
  32. package/common/bundle-stats.js +41 -0
  33. package/common/bundle-tabs.js +1 -0
  34. package/common/code-language.js +66 -0
  35. package/common/default-scan-models.ts +36 -0
  36. package/common/dependency-reviews.d.ts +18 -0
  37. package/common/dependency-reviews.js +64 -0
  38. package/common/finding-duplicates.js +63 -0
  39. package/common/finding-filters.js +313 -0
  40. package/common/finding-id.js +47 -0
  41. package/common/finding-repo.d.ts +5 -0
  42. package/common/finding-repo.js +67 -0
  43. package/common/github-issue-labels.d.ts +1 -0
  44. package/common/github-issue-labels.js +11 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +14 -0
  48. package/common/line-diff.js +181 -0
  49. package/common/linked-workspace-groups.js +63 -0
  50. package/common/managed/agent-tasks.ts +292 -0
  51. package/common/managed/comments.ts +43 -0
  52. package/common/managed/dependency-routes.js +25 -0
  53. package/common/managed/directory-packages.ts +28 -0
  54. package/common/managed/finding-detail.d.ts +5 -0
  55. package/common/managed/finding-detail.js +75 -0
  56. package/common/managed/finding-values.d.ts +2 -0
  57. package/common/managed/finding-values.js +138 -0
  58. package/common/managed/github-agents.ts +114 -0
  59. package/common/managed/github-logins.ts +49 -0
  60. package/common/managed/lite-name.d.ts +2 -0
  61. package/common/managed/lite-name.js +20 -0
  62. package/common/managed/npm-packages.d.ts +9 -0
  63. package/common/managed/npm-packages.js +63 -0
  64. package/common/managed/permissions.ts +31 -0
  65. package/common/managed/report-content.ts +72 -0
  66. package/common/managed/report-filter.ts +120 -0
  67. package/common/managed/repository-alias.ts +65 -0
  68. package/common/managed/review-view-routes.js +23 -0
  69. package/common/managed/risk-routes.js +30 -0
  70. package/common/managed/roles.ts +41 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +385 -0
  73. package/common/managed/scan-models.ts +6 -0
  74. package/common/managed/stasis-config.ts +7 -0
  75. package/common/managed/team-app.d.ts +19 -0
  76. package/common/managed/team-app.js +129 -0
  77. package/common/managed/team-filters.js +26 -0
  78. package/common/managed/triage.ts +83 -0
  79. package/common/managed/upload-seal.ts +126 -0
  80. package/common/pretty-json.js +98 -0
  81. package/common/pretty-kinds.js +20 -0
  82. package/common/pretty-print.d.ts +6 -0
  83. package/common/pretty-print.js +36 -0
  84. package/common/pretty-sourcemap.js +70 -0
  85. package/common/repo-commit.d.ts +4 -0
  86. package/common/repo-commit.js +30 -0
  87. package/common/revalidation-conflicts.js +48 -0
  88. package/common/revalidation-input-groups.js +56 -0
  89. package/common/save-error-reason.ts +20 -7
  90. package/common/scan-server.ts +13 -0
  91. package/common/security-links.d.ts +5 -0
  92. package/common/security-links.js +33 -0
  93. package/common/server-info.ts +46 -0
  94. package/common/sourcemap-listing.js +78 -0
  95. package/common/sourcemap-mappings.js +136 -0
  96. package/common/sourcemap-unlist.js +85 -0
  97. package/common/stasis-files.d.ts +5 -0
  98. package/common/stasis-files.js +20 -0
  99. package/common/stasis-tgz.d.ts +6 -0
  100. package/common/stasis-tgz.js +27 -0
  101. package/common/utf8.d.ts +3 -0
  102. package/common/utf8.js +45 -0
  103. package/common/whitespace-insensitive.js +19 -0
  104. package/common/workspace-app.js +91 -0
  105. package/common/workspace-groups.js +176 -0
  106. package/out/activity.js +2 -0
  107. package/out/brotli-fallback.js +3 -3
  108. package/out/chunk-2XUEZHIP.js +28 -0
  109. package/out/chunk-55YIWY3H.js +5 -0
  110. package/out/chunk-563V5VVT.js +266 -0
  111. package/out/chunk-5AVGKFMR.js +1 -0
  112. package/out/chunk-5EAVJAD2.js +3 -0
  113. package/out/chunk-5M2X3QPK.js +6 -0
  114. package/out/chunk-5QWPKTCE.js +40 -0
  115. package/out/chunk-5UJHJWFU.js +4 -0
  116. package/out/chunk-6CCSTJWB.js +1 -0
  117. package/out/chunk-6VOB5WXX.js +2 -0
  118. package/out/chunk-6WMQVUT2.js +3 -0
  119. package/out/chunk-6Y6PZ2BU.js +9 -0
  120. package/out/chunk-74JZTGTO.js +11 -0
  121. package/out/chunk-7BKKYVWR.js +7 -0
  122. package/out/chunk-7C7DWL7I.js +1 -0
  123. package/out/chunk-7HP2VYIC.js +2 -0
  124. package/out/chunk-7YFJUT2P.js +1 -0
  125. package/out/chunk-7YO4QV5P.js +1 -0
  126. package/out/chunk-A4BBBHQU.js +1 -0
  127. package/out/chunk-B64CTMVU.js +4 -0
  128. package/out/chunk-BEKYZCPX.js +14 -0
  129. package/out/chunk-C4Z6ZBXV.js +10 -0
  130. package/out/chunk-CU3FPB3P.js +1 -0
  131. package/out/chunk-DEVAORP2.js +1 -0
  132. package/out/chunk-DOYTKRIR.js +53 -0
  133. package/out/chunk-DUASGS2O.js +8 -0
  134. package/out/chunk-EEJA7JBI.js +13 -0
  135. package/out/chunk-FSU2PLJL.js +1 -0
  136. package/out/chunk-GO7FT4OD.js +1 -0
  137. package/out/chunk-GX5UXWT4.js +1 -0
  138. package/out/chunk-H4FEC57K.js +1 -0
  139. package/out/chunk-ITUKKCCK.js +10 -0
  140. package/out/chunk-IYPY47MC.js +1 -0
  141. package/out/chunk-K4XJHM2T.js +1 -0
  142. package/out/chunk-LBD3M3J6.js +1 -0
  143. package/out/chunk-LVSLM7HB.js +1 -0
  144. package/out/chunk-LVW7WWV4.js +1 -0
  145. package/out/chunk-N57OWFKY.js +15 -0
  146. package/out/chunk-NRPC74AM.js +1 -0
  147. package/out/chunk-OAWQNDAO.js +3 -0
  148. package/out/chunk-OOJM4CTU.js +1 -0
  149. package/out/chunk-PEE47ANR.js +1 -0
  150. package/out/chunk-PKLVXUEI.js +11 -0
  151. package/out/chunk-PLGH63UC.js +2 -0
  152. package/out/chunk-PNHBZGDD.js +1 -0
  153. package/out/chunk-PTFYDJUP.js +1 -0
  154. package/out/chunk-PWFUOLZK.js +17 -0
  155. package/out/chunk-PXK7EU4V.js +1 -0
  156. package/out/chunk-QD3IBSF4.js +7 -0
  157. package/out/chunk-QI66YA4F.js +1 -0
  158. package/out/chunk-QRKFPLA4.js +80 -0
  159. package/out/chunk-R3NZFXVR.js +1 -0
  160. package/out/chunk-R5O6FAW4.js +2 -0
  161. package/out/chunk-RPNO56H2.js +1 -0
  162. package/out/chunk-SSPDMA6D.js +1 -0
  163. package/out/chunk-SZWPYLPC.js +1 -0
  164. package/out/chunk-TUII34K2.js +1 -0
  165. package/out/chunk-UJP4PQJA.js +1 -0
  166. package/out/chunk-UJSJMXEG.js +1 -0
  167. package/out/chunk-UR4WYMIP.js +1 -0
  168. package/out/chunk-VHEXSGGP.js +1 -0
  169. package/out/chunk-VYYUMYVW.js +9 -0
  170. package/out/chunk-WCDYSIKG.js +1 -0
  171. package/out/chunk-WFBVS4QI.js +1 -0
  172. package/out/chunk-XM4RLC4A.js +2 -0
  173. package/out/chunk-ZQHLECTI.js +1 -0
  174. package/out/client-managed-import.js +4 -0
  175. package/out/client-managed.js +37 -0
  176. package/out/client-sync.js +11 -17
  177. package/out/compare.js +26 -0
  178. package/out/dialogs.js +40 -0
  179. package/out/github-issue-authorized.html +3 -0
  180. package/out/github-issue-authorized.js +1 -0
  181. package/out/graph.js +19 -4
  182. package/out/index.html +104 -24
  183. package/out/prism.js +14 -10
  184. package/out/scan.js +2 -0
  185. package/out/stasis.svg +20 -0
  186. package/out/terminal.js +367 -39
  187. package/out/view.css +1 -1
  188. package/out/view.js +19 -147
  189. package/package.json +409 -64
  190. package/risk/actions/findings.js +161 -0
  191. package/risk/actions/resolve.js +287 -0
  192. package/risk/actions/scripts/commands.js +182 -0
  193. package/risk/actions/scripts/grade.js +113 -0
  194. package/risk/actions/scripts/packages.js +123 -0
  195. package/risk/actions/scripts/shell.js +169 -0
  196. package/risk/actions/uses.js +94 -0
  197. package/risk/actions/workflow.js +183 -0
  198. package/risk/files/characters.js +354 -0
  199. package/risk/files/hosts.js +206 -0
  200. package/risk/files/readability.js +185 -0
  201. package/risk/files/runs-code.js +568 -0
  202. package/risk/files/script.js +410 -0
  203. package/risk/files/source-map-link.js +43 -0
  204. package/risk/files/stamps.js +47 -0
  205. package/risk/index.d.ts +294 -0
  206. package/risk/index.js +12 -0
  207. package/risk/npm/assess.js +285 -0
  208. package/risk/npm/combined.js +68 -0
  209. package/risk/npm/compare.js +236 -0
  210. package/risk/npm/dependencies.js +172 -0
  211. package/risk/npm/diff.js +79 -0
  212. package/risk/npm/downloads.js +84 -0
  213. package/risk/npm/files.js +445 -0
  214. package/risk/npm/held.js +67 -0
  215. package/risk/npm/install-scripts.js +34 -0
  216. package/risk/npm/malware.js +38 -0
  217. package/risk/npm/manifest.js +65 -0
  218. package/risk/npm/new-dependency.js +60 -0
  219. package/risk/npm/old-version.js +108 -0
  220. package/risk/npm/registry.js +393 -0
  221. package/risk/npm/release.js +85 -0
  222. package/risk/npm/score.js +59 -0
  223. package/risk/npm/specs.js +124 -0
  224. package/risk/npm/tarball.js +169 -0
  225. package/server-common/database-config.ts +16 -0
  226. package/server-common/initialize.ts +18 -0
  227. package/server-common/npm-advisories.ts +101 -0
  228. package/{server → server-common}/origin.ts +5 -5
  229. package/server-common/reap.ts +48 -0
  230. package/server-common/scan-config.ts +19 -0
  231. package/server-common/standalone.ts +29 -0
  232. package/server-common/storage-crypto.ts +182 -0
  233. package/server-common/storage-log.ts +38 -0
  234. package/server-common/vercel-blob.ts +103 -0
  235. package/server-e2e/app.ts +487 -0
  236. package/{server → server-e2e}/bus-receiver.ts +2 -1
  237. package/{server → server-e2e}/cli.js +9 -4
  238. package/{server → server-e2e}/config.ts +50 -42
  239. package/{server → server-e2e}/db-neon.ts +2 -2
  240. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  241. package/{server → server-e2e}/db-stmt.ts +2 -2
  242. package/{server → server-e2e}/db.ts +7 -7
  243. package/{server → server-e2e}/http.ts +44 -13
  244. package/{server → server-e2e}/hub.ts +40 -9
  245. package/server-e2e/index.ts +17 -0
  246. package/server-e2e/lifecycle.ts +95 -0
  247. package/{server → server-e2e}/neon-driver.ts +2 -2
  248. package/{server → server-e2e}/npm-proxy.ts +12 -145
  249. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  250. package/{server → server-e2e}/objstore/blob.ts +1 -1
  251. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  252. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  253. package/{server → server-e2e}/objstore/init.ts +19 -27
  254. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  255. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  257. package/{server → server-e2e}/objstore/rest.ts +3 -3
  258. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  259. package/{server → server-e2e}/objstore/store.ts +7 -7
  260. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  261. package/{server → server-e2e}/pubsub.ts +12 -9
  262. package/{server → server-e2e}/sign.ts +4 -4
  263. package/{server → server-e2e}/sse-server.ts +60 -33
  264. package/{server → server-e2e}/static.ts +18 -17
  265. package/{server → server-e2e}/sync-handlers.ts +64 -30
  266. package/{server → server-e2e}/ws-server.ts +20 -9
  267. package/server-managed/activity.ts +269 -0
  268. package/server-managed/agent-merges.ts +109 -0
  269. package/server-managed/app-agents.ts +23 -0
  270. package/server-managed/avatar-store.ts +13 -0
  271. package/server-managed/blob-store.ts +26 -0
  272. package/server-managed/brotli.ts +10 -0
  273. package/server-managed/bundle-advisories.ts +79 -0
  274. package/server-managed/bundle-advisory-inventory.ts +85 -0
  275. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  276. package/server-managed/bundle-build-diagnostics.js +23 -0
  277. package/server-managed/bundle-build-leases.ts +41 -0
  278. package/server-managed/bundle-build-worker.js +380 -0
  279. package/server-managed/bundle-build.ts +326 -0
  280. package/server-managed/bundle-cache.ts +261 -0
  281. package/server-managed/bundle-catalog.ts +29 -0
  282. package/server-managed/bundle-commits.ts +133 -0
  283. package/server-managed/bundle-dependency-reviews.ts +91 -0
  284. package/server-managed/bundle-store.ts +24 -0
  285. package/server-managed/bundle-summary-cache.ts +139 -0
  286. package/server-managed/bundle-validation.ts +33 -0
  287. package/server-managed/bundle.ts +151 -0
  288. package/server-managed/cache-storage.ts +20 -0
  289. package/server-managed/cli.js +21 -0
  290. package/server-managed/combined.ts +43 -0
  291. package/server-managed/comments.ts +138 -0
  292. package/server-managed/commit-coauthors.ts +105 -0
  293. package/server-managed/commit-lockfiles.ts +78 -0
  294. package/server-managed/comparison.ts +51 -0
  295. package/server-managed/config.ts +163 -0
  296. package/server-managed/content-access.ts +15 -0
  297. package/server-managed/crypto.ts +25 -0
  298. package/server-managed/db-methods.ts +1915 -0
  299. package/server-managed/db-neon.ts +398 -0
  300. package/server-managed/db-schema.ts +263 -0
  301. package/server-managed/db-table-names.ts +22 -0
  302. package/server-managed/db.ts +149 -0
  303. package/server-managed/dependabot-access.ts +61 -0
  304. package/server-managed/dependabot-alerts.ts +180 -0
  305. package/server-managed/dependency-review-comments.ts +158 -0
  306. package/server-managed/dependency-reviews.ts +369 -0
  307. package/server-managed/github-accounts.ts +59 -0
  308. package/server-managed/github-actions.ts +71 -0
  309. package/server-managed/github-app.ts +347 -0
  310. package/server-managed/github-errors.ts +92 -0
  311. package/server-managed/github-graphql.ts +42 -0
  312. package/server-managed/github-issue-links.ts +264 -0
  313. package/server-managed/github-issue-oauth.ts +30 -0
  314. package/server-managed/github-issues.ts +157 -0
  315. package/server-managed/github-link-oauth.ts +56 -0
  316. package/server-managed/github-links.ts +204 -0
  317. package/server-managed/github-metadata.ts +213 -0
  318. package/server-managed/github-oauth.ts +264 -0
  319. package/server-managed/github-pulls.ts +257 -0
  320. package/server-managed/github-requests.ts +181 -0
  321. package/server-managed/github-users.ts +30 -0
  322. package/server-managed/github-values.ts +26 -0
  323. package/server-managed/history-windows.ts +172 -0
  324. package/server-managed/http-response.ts +76 -0
  325. package/server-managed/http.ts +6327 -0
  326. package/server-managed/import-triage.ts +51 -0
  327. package/server-managed/index.ts +204 -0
  328. package/server-managed/kept-briefly.ts +37 -0
  329. package/server-managed/kept.ts +28 -0
  330. package/server-managed/link-reports.ts +149 -0
  331. package/server-managed/listed-activity.ts +39 -0
  332. package/server-managed/locked-packages.ts +234 -0
  333. package/server-managed/lockfile-scope.ts +58 -0
  334. package/server-managed/lru.ts +30 -0
  335. package/server-managed/managed-issues.ts +92 -0
  336. package/server-managed/management-catalog.ts +45 -0
  337. package/server-managed/management.ts +116 -0
  338. package/server-managed/npm-delta-worker.js +142 -0
  339. package/server-managed/npm-delta.ts +277 -0
  340. package/server-managed/npm-insights.ts +455 -0
  341. package/server-managed/npm-kept.ts +265 -0
  342. package/server-managed/npm-loads.ts +259 -0
  343. package/server-managed/npm-manifest.ts +117 -0
  344. package/server-managed/npm-packages.ts +469 -0
  345. package/server-managed/npm-patch-paths.ts +86 -0
  346. package/server-managed/npm-patch.ts +455 -0
  347. package/server-managed/npm-provenance.ts +127 -0
  348. package/server-managed/npm-risk.ts +287 -0
  349. package/server-managed/object-storage-disk.ts +147 -0
  350. package/server-managed/object-storage-vercel.ts +71 -0
  351. package/server-managed/object-storage.ts +82 -0
  352. package/server-managed/package-entry-points.ts +127 -0
  353. package/server-managed/pretty-copies.ts +22 -0
  354. package/server-managed/pretty-format.d.ts +3 -0
  355. package/server-managed/pretty-format.js +13 -0
  356. package/server-managed/pretty-print.ts +442 -0
  357. package/server-managed/public-workspace.ts +243 -0
  358. package/server-managed/pull-comment-reviews.ts +161 -0
  359. package/server-managed/pull-dependencies.ts +370 -0
  360. package/server-managed/pull-dependency-reviews.ts +407 -0
  361. package/server-managed/pull-reviews.ts +202 -0
  362. package/server-managed/queue.ts +54 -0
  363. package/server-managed/release-commits.ts +85 -0
  364. package/server-managed/rename-diff-worker.js +30 -0
  365. package/server-managed/rename-diff.ts +237 -0
  366. package/server-managed/repo-path.ts +21 -0
  367. package/server-managed/report-migration.ts +32 -0
  368. package/server-managed/report-opening.ts +77 -0
  369. package/server-managed/report-query.ts +10 -0
  370. package/server-managed/report-response.ts +16 -0
  371. package/server-managed/report-sources.ts +185 -0
  372. package/server-managed/report-store.ts +77 -0
  373. package/server-managed/repository-actions.ts +220 -0
  374. package/server-managed/repository-agents.ts +422 -0
  375. package/server-managed/repository-aliases.ts +119 -0
  376. package/server-managed/repository-browser.ts +361 -0
  377. package/server-managed/repository-changes.ts +280 -0
  378. package/server-managed/repository-code.ts +222 -0
  379. package/server-managed/repository-dependency-reviews.ts +182 -0
  380. package/server-managed/repository-discovery.ts +83 -0
  381. package/server-managed/repository-history.ts +428 -0
  382. package/server-managed/repository-issues.ts +293 -0
  383. package/server-managed/repository-policy.ts +27 -0
  384. package/server-managed/repository-pulls.ts +207 -0
  385. package/server-managed/repository-pulse.ts +477 -0
  386. package/server-managed/repository-risk-assess.ts +108 -0
  387. package/server-managed/repository-risk-audit.ts +78 -0
  388. package/server-managed/repository-risk-caches.ts +37 -0
  389. package/server-managed/repository-risk-read.ts +260 -0
  390. package/server-managed/repository-risk-stasis.ts +61 -0
  391. package/server-managed/repository-risk-turn.ts +97 -0
  392. package/server-managed/repository-risk.ts +516 -0
  393. package/server-managed/repository-squashes.ts +160 -0
  394. package/server-managed/repository-stamp.ts +41 -0
  395. package/server-managed/request-timing.ts +63 -0
  396. package/server-managed/reviewed-dependencies.ts +170 -0
  397. package/server-managed/revisions.ts +35 -0
  398. package/server-managed/scan-downloads.ts +121 -0
  399. package/server-managed/session.ts +132 -0
  400. package/server-managed/slugs.ts +38 -0
  401. package/server-managed/solidity-entry-points.ts +71 -0
  402. package/server-managed/sql-postgres.ts +34 -0
  403. package/server-managed/sql.ts +107 -0
  404. package/server-managed/stasis-config.ts +147 -0
  405. package/server-managed/stasis-dependencies.ts +221 -0
  406. package/server-managed/static.ts +28 -0
  407. package/server-managed/storage-command.ts +16 -0
  408. package/server-managed/storage-db.ts +183 -0
  409. package/server-managed/storage-encryption.ts +288 -0
  410. package/server-managed/storage-maintenance.ts +259 -0
  411. package/server-managed/storage-payload.ts +121 -0
  412. package/server-managed/storage-stores.ts +91 -0
  413. package/server-managed/storage.ts +82 -0
  414. package/server-managed/team-app-summaries.ts +56 -0
  415. package/server-managed/team-app.ts +156 -0
  416. package/server-managed/team-catalog.ts +7 -0
  417. package/server-managed/team-feed.ts +180 -0
  418. package/server-managed/team-npm-scopes.ts +103 -0
  419. package/server-managed/team-reports.ts +368 -0
  420. package/server-managed/triage-response.ts +16 -0
  421. package/server-managed/type-only-proof.js +161 -0
  422. package/server-managed/type-only-worker.js +31 -0
  423. package/server-managed/type-only.ts +135 -0
  424. package/server-managed/uploads.ts +106 -0
  425. package/server-managed/upstream-cache.ts +256 -0
  426. package/server-managed/view-as.ts +58 -0
  427. package/server-managed/worker-turns.ts +76 -0
  428. package/server-managed/workspace-shares.ts +170 -0
  429. package/server.ts +70 -0
  430. package/strip-types-loader.js +13 -10
  431. package/server/index.ts +0 -480
  432. package/server/lifecycle.ts +0 -208
  433. /package/{LICENSE → LICENSE-MIT} +0 -0
  434. /package/{server → server-e2e}/auth.ts +0 -0
  435. /package/{server → server-e2e}/config.example.json +0 -0
  436. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  437. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  438. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  439. /package/{server → server-e2e}/peer.ts +0 -0
  440. /package/{server → server-e2e}/sse-session.ts +0 -0
  441. /package/{server → server-e2e}/util.ts +0 -0
  442. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,455 @@
1
+ // A pnpm patch of an npm package version (patchedDependencies), as its
2
+ // dependency review reads it (pull-dependency-reviews.ts): its file, which a
3
+ // lockfile names (locked-packages.ts `patchPath`), or which is found where it
4
+ // names it by its hash alone (withPatchFiles), or by its hash among a
5
+ // commit's patches (foundPatch), read of a repository at a commit, and held
6
+ // to the hash the lockfile names it by, as pnpm 10 and later hash it
7
+ // (hashOfPatch; one pnpm 9 names by an md5 isn't read), by which it is kept
8
+ // for good, read of GitHub once; and applied to the version's files as pnpm applies
9
+ // it as it installs it (patch-package's applyPatch, which pnpm 10 bundles):
10
+ // each file it deletes, creates, renames or changes, a change's hunks each
11
+ // found in the file as it was, where its header says, else as many as FUZZ
12
+ // lines either side, its lines the same but for the space they end in, and
13
+ // those it keeps kept as the file has them. pnpm 10, 11 and 12 each read a
14
+ // patch their own way, so one is read only where none installs other than
15
+ // it shows (parsePatch): a line outside what git writes, paths that
16
+ // disagree, a rename that also creates or deletes, or a hunk whose missing
17
+ // final newline the file doesn't bear out, isn't read. A file it makes
18
+ // executable, or no longer, is so, as every pnpm makes it. Nor is a patch of
19
+ // a file's bytes (git's binary patch) or of a mode but 644 and 755, or of a
20
+ // file outside the package, read; and one that doesn't apply fails as a whole.
21
+ import { Buffer } from 'node:buffer'
22
+ import { createHash } from 'node:crypto'
23
+ import { YamlError, parseYaml } from '@preventive/lockfile/yaml.js'
24
+ import { isGithubRepoName } from '../common/github-pr.ts'
25
+ import { isPatchHash, isPatchPath } from '../common/managed/npm-packages.js'
26
+ import { GithubApiError } from './github-errors.ts'
27
+ import { isStasisConfig } from '../common/managed/stasis-config.ts'
28
+ import { SHA, isId } from './github-values.ts'
29
+ import { type LockedPackage, pathFrom } from './locked-packages.ts'
30
+ import { type Lru, lru } from './lru.ts'
31
+ import type { KeptStore } from './npm-kept.ts'
32
+ import { plainObject } from './npm-manifest.ts'
33
+ import { NpmPackageError, type NpmPackageFile, npmFileText, pathOrder } from './npm-packages.ts'
34
+ import { gitPath, isPlainPath, namesBoth, pathClaims, sidePath, unquoted } from './npm-patch-paths.ts'
35
+ import { type GithubAsked, type PullDependencies, lockfileFormat, repositoryFile } from './pull-dependencies.ts'
36
+ import { eachOf } from './queue.ts'
37
+
38
+ // Where a patch is read: its file in a repository (by its id) at a commit,
39
+ // from the repository's root; and the patch, by its hash besides. A request
40
+ // names its repository by its id, or by its name (`owner/name`) in its place
41
+ // (http.ts wholeRepositoryAccess), and may leave its path out, the patch
42
+ // looked for there (foundPatch); or the patch by its hash alone, which only
43
+ // one kept answers (keptPatch).
44
+ export interface PatchSource { repoId: number; commit: string; path: string }
45
+ export interface NpmPatch extends PatchSource { hash: string }
46
+ export type RequestedPatch = (Omit<NpmPatch, 'repoId' | 'path'> & { repoId: number | string; path?: string }) | { hash: string }
47
+
48
+ // The most a patch's file may hold, and how many lines either side of where a
49
+ // hunk says its lines are they are looked for; and how many patches an
50
+ // answer looks for, those past them left for the next, and how many at once.
51
+ const MAX_PATCH_BYTES = 8 * 1024 * 1024
52
+ const FUZZ = 20
53
+ const MAX_FOUND = 100
54
+ const FIND_AT_ONCE = 4
55
+
56
+ // The patch a request names, by its hash (`hash`), its repository's id
57
+ // (`repoId`, a number or its digits) or name, the commit and its file's
58
+ // path or none, or by its hash alone; null where it names none, and
59
+ // 'invalid' where it names one otherwise.
60
+ export function requestedPatch({ hash, repoId, commit, path }: { hash: unknown; repoId?: unknown; commit?: unknown; path?: unknown }): RequestedPatch | null | 'invalid' {
61
+ if ([repoId, commit, path].every(field => field == null)) return hash == null ? null : isPatchHash(hash) ? { hash } : 'invalid'
62
+ const id = typeof repoId === 'string' && /^[1-9]\d{0,15}$/u.test(repoId) ? Number(repoId) : repoId
63
+ if (!isPatchHash(hash) || !(isId(id) || typeof id === 'string' && isGithubRepoName(id)) || typeof commit !== 'string' || !SHA.test(commit)
64
+ || path != null && !isPatchPath(path)) return 'invalid'
65
+ return { hash, repoId: id, commit, ...typeof path === 'string' ? { path } : {} }
66
+ }
67
+
68
+ // The hash pnpm names a patch's text by, a sha256 in hex of it with its
69
+ // CRLFs as LFs, as pnpm 10 and later read a patch's file (the CRs of lines
70
+ // it ends otherwise kept); and whether `text` is the patch `hash` names.
71
+ export const hashOfPatch = (text: string) => createHash('sha256').update(text.replaceAll('\r\n', '\n')).digest('hex')
72
+ export const isPatchOf = (text: string, hash: string) => hashOfPatch(text) === hash
73
+
74
+ // The text of a patch's file in repository `fullName` at `commit`, read with
75
+ // `token`; null where GitHub has no text of it, or it is past MAX_PATCH_BYTES.
76
+ const patchFileAt = (fullName: string, token: string, path: string, commit: string) => repositoryFile(fullName, token, path, commit).then(text => text !== null
77
+ && Buffer.byteLength(text) > MAX_PATCH_BYTES ? null : text, (err: unknown) => { if (err instanceof GithubApiError && err.message === 'github-malformed') return null; throw err })
78
+
79
+ // A change a patch makes to a file at `path` of the package: deleting it,
80
+ // creating it, renaming it from another (`from`), and its hunks, as
81
+ // patch-package reads them: where its header says its lines are (`at`, the
82
+ // first's index, as it reads `-0`, the first line), how many it finds
83
+ // (`length`), and its lines, each without its LF, in runs of a kind
84
+ // (`parts`): those it keeps, removes or adds, the last of a side told where
85
+ // the file has no LF after it (`unended`); and whether it makes the file
86
+ // executable, or no longer (`executable`), where it says.
87
+ export interface HunkPart { kind: 'context' | 'deletion' | 'insertion'; lines: string[]; unended?: true }
88
+ export interface PatchHunk { at: number; length: number; parts: HunkPart[] }
89
+ export interface PatchedFile { path: string; from?: string; deleted?: true; created?: true; executable?: boolean; hunks: PatchHunk[] }
90
+
91
+ const unreadable = () => new NpmPackageError(422, 'patch-unreadable')
92
+
93
+ // The hunk whose `@@` line is at `at` of `lines`, those before `end` read,
94
+ // and the line after it, as patch-package reads it: a line of its own
95
+ // kind, else of those it keeps where it is empty, or a CR alone.
96
+ function readHunk(lines: string[], at: number, end: number): { hunk: PatchHunk; next: number } {
97
+ const range = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/u.exec(lines[at++]!)
98
+ if (!range) throw unreadable()
99
+ let news = Number(range[4] ?? 1), olds = Number(range[2] ?? 1)
100
+ const hunk: PatchHunk = { at: Math.max(Number(range[1]), 1) - 1, length: olds, parts: [] }
101
+ // Lines added with none to find them by, past the file's start (git's -U0): pnpm 10 and 11 add them
102
+ // before the line named, pnpm 12 after it.
103
+ if (olds === 0 && Number(range[1]) > 0) throw unreadable()
104
+ while (olds > 0 || news > 0) {
105
+ // A line its count reads past those read isn't one.
106
+ if (at >= end) throw unreadable()
107
+ const line = lines[at++]!
108
+ const kind = line === '' || line === '\r' || line[0] === ' ' ? 'context' : line[0] === '-' ? 'deletion' : line[0] === '+' ? 'insertion' : null
109
+ if (!kind) throw unreadable()
110
+ const last = hunk.parts.at(-1)
111
+ const part = last?.kind === kind ? last : hunk.parts[hunk.parts.push({ kind, lines: [] }) - 1]!
112
+ part.lines.push(line.slice(1))
113
+ if (kind !== 'insertion') olds--
114
+ if (kind !== 'deletion') news--
115
+ if (olds < 0 || news < 0) throw unreadable()
116
+ // The line before it the last of its side, with no LF after it.
117
+ if (lines[at]?.startsWith('\\')) {
118
+ if (!lines[at++]!.startsWith('\')) throw unreadable()
119
+ part.unended = true
120
+ }
121
+ }
122
+ return { hunk, next: at }
123
+ }
124
+
125
+ // A patch's files as git's diff writes them, as pnpm writes a patch: a file's
126
+ // `diff --git` line, its headers, the paths its sides have, and its hunks.
127
+ // One whose own lines end in CRLFs, as an editor or git's autocrlf leaves
128
+ // one, is read as patch-package reads it: its headers but their CRs, its
129
+ // hunks' lines with them. pnpm 10 and 11 also read hunks where git puts none
130
+ // (with no `diff --git` line, past a blank or `index` line, after another
131
+ // file's hunks) and pnpm 12 doesn't, so a line git doesn't write is refused,
132
+ // but blank lines at the end. So are a `diff --git` line naming other paths
133
+ // than its sides (pnpm 10 and 11 take one, pnpm 12 the other), a rename that
134
+ // also creates or deletes, and a `new mode` line without its `old mode`
135
+ // (pnpm 12 alone reads one). Throws for one it can't read, or of bytes.
136
+ export function parsePatch(patch: string): PatchedFile[] {
137
+ // One whose last line has no LF: pnpm 12 alone adds that line without one.
138
+ if (patch !== '' && !patch.endsWith('\n')) throw unreadable()
139
+ const lines = patch.split('\n')
140
+ // The lines read: those but the empty one past the patch's last ending.
141
+ const end = lines.length - (patch.endsWith('\n') ? 1 : 0)
142
+ // A header's line but its CR.
143
+ const headerAt = (at: number) => lines[at]?.replace(/\r$/u, '') ?? ''
144
+ const files: PatchedFile[] = []
145
+ for (let at = 0; at < lines.length;) {
146
+ const head = headerAt(at++)
147
+ if (head === '' && lines.slice(at, end).every((_, i) => headerAt(at + i) === '')) break
148
+ if (!head.startsWith('diff --git ')) throw unreadable()
149
+ let created = false, deleted = false, executable: boolean | undefined, from: string | null = null, to: string | null = null
150
+ let sides: [string | null, string | null] | null = null
151
+ const seen = new Set<string>()
152
+ for (; at < end && !/^(?:diff --git |@@ |--- )/u.test(lines[at]!); at++) {
153
+ const header = headerAt(at)
154
+ if (header === 'GIT binary patch' || header.startsWith('Binary files ')) throw new NpmPackageError(422, 'patch-unsupported')
155
+ const kind = /^(?:index|similarity index|dissimilarity index|deleted file mode|new file mode|rename from|rename to|old mode|new mode|copy from|copy to) /u.exec(header)?.[0]
156
+ if (kind === undefined || seen.has(kind)) throw unreadable()
157
+ seen.add(kind)
158
+ // A mode it names: `100644`, or `100755` (executable).
159
+ const mode = kind.endsWith('mode ') ? header.slice(kind.length) : undefined
160
+ if (kind.startsWith('copy ') || (mode !== undefined && mode !== '100644' && mode !== '100755')) throw new NpmPackageError(422, 'patch-unsupported')
161
+ if (kind === 'deleted file mode ') deleted = true
162
+ else if (kind === 'new file mode ') { created = true; executable = mode === '100755' }
163
+ else if (kind === 'new mode ') executable = mode === '100755'
164
+ else if (kind === 'rename from ') from = unquoted(header.slice(kind.length))
165
+ else if (kind === 'rename to ') to = unquoted(header.slice(kind.length))
166
+ }
167
+ if (lines[at]?.startsWith('--- ')) {
168
+ if (!lines[at + 1]?.startsWith('+++ ')) throw unreadable()
169
+ sides = [sidePath(headerAt(at).slice(4), 'a/'), sidePath(headerAt(at + 1).slice(4), 'b/')]
170
+ at += 2
171
+ }
172
+ if ((from === null) !== (to === null) || (deleted && created) || (from !== null && (deleted || created)) || seen.has('old mode ') !== seen.has('new mode ')) throw unreadable()
173
+ const rest = head.slice('diff --git '.length)
174
+ const path = sides ? (created ? sides[1] : sides[0]) : gitPath(rest)
175
+ const after = to ?? path, before = from ?? path
176
+ if (before == null || after == null || ![before, after].every(name => isPatchPath(name) && isPlainPath(name)) || !namesBoth(rest, before, after)
177
+ || (sides && (sides[0] !== (created ? null : before) || sides[1] !== (deleted ? null : after)))) throw unreadable()
178
+ const hunks: PatchHunk[] = []
179
+ while (lines[at]?.startsWith('@@ ')) {
180
+ const { hunk, next } = readHunk(lines, at, end)
181
+ hunks.push(hunk)
182
+ at = next
183
+ }
184
+ // A file created is its one hunk's lines, as git writes it, which pnpm 10 alone writes of a hunk otherwise.
185
+ if (created && (hunks.length > 1 || hunks.some(hunk => hunk.parts.some(part => part.kind !== 'insertion')))) throw unreadable()
186
+ files.push({ path: deleted ? before : after, ...from === null ? {} : { from: before }, ...deleted ? { deleted: true as const } : {},
187
+ ...created ? { created: true as const } : {}, ...executable === undefined || deleted ? {} : { executable }, hunks: deleted ? [] : hunks })
188
+ }
189
+ return files
190
+ }
191
+
192
+ const doesNotApply = () => new NpmPackageError(422, 'patch-does-not-apply')
193
+
194
+ // A change a hunk makes to a file's lines (`lines`, split at its LFs): those
195
+ // at `splice` that it removes (`remove`) and adds in their place (`insert`),
196
+ // or an empty last line it adds or removes, its LF after the last.
197
+ type LineChange = { splice: number; remove: number; insert: string[] } | 'push' | 'pop'
198
+
199
+ // The changes `hunk` makes where its lines are at `at` of `lines`, as
200
+ // patch-package works them out (evaluateHunk): those it finds the same but
201
+ // for the space they end in, as it compares them; else null.
202
+ function changesAt(hunk: PatchHunk, lines: string[], at: number): LineChange[] | null {
203
+ if (at < 0 || lines.length - at < hunk.length) return null
204
+ const changes: LineChange[] = []
205
+ for (const part of hunk.parts) {
206
+ if (part.kind === 'insertion') {
207
+ changes.push({ splice: at, remove: 0, insert: part.lines })
208
+ if (part.unended) changes.push('pop')
209
+ continue
210
+ }
211
+ for (const line of part.lines) if (lines[at++]!.trimEnd() !== line.trimEnd()) return null
212
+ if (part.kind === 'deletion') {
213
+ changes.push({ splice: at - part.lines.length, remove: part.lines.length, insert: [] })
214
+ if (part.unended) changes.push('push')
215
+ }
216
+ }
217
+ return changes
218
+ }
219
+
220
+ // Whether `hunk`, found at `at` of `lines`, may say a side ends with no LF
221
+ // (`unended`): pnpm versions apply that mark alike only where the hunk ends
222
+ // where the file does, and the file agrees: no LF at its end for the old
223
+ // side's mark; one, or the old side's mark, for the new side's.
224
+ function endsAgree(hunk: PatchHunk, lines: string[], at: number): boolean {
225
+ const unended = lines.at(-1) !== ''
226
+ const ending = at + hunk.length === lines.length - (unended ? 0 : 1)
227
+ const pushes = hunk.parts.some(part => part.kind === 'deletion' && part.unended)
228
+ const pops = hunk.parts.some(part => part.kind === 'insertion' && part.unended)
229
+ return (!pushes || (ending && unended)) && (!pops || (ending && (pushes || !unended)))
230
+ }
231
+
232
+ // `text` with `hunks` applied as patch-package applies them (applyPatch):
233
+ // each one's lines found in the text as it was, where its header says, else
234
+ // as near as FUZZ lines either side, the nearer first, and the earlier of
235
+ // two as near; then its changes made in turn, past the lines those before
236
+ // added or removed.
237
+ function applied(text: string, hunks: PatchHunk[]): string {
238
+ const lines = text.split('\n')
239
+ const changes = hunks.flatMap(hunk => {
240
+ for (let offset = 0; Math.abs(offset) <= FUZZ; offset = offset < 0 ? -offset : -offset - 1) {
241
+ const found = changesAt(hunk, lines, hunk.at + offset)
242
+ // Where pnpm finds it, whatever its marks say, lest another place be shown changed than it changes.
243
+ if (found && !endsAgree(hunk, lines, hunk.at + offset)) throw doesNotApply()
244
+ if (found) return found
245
+ }
246
+ throw doesNotApply()
247
+ })
248
+ let shift = 0
249
+ for (const change of changes) {
250
+ if (change === 'push') lines.push('')
251
+ else if (change === 'pop') lines.pop()
252
+ else {
253
+ lines.splice(change.splice + shift, change.remove, ...change.insert)
254
+ shift += change.insert.length - change.remove
255
+ }
256
+ }
257
+ return lines.join('\n')
258
+ }
259
+
260
+ // A version's `files` with `patch` applied, in the order of their paths, as
261
+ // its tarball's are read; a file it changes the text of must be text. One it
262
+ // creates holds its first hunk's first lines, in place of any there, as
263
+ // patch-package writes it. A file keeps its mode but where the patch says
264
+ // otherwise. A symlink, which pnpm never installs, is none to patch. A path
265
+ // it creates or renames to is one macOS and Windows take as written (pathClaims).
266
+ export function patchedFiles(files: NpmPackageFile[], patch: PatchedFile[]): NpmPackageFile[] {
267
+ const byPath = new Map(files.map(file => [file.path, file]))
268
+ const encoder = new TextEncoder()
269
+ let claim: ((path: string) => void) | undefined
270
+ for (const file of patch) {
271
+ if (file.created || file.from !== undefined) (claim ??= pathClaims(files.map(each => each.path)))(file.path)
272
+ if (file.created) {
273
+ const first = file.hunks[0]?.parts[0]
274
+ byPath.set(file.path, { path: file.path, bytes: encoder.encode(first ? `${first.lines.join('\n')}${first.unended ? '' : '\n'}` : ''),
275
+ ...file.executable ? { executable: true as const } : {} })
276
+ continue
277
+ }
278
+ const source = file.from ?? file.path
279
+ const was = byPath.get(source)
280
+ if (!was || was.link !== undefined) throw doesNotApply()
281
+ if (file.deleted) { byPath.delete(source); continue }
282
+ let next = was.bytes
283
+ if (file.hunks.length > 0) {
284
+ const text = npmFileText(was.bytes)
285
+ if (text === null) throw doesNotApply()
286
+ next = encoder.encode(applied(text, file.hunks))
287
+ }
288
+ if (file.from !== undefined) {
289
+ if (byPath.has(file.path)) throw doesNotApply()
290
+ byPath.delete(source)
291
+ }
292
+ byPath.set(file.path, { path: file.path, bytes: next, ...(file.executable ?? was.executable) ? { executable: true as const } : {} })
293
+ }
294
+ return [...byPath.values()].toSorted((a, b) => pathOrder(a.path, b.path))
295
+ }
296
+
297
+ // About the bytes a patch read takes: the characters of its paths and of the
298
+ // lines its hunks hold, and the room past them each line takes (LINE_COST)
299
+ // and each file, hunk and part (HUNK_COST), as V8 takes it; so a patch of a
300
+ // few long lines (a minified file's) weighs about its size, and one of many
301
+ // short lines or tiny hunks many times it, as it takes.
302
+ const HUNK_COST = 256, LINE_COST = 40
303
+ const held = (lines: string[]) => lines.reduce((sum, line) => sum + LINE_COST + line.length, HUNK_COST)
304
+ export const patchWeight = (files: PatchedFile[]) => files.reduce((sum, file) => sum + HUNK_COST + file.path.length + (file.from?.length ?? 0)
305
+ + file.hunks.reduce((bytes, hunk) => bytes + HUNK_COST + hunk.parts.reduce((parts, part) => parts + held(part.lines), 0), 0), 1)
306
+
307
+ // What is kept of a patch, for good, by its repository and hash (patchKey):
308
+ // where it was read, and its text, which its hash names wherever it is.
309
+ // Kept by its repository too, as only one who reads all of that is given it.
310
+ export interface KeptPatch { commit: string; path: string; text: string }
311
+ export const patchKey = (repoId: number, hash: string) => `${repoId}\0${hash}`
312
+
313
+ // Patches read lately, with where each was read, by their keys, as many as
314
+ // MAX_KEPT_PATCHES of the bytes they take (patchWeight); and the path each
315
+ // found or kept is at (`located`): '' by its key and a commit for one not
316
+ // found there, lest each telling look again, none for one not looked for;
317
+ // and '' by its repository's key and a commit whose patches were all kept.
318
+ const MAX_KEPT_PATCHES = 64 * 1024 * 1024
319
+ export interface ReadPatch { source: PatchSource; files: PatchedFile[] }
320
+ const patches: Lru<ReadPatch> = lru(MAX_KEPT_PATCHES, read => patchWeight(read.files))
321
+ const located: Lru<string> = lru(100_000)
322
+
323
+ // The patch `patch` names, and where it was read (`source`): as kept by its
324
+ // repository and hash, in this instance, else beyond it (`kept`, held to its
325
+ // hash again), wherever the request says it is; else read of repository
326
+ // `fullName` with `token` at the commit and path it names, held to its
327
+ // hash, and kept for good; `asked` told where GitHub was. Its file missing
328
+ // there, or other than its hash says, or past MAX_PATCH_BYTES, fails, as
329
+ // does one that isn't read as git writes a diff (parsePatch).
330
+ export async function readPatch(fullName: string, token: string, patch: NpmPatch, kept: KeptStore<KeptPatch>, asked?: GithubAsked): Promise<ReadPatch> {
331
+ const key = patchKey(patch.repoId, patch.hash)
332
+ const known = patches.get(key)
333
+ if (known) return known
334
+ let stored = (await kept.read(key))?.value
335
+ if (typeof stored?.text !== 'string' || !isPatchOf(stored.text, patch.hash)) {
336
+ if (asked) asked.github = true
337
+ const text = await repositoryFile(fullName, token, patch.path, patch.commit)
338
+ if (text === null) throw new NpmPackageError(404, 'patch-not-found')
339
+ if (Buffer.byteLength(text) > MAX_PATCH_BYTES) throw new NpmPackageError(413, 'patch-too-large')
340
+ if (!isPatchOf(text, patch.hash)) throw new NpmPackageError(409, 'patch-mismatch')
341
+ stored = { commit: patch.commit, path: patch.path, text }
342
+ await kept.write(key, stored, Date.now())
343
+ }
344
+ const read = { source: { repoId: patch.repoId, commit: stored.commit, path: stored.path }, files: parsePatch(stored.text) }
345
+ patches.set(key, read)
346
+ return read
347
+ }
348
+
349
+ // The patch `hash` names as kept, of the first of repositories `repoIds`
350
+ // that keeps it, in this instance, else beyond it (`kept`, held to its hash
351
+ // again), GitHub asked for none of it; null where none does.
352
+ export async function keptPatch(repoIds: number[], hash: string, kept: KeptStore<KeptPatch>): Promise<ReadPatch | null> {
353
+ const keys = repoIds.map(repoId => patchKey(repoId, hash))
354
+ const known = keys.map(key => patches.get(key)).find(Boolean)
355
+ if (known) return known
356
+ const stored = keys.length > 0 ? await kept.readMany(keys) : new Map()
357
+ for (const [at, key] of keys.entries()) {
358
+ const patch = stored.get(key)?.value
359
+ if (typeof patch?.text !== 'string' || !isPatchOf(patch.text, hash)) continue
360
+ const read = { source: { repoId: repoIds[at]!, commit: patch.commit, path: patch.path }, files: parsePatch(patch.text) }
361
+ patches.set(key, read)
362
+ return read
363
+ }
364
+ return null
365
+ }
366
+
367
+ // The patch `patch` names by its hash at a commit of its repository, its
368
+ // file unnamed: as kept by its repository and hash (keptPatch); else among
369
+ // the patches of the commit's files (`listed` lists them, with their bytes;
370
+ // null where its repository isn't looked in), each `.patch` file in a
371
+ // `patches` directory beside a pnpm lockfile or a stasis.config.json, where
372
+ // pnpm patch-commit writes them, as many as MAX_FOUND, read of repository
373
+ // `fullName` with `token` and each kept for good by its own hash, so a
374
+ // commit is looked in once; `asked` told where GitHub was. One none of them
375
+ // is fails as not found.
376
+ export async function foundPatch(fullName: string, token: string, patch: Omit<NpmPatch, 'path'>, kept: KeptStore<KeptPatch>,
377
+ listed: () => Promise<{ files: string[]; sizes: number[] } | null>, asked?: GithubAsked): Promise<ReadPatch> {
378
+ const ofIt = () => keptPatch([patch.repoId], patch.hash, kept), searched = `${patchKey(patch.repoId, '')}\0${patch.commit}`
379
+ let found = await ofIt()
380
+ const tree = found || located.get(searched) !== undefined ? null : await listed()
381
+ if (tree) {
382
+ if (asked) asked.github = true
383
+ const dirOf = (path: string) => path.slice(0, path.lastIndexOf('/') + 1)
384
+ const beside = new Set(tree.files.filter(path => lockfileFormat(path) === 'pnpm' || isStasisConfig(path)).map(path => `${dirOf(path)}patches/`))
385
+ const paths = tree.files.filter((path, at) => path.endsWith('.patch') && beside.has(dirOf(path)) && (tree.sizes[at] ?? 0) <= MAX_PATCH_BYTES)
386
+ await eachOf(paths.slice(0, MAX_FOUND), FIND_AT_ONCE, path => patchFileAt(fullName, token, path, patch.commit)
387
+ .then(text => text === null ? undefined : kept.write(patchKey(patch.repoId, hashOfPatch(text)), { commit: patch.commit, path, text }, Date.now())))
388
+ located.set(searched, '')
389
+ found = await ofIt()
390
+ }
391
+ if (!found) throw new NpmPackageError(404, 'patch-not-found')
392
+ return found
393
+ }
394
+
395
+ // The files a pnpm-workspace.yaml (`workspace`, its text, null for none)
396
+ // names its patches by, as pnpm 11 and later read their patchedDependencies
397
+ // there alone, by a version or a package; none where its reader refuses it.
398
+ function patchedBy(workspace: string | null): Record<string, unknown> {
399
+ let settings: unknown
400
+ try { settings = workspace === null ? null : parseYaml(workspace, { workflow: true }) } catch (err) {
401
+ if (!(err instanceof YamlError)) throw err
402
+ }
403
+ const patched = plainObject(settings) ? settings['patchedDependencies'] : null
404
+ return plainObject(patched) ? patched : {}
405
+ }
406
+
407
+ // A version pnpm patches by a patch named by a sha256, with its lockfile's
408
+ // directory: one its lockfile names by its hash alone (pnpm 11's and later),
409
+ // which wants its file found; and, `keepNamed`, one whose file it names.
410
+ type Patched = LockedPackage & { patchHash: string; patchDir: string; version: string }
411
+ const patchedBy256 = (pkg: LockedPackage, keepNamed = false): pkg is Patched => (pkg.patchPath === undefined || keepNamed) && pkg.patchDir !== undefined
412
+ && pkg.version !== null && isPatchHash(pkg.patchHash)
413
+
414
+ // `told`, each version of its that pnpm patches by a patch its lockfile names
415
+ // by its hash alone with its patch's file (`patchPath`), as a lockfile naming
416
+ // one tells it: as kept by its repository and hash, else the file the
417
+ // pnpm-workspace.yaml beside its lockfile names of it (patchedBy: its
418
+ // version's, else its package's) at `told.head`, held to its hash and kept
419
+ // for good, so each is found once, as many an answer as MAX_FOUND; one not
420
+ // found left with none. With `keepNamed`, as a default branch's are told,
421
+ // each patch whose file a lockfile names is read there and kept as well, so
422
+ // that a link naming it by its hash alone finds it later (keptPatch).
423
+ // `asked` told where GitHub was. A file GitHub has no text of, or past
424
+ // MAX_PATCH_BYTES, is none; any other failure of GitHub's is the whole
425
+ // answer's, as a lockfile's is.
426
+ export async function withPatchFiles<T extends PullDependencies>(told: T, repoId: number, fullName: string, token: string, kept: KeptStore<KeptPatch>,
427
+ asked?: GithubAsked, { keepNamed = false } = {}): Promise<T> {
428
+ const wanted = new Map<string, Patched>()
429
+ for (const dir of told.lockfiles) {
430
+ for (const pkg of 'error' in dir ? [] : [...dir.added, ...dir.locked]) if (patchedBy256(pkg, keepNamed)) wanted.set(patchKey(repoId, pkg.patchHash), pkg)
431
+ }
432
+ if (wanted.size === 0) return told
433
+ const at = (key: string) => located.get(key) ?? located.get(`${key}\0${told.head}`)
434
+ const unknown = [...wanted.keys()].filter(key => at(key) === undefined)
435
+ for (const [key, { value }] of unknown.length > 0 ? await kept.readMany(unknown) : []) if (typeof value?.path === 'string') located.set(key, value.path)
436
+ const files = new Map<string, Promise<string | null>>(), read = (path: string) => files.get(path) ?? files.set(path, patchFileAt(fullName, token, path, told.head)).get(path)!
437
+ const workspaces = new Map<string, Promise<Record<string, unknown>>>()
438
+ const namedIn = (dir: string) => workspaces.get(dir) ?? workspaces.set(dir, read(pathFrom(dir, 'pnpm-workspace.yaml')!).then(patchedBy)).get(dir)!
439
+ await eachOf(unknown.filter(key => at(key) === undefined).slice(0, MAX_FOUND), FIND_AT_ONCE, async key => {
440
+ const pkg = wanted.get(key)!
441
+ if (asked) asked.github = true
442
+ const patched = pkg.patchPath === undefined ? await namedIn(pkg.patchDir) : {}
443
+ const file = pkg.patchPath ?? patched[`${pkg.name}@${pkg.version}`] ?? patched[pkg.name]
444
+ const path = typeof file === 'string' ? pkg.patchPath ?? pathFrom(pkg.patchDir, file) : null
445
+ const text = path === null ? null : await read(path)
446
+ if (path === null || text === null || !isPatchOf(text, pkg.patchHash)) { located.set(`${key}\0${told.head}`, ''); return }
447
+ await kept.write(key, { commit: told.head, path, text }, Date.now())
448
+ located.set(key, path)
449
+ })
450
+ const named = <P extends LockedPackage>(pkg: P): P => {
451
+ const patchPath = patchedBy256(pkg) && at(patchKey(repoId, pkg.patchHash))
452
+ return patchPath ? { ...pkg, patchPath } : pkg
453
+ }
454
+ return { ...told, lockfiles: told.lockfiles.map(dir => 'error' in dir ? dir : { ...dir, added: dir.added.map(named), locked: dir.locked.map(named) }) }
455
+ }
@@ -0,0 +1,127 @@
1
+ // npm's provenance for a public version (npm-packages.ts npmManifest marks
2
+ // one that has it): the SLSA statement npm's registry keeps beside it,
3
+ // saying where the version was built: from which repository and commit, by
4
+ // which workflow, on which builder, in which run, with its entry in
5
+ // Sigstore's transparency log. Only a statement naming this version's
6
+ // tarball (its name, version and sha512 digest) is read; its signature isn't
7
+ // checked here, as npm checks it when the version is published. npm is asked
8
+ // without the server's token, and only about a version it answers for
9
+ // without one (http.ts), each answer kept as npm-insights.ts keeps its own.
10
+ import { Buffer } from 'node:buffer'
11
+ import { SHA } from './github-values.ts'
12
+ import { kept } from './kept.ts'
13
+ import { plainObject } from './npm-manifest.ts'
14
+ import { NPM_REGISTRY, askUpstreamJson } from './npm-packages.ts'
15
+
16
+ const ATTESTATIONS_API = `${NPM_REGISTRY}/-/npm/v1/attestations`
17
+ const ATTESTATIONS_BYTES = 1024 * 1024
18
+ // SLSA's v1 statement, as npm writes it now, and v0.2, as it first did.
19
+ const SLSA = /^https:\/\/slsa\.dev\/provenance\/v(?:1|0\.2)$/u
20
+ const GITHUB_REPOSITORY = /^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)$/u
21
+
22
+ // Where a version was built: its source `repository` (an https URL) and
23
+ // `commit`, the `workflow` file and the `ref` it ran on, the `builder` and
24
+ // the `run` (an https URL), its transparency log entry (`logIndex`), and
25
+ // whose runner built it (`runner`: `github-hosted`, `gitlab-hosted` or
26
+ // `self-hosted`, as its signing certificate says); each null where they
27
+ // don't say.
28
+ export interface NpmProvenance {
29
+ repository: string; commit: string | null; workflow: string | null; ref: string | null
30
+ builder: string | null; run: string | null; logIndex: number | null; runner: string | null
31
+ }
32
+
33
+ const text = (value: unknown) => typeof value === 'string' && value !== '' && value.length <= 2048 ? value : null
34
+ const https = (value: unknown) => {
35
+ const url = text(value)
36
+ try { return url && new URL(url).protocol === 'https:' ? url : null } catch { return null }
37
+ }
38
+ // `git+https://github.com/org/repo@refs/heads/main` → the repository and
39
+ // ref; GitLab's names no ref (`git+https://gitlab.com/group/project`).
40
+ function sourceOf(uri: unknown) {
41
+ const match = /^git\+(https:\/\/[^@\s]+?)(?:\.git)?(?:@(.+))?$/u.exec(text(uri) ?? '')
42
+ return match ? { repository: https(match[1]), ref: match[2] ?? null } : { repository: null, ref: null }
43
+ }
44
+ // What `keys` lead to in `value`, through objects and arrays.
45
+ const field = (value: unknown, ...keys: string[]): unknown =>
46
+ keys.reduce<unknown>((at, key) => plainObject(at) || Array.isArray(at) ? (at as Record<string, unknown>)[key] : undefined, value)
47
+ // The list they lead to, none where it is none.
48
+ const listAt = (value: unknown, ...keys: string[]): unknown[] => {
49
+ const list = field(value, ...keys)
50
+ return Array.isArray(list) ? list : []
51
+ }
52
+
53
+ // What a statement says of the build, as v1 or v0.2 says it; null where it
54
+ // names no source repository.
55
+ function readStatement(predicateType: string, predicate: unknown): NpmProvenance | null {
56
+ if (predicateType.endsWith('v1')) {
57
+ const workflow = field(predicate, 'buildDefinition', 'externalParameters', 'workflow')
58
+ const source = field(predicate, 'buildDefinition', 'resolvedDependencies', '0')
59
+ const repository = https(field(workflow, 'repository')) ?? sourceOf(field(source, 'uri')).repository
60
+ if (!repository) return null
61
+ const commit = text(field(source, 'digest', 'gitCommit'))
62
+ return {
63
+ repository, commit: commit && SHA.test(commit) ? commit : null, workflow: text(field(workflow, 'path')),
64
+ ref: text(field(workflow, 'ref')) ?? sourceOf(field(source, 'uri')).ref, builder: https(field(predicate, 'runDetails', 'builder', 'id')),
65
+ run: https(field(predicate, 'runDetails', 'metadata', 'invocationId')), logIndex: null, runner: null,
66
+ }
67
+ }
68
+ const config = field(predicate, 'invocation', 'configSource')
69
+ const { repository, ref } = sourceOf(field(config, 'uri'))
70
+ if (!repository) return null
71
+ const commit = text(field(config, 'digest', 'sha1'))
72
+ // Its run: GitLab's job URL, or GitHub's as `<run id>-<attempt>`.
73
+ const invocation = field(predicate, 'metadata', 'buildInvocationId')
74
+ const run = /^(\d+)-(\d+)$/u.exec(text(invocation) ?? '')
75
+ const github = GITHUB_REPOSITORY.exec(repository)?.[1]
76
+ return {
77
+ repository, commit: commit && SHA.test(commit) ? commit : null, workflow: text(field(config, 'entryPoint')), ref,
78
+ builder: https(field(predicate, 'builder', 'id')),
79
+ run: https(invocation) ?? (run && github ? `https://github.com/${github}/actions/runs/${run[1]}/attempts/${run[2]}` : null), logIndex: null, runner: null,
80
+ }
81
+ }
82
+
83
+ // Fulcio's Runner Environment extension (1.3.6.1.4.1.57264.1.11) in the
84
+ // certificate that signed it: its OID, then its value, a short UTF8String
85
+ // in an OCTET STRING, as the CI's token gave it. A builder's id doesn't
86
+ // tell GitLab's own runners from a project's.
87
+ const RUNNER_ENVIRONMENT = Buffer.from('060a2b0601040183bf30010b', 'hex')
88
+ function runnerOf(bundle: unknown): string | null {
89
+ const raw = field(bundle, 'verificationMaterial', 'certificate', 'rawBytes') ?? field(bundle, 'verificationMaterial', 'x509CertificateChain', 'certificates', '0', 'rawBytes')
90
+ if (typeof raw !== 'string') return null
91
+ const der = Buffer.from(raw, 'base64')
92
+ const at = der.indexOf(RUNNER_ENVIRONMENT) + RUNNER_ENVIRONMENT.length
93
+ if (at < RUNNER_ENVIRONMENT.length || der[at] !== 0x04 || der[at + 2] !== 0x0c || der[at + 1] !== der[at + 3]! + 2) return null
94
+ return text(der.subarray(at + 4, at + 4 + der[at + 3]!).toString('utf8'))
95
+ }
96
+
97
+ async function askProvenance(name: string, version: string, integrity: string): Promise<NpmProvenance | null> {
98
+ const json = await askUpstreamJson(`${ATTESTATIONS_API}/${name.replace('/', '%2f')}@${encodeURIComponent(version)}`,
99
+ { headers: { accept: 'application/json' }, limit: ATTESTATIONS_BYTES })
100
+ if (json === null) return null
101
+ const slsa = listAt(json, 'attestations').find(item => SLSA.test(text(field(item, 'predicateType')) ?? ''))
102
+ if (!slsa) return null
103
+ // The statement, whatever its length (the answer is bounded as a whole),
104
+ // unlike the fields read out of it.
105
+ const payload = field(slsa, 'bundle', 'dsseEnvelope', 'payload')
106
+ let statement: unknown
107
+ try { statement = JSON.parse(Buffer.from(typeof payload === 'string' ? payload : '', 'base64').toString('utf8')) } catch { return null }
108
+ // Only one naming this version's tarball: its purl, and its digest as the
109
+ // version's integrity has it.
110
+ const purl = `pkg:npm/${name.replace(/^@/u, '%40')}@${version}`
111
+ const digest = /^sha512-(.+)$/u.exec(integrity)?.[1]
112
+ if (!digest || !listAt(statement, 'subject').some(subject => field(subject, 'name') === purl && field(subject, 'digest', 'sha512') === Buffer.from(digest, 'base64').toString('hex'))) return null
113
+ const provenance = readStatement(text(field(slsa, 'predicateType'))!, field(statement, 'predicate'))
114
+ const logIndex = Number(field(slsa, 'bundle', 'verificationMaterial', 'tlogEntries', '0', 'logIndex'))
115
+ return provenance && { ...provenance, logIndex: Number.isSafeInteger(logIndex) && logIndex >= 0 ? logIndex : null, runner: runnerOf(field(slsa, 'bundle')) }
116
+ }
117
+
118
+ const provenances = kept<NpmProvenance | null>(1000)
119
+
120
+ // npm's provenance for a version of a public package, its tarball's
121
+ // `integrity` as the registry has it; null where npm keeps none for it.
122
+ export function npmProvenance(name: string, version: string, integrity: string): Promise<NpmProvenance | null> {
123
+ return provenances(`${name}@${version}`, () => askProvenance(name, version, integrity))
124
+ }
125
+
126
+ // One kept, asking for nothing; undefined where none is.
127
+ export const keptNpmProvenance = (name: string, version: string) => provenances.peek(`${name}@${version}`)