@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,317 @@
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`), read of a repository at a
4
+ // commit, and held to the hash the lockfile names it by, as pnpm hashes it,
5
+ // a sha256 in hex from pnpm 10 and an md5 in base32 before, of its text with
6
+ // its CRLFs read as LFs; and applied to the version's files as pnpm applies
7
+ // it as it installs it (patch-package's applyPatch, which pnpm 9, 10 and 11
8
+ // bundle): each file it deletes, creates, renames or changes, a change's
9
+ // hunks each found in the file as it was, where its header says, else as
10
+ // many as FUZZ lines either side, its lines the same but for the space they
11
+ // end in, and those it keeps kept as the file has them. A patch of a file's
12
+ // bytes (git's binary patch), or of a file outside the package, isn't read,
13
+ // and one that doesn't apply fails as a whole; what a patch changes of a
14
+ // file's mode is left out, as the files it reads have none.
15
+ import { Buffer } from 'node:buffer'
16
+ import { createHash } from 'node:crypto'
17
+ import { isPatchHash, isPatchPath } from '../common/managed/npm-packages.js'
18
+ import { SHA } from './github-values.ts'
19
+ import { type Lru, lru } from './lru.ts'
20
+ import { NpmPackageError, type NpmPackageFile, npmFileText, pathOrder } from './npm-packages.ts'
21
+ import { type GithubAsked, repositoryFile } from './pull-dependencies.ts'
22
+
23
+ // Where a patch is read: its file in a repository (by its id) at a commit,
24
+ // from the repository's root; and the patch, by its hash besides.
25
+ export interface PatchSource { repoId: number; commit: string; path: string }
26
+ export interface NpmPatch extends PatchSource { hash: string }
27
+
28
+ // The most a patch's file may hold, and how many lines either side of where a
29
+ // hunk says its lines are they are looked for.
30
+ const MAX_PATCH_BYTES = 8 * 1024 * 1024
31
+ const FUZZ = 20
32
+
33
+
34
+ // The patch a request names, by its hash (`hash`), its repository's id
35
+ // (`repoId`, a number or its digits), the commit and its file's path; null
36
+ // where it names none of where it is, and 'invalid' where it names one
37
+ // otherwise.
38
+ export function requestedPatch({ hash, repoId, commit, path }: { hash: unknown; repoId: unknown; commit: unknown; path: unknown }): NpmPatch | null | 'invalid' {
39
+ if ([repoId, commit, path].every(field => field == null)) return null
40
+ const id = typeof repoId === 'string' && /^[1-9]\d{0,15}$/u.test(repoId) ? Number(repoId) : repoId
41
+ if (!isPatchHash(hash) || !Number.isSafeInteger(id) || (id as number) <= 0 || typeof commit !== 'string' || !SHA.test(commit)
42
+ || !isPatchPath(path)) return 'invalid'
43
+ return { hash, repoId: id as number, commit, path }
44
+ }
45
+
46
+ // RFC 4648's base32 of `bytes`, in lowercase and unpadded, as pnpm 9 spells
47
+ // an md5.
48
+ const BASE32 = 'abcdefghijklmnopqrstuvwxyz234567'
49
+ function base32(bytes: Uint8Array) {
50
+ let bits = 0, spelled = '', value = 0
51
+ for (const byte of bytes) {
52
+ value = ((value << 8) | byte) & 0xfff
53
+ bits += 8
54
+ for (; bits >= 5; bits -= 5) spelled += BASE32[(value >>> (bits - 5)) & 31]
55
+ }
56
+ return bits > 0 ? spelled + BASE32[(value << (5 - bits)) & 31] : spelled
57
+ }
58
+
59
+ // Whether `text` is the patch `hash` names: of its text with its CRLFs as
60
+ // LFs, as pnpm reads it, or as it is.
61
+ export function isPatchOf(text: string, hash: string): boolean {
62
+ return [...new Set([text.replaceAll('\r\n', '\n'), text])].some(read => hash.length === 64
63
+ ? createHash('sha256').update(read).digest('hex') === hash : base32(createHash('md5').update(read).digest()) === hash)
64
+ }
65
+
66
+ // A change a patch makes to a file at `path` of the package: deleting it,
67
+ // creating it, renaming it from another (`from`), and its hunks, as
68
+ // patch-package reads them: where its header says its lines are (`at`, the
69
+ // first's index, as it reads `-0`, the first line), how many it finds
70
+ // (`length`), and its lines, each without its LF, in runs of a kind
71
+ // (`parts`): those it keeps, removes or adds, the last of a side told where
72
+ // the file has no LF after it (`unended`).
73
+ export interface HunkPart { kind: 'context' | 'deletion' | 'insertion'; lines: string[]; unended?: true }
74
+ export interface PatchHunk { at: number; length: number; parts: HunkPart[] }
75
+ export interface PatchedFile { path: string; from?: string; deleted?: true; created?: true; hunks: PatchHunk[] }
76
+
77
+ const unreadable = () => new NpmPackageError(422, 'patch-unreadable')
78
+
79
+ // A path as git writes it, unquoted where quoted (as C writes a string, its
80
+ // bytes past ASCII in octal); null where it is quoted otherwise.
81
+ const ESCAPES: Record<string, number> = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 }
82
+ function unquoted(path: string): string | null {
83
+ if (!path.startsWith('"')) return path
84
+ const bytes: number[] = []
85
+ for (let at = 1; at < path.length; at++) {
86
+ const char = path[at]!
87
+ if (char === '"') return at === path.length - 1 ? new TextDecoder().decode(Uint8Array.from(bytes)) : null
88
+ if (char !== '\\') { bytes.push(...Buffer.from(char)); continue }
89
+ const next = path[++at] ?? ''
90
+ const octal = /^[0-3][0-7]{2}/u.exec(path.slice(at))?.[0]
91
+ if (octal) { bytes.push(Number.parseInt(octal, 8)); at += 2 }
92
+ else if (next in ESCAPES) bytes.push(ESCAPES[next]!)
93
+ else return null
94
+ }
95
+ return null
96
+ }
97
+
98
+ // A side's path in the package, as a `---` or `+++` line names it after its
99
+ // prefix (`a/` or `b/`), git's tab after one with a space in it left out;
100
+ // null for none (`/dev/null`).
101
+ function sidePath(named: string, prefix: string): string | null {
102
+ const path = unquoted(named.endsWith('\t') ? named.slice(0, -1) : named)
103
+ if (path === '/dev/null') return null
104
+ if (path === null || !path.startsWith(prefix)) throw unreadable()
105
+ return path.slice(prefix.length)
106
+ }
107
+
108
+ // The paths a `diff --git` line names, where they are the same, as git
109
+ // writes them for a file neither renamed nor copied: `a/<path> b/<path>`.
110
+ function gitPath(named: string): string | null {
111
+ if (named.startsWith('"')) {
112
+ const quoted = /^("(?:[^"\\]|\\.)*") ("(?:[^"\\]|\\.)*")$/u.exec(named)
113
+ const [a, b] = quoted ? [unquoted(quoted[1]!), unquoted(quoted[2]!)] : []
114
+ return a?.startsWith('a/') && b?.startsWith('b/') && a.slice(2) === b.slice(2) ? a.slice(2) : null
115
+ }
116
+ const length = (named.length - 5) / 2
117
+ const path = named.slice(2, 2 + length)
118
+ return Number.isInteger(length) && named.startsWith('a/') && named.slice(2 + length) === ` b/${path}` ? path : null
119
+ }
120
+
121
+ // The hunk whose `@@` line is at `at` of `lines`, those before `end` read,
122
+ // and the line after it, as patch-package reads it: a line of its own
123
+ // kind, else of those it keeps where it is empty, or a CR alone.
124
+ function readHunk(lines: string[], at: number, end: number): { hunk: PatchHunk; next: number } {
125
+ const range = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/u.exec(lines[at++]!)
126
+ if (!range) throw unreadable()
127
+ let news = Number(range[4] ?? 1), olds = Number(range[2] ?? 1)
128
+ const hunk: PatchHunk = { at: Math.max(Number(range[1]), 1) - 1, length: olds, parts: [] }
129
+ while (olds > 0 || news > 0) {
130
+ // A line its count reads past those read isn't one.
131
+ if (at >= end) throw unreadable()
132
+ const line = lines[at++]!
133
+ const kind = line === '' || line === '\r' || line[0] === ' ' ? 'context' : line[0] === '-' ? 'deletion' : line[0] === '+' ? 'insertion' : null
134
+ if (!kind) throw unreadable()
135
+ const last = hunk.parts.at(-1)
136
+ const part = last?.kind === kind ? last : hunk.parts[hunk.parts.push({ kind, lines: [] }) - 1]!
137
+ part.lines.push(line.slice(1))
138
+ if (kind !== 'insertion') olds--
139
+ if (kind !== 'deletion') news--
140
+ if (olds < 0 || news < 0) throw unreadable()
141
+ // The line before it the last of its side, with no LF after it.
142
+ if (lines[at]?.startsWith('\\')) {
143
+ if (!lines[at++]!.startsWith('\')) throw unreadable()
144
+ part.unended = true
145
+ }
146
+ }
147
+ return { hunk, next: at }
148
+ }
149
+
150
+ // A patch's files as git's diff writes them, as pnpm writes a patch: a file's
151
+ // `diff --git` line, its headers, the paths its sides have, and its hunks;
152
+ // what comes before the first file, or between one file and the next, left
153
+ // out. One whose own lines end in CRLFs, as an editor or git's autocrlf
154
+ // leaves one, is read as patch-package reads it: its headers but their CRs,
155
+ // its hunks' lines with them. Throws for one it can't read, or of bytes.
156
+ export function parsePatch(patch: string): PatchedFile[] {
157
+ const lines = patch.split('\n')
158
+ // The lines read: those but the empty one past the patch's last ending.
159
+ const end = lines.length - (patch.endsWith('\n') ? 1 : 0)
160
+ // A header's line but its CR.
161
+ const headerAt = (at: number) => lines[at]?.replace(/\r$/u, '') ?? ''
162
+ const files: PatchedFile[] = []
163
+ for (let at = 0; at < lines.length;) {
164
+ const head = headerAt(at++)
165
+ if (!head.startsWith('diff --git ')) continue
166
+ let created = false, deleted = false, from: string | null = null, to: string | null = null
167
+ let sides: [string | null, string | null] | null = null
168
+ for (; at < lines.length && !/^(?:diff --git |@@ |--- )/u.test(lines[at]!); at++) {
169
+ const header = headerAt(at)
170
+ if (header === 'GIT binary patch' || header.startsWith('Binary files ')) throw new NpmPackageError(422, 'patch-unsupported')
171
+ if (header.startsWith('copy from ') || header.startsWith('copy to ')) throw new NpmPackageError(422, 'patch-unsupported')
172
+ if (header.startsWith('deleted file mode ')) deleted = true
173
+ else if (header.startsWith('new file mode ')) created = true
174
+ else if (header.startsWith('rename from ')) from = unquoted(header.slice('rename from '.length))
175
+ else if (header.startsWith('rename to ')) to = unquoted(header.slice('rename to '.length))
176
+ }
177
+ if (lines[at]?.startsWith('--- ')) {
178
+ if (!lines[at + 1]?.startsWith('+++ ')) throw unreadable()
179
+ sides = [sidePath(headerAt(at).slice(4), 'a/'), sidePath(headerAt(at + 1).slice(4), 'b/')]
180
+ at += 2
181
+ }
182
+ const named = gitPath(head.slice('diff --git '.length))
183
+ const after = to ?? (sides ? sides[1] : named), before = from ?? (sides ? sides[0] : named)
184
+ if ((from === null) !== (to === null) || (deleted && created)) throw unreadable()
185
+ const path = deleted ? before : after
186
+ if (path == null || (!created && before == null) || (!deleted && after == null) || ![before, after].every(side => side == null || isPatchPath(side))
187
+ || (from === null && !deleted && !created && before !== after)) throw unreadable()
188
+ const hunks: PatchHunk[] = []
189
+ while (lines[at]?.startsWith('@@ ')) {
190
+ const { hunk, next } = readHunk(lines, at, end)
191
+ hunks.push(hunk)
192
+ at = next
193
+ }
194
+ files.push({ path, ...from !== null && to !== null ? { from: before! } : {}, ...deleted ? { deleted: true as const } : {},
195
+ ...created ? { created: true as const } : {}, hunks: deleted ? [] : hunks })
196
+ }
197
+ return files
198
+ }
199
+
200
+ const doesNotApply = () => new NpmPackageError(422, 'patch-does-not-apply')
201
+
202
+ // A change a hunk makes to a file's lines (`lines`, split at its LFs): those
203
+ // at `splice` that it removes (`remove`) and adds in their place (`insert`),
204
+ // or an empty last line it adds or removes, its LF after the last.
205
+ type LineChange = { splice: number; remove: number; insert: string[] } | 'push' | 'pop'
206
+
207
+ // The changes `hunk` makes where its lines are at `at` of `lines`, as
208
+ // patch-package works them out (evaluateHunk): those it finds the same but
209
+ // for the space they end in, as it compares them; else null.
210
+ function changesAt(hunk: PatchHunk, lines: string[], at: number): LineChange[] | null {
211
+ if (at < 0 || lines.length - at < hunk.length) return null
212
+ const changes: LineChange[] = []
213
+ for (const part of hunk.parts) {
214
+ if (part.kind === 'insertion') {
215
+ changes.push({ splice: at, remove: 0, insert: part.lines })
216
+ if (part.unended) changes.push('pop')
217
+ continue
218
+ }
219
+ for (const line of part.lines) if (lines[at++]!.trimEnd() !== line.trimEnd()) return null
220
+ if (part.kind === 'deletion') {
221
+ changes.push({ splice: at - part.lines.length, remove: part.lines.length, insert: [] })
222
+ if (part.unended) changes.push('push')
223
+ }
224
+ }
225
+ return changes
226
+ }
227
+
228
+ // `text` with `hunks` applied as patch-package applies them (applyPatch):
229
+ // each one's lines found in the text as it was, where its header says, else
230
+ // as near as FUZZ lines either side, the nearer first, and the earlier of
231
+ // two as near; then its changes made in turn, past the lines those before
232
+ // added or removed.
233
+ function applied(text: string, hunks: PatchHunk[]): string {
234
+ const lines = text.split('\n')
235
+ const changes = hunks.flatMap(hunk => {
236
+ for (let offset = 0; Math.abs(offset) <= FUZZ; offset = offset < 0 ? -offset : -offset - 1) {
237
+ const found = changesAt(hunk, lines, hunk.at + offset)
238
+ if (found) return found
239
+ }
240
+ throw doesNotApply()
241
+ })
242
+ let shift = 0
243
+ for (const change of changes) {
244
+ if (change === 'push') lines.push('')
245
+ else if (change === 'pop') lines.pop()
246
+ else {
247
+ lines.splice(change.splice + shift, change.remove, ...change.insert)
248
+ shift += change.insert.length - change.remove
249
+ }
250
+ }
251
+ return lines.join('\n')
252
+ }
253
+
254
+ // A version's `files` with `patch` applied, in the order of their paths, as
255
+ // its tarball's are read; a file it changes the text of must be text. One it
256
+ // creates holds its first hunk's first lines, in place of any there, as
257
+ // patch-package writes it.
258
+ export function patchedFiles(files: NpmPackageFile[], patch: PatchedFile[]): NpmPackageFile[] {
259
+ const byPath = new Map(files.map(file => [file.path, file.bytes]))
260
+ const encoder = new TextEncoder()
261
+ for (const file of patch) {
262
+ if (file.created) {
263
+ const first = file.hunks[0]?.parts[0]
264
+ byPath.set(file.path, encoder.encode(first ? `${first.lines.join('\n')}${first.unended ? '' : '\n'}` : ''))
265
+ continue
266
+ }
267
+ const source = file.from ?? file.path
268
+ const bytes = byPath.get(source)
269
+ if (!bytes) throw doesNotApply()
270
+ if (file.deleted) { byPath.delete(source); continue }
271
+ let next = bytes
272
+ if (file.hunks.length > 0) {
273
+ const text = npmFileText(bytes)
274
+ if (text === null) throw doesNotApply()
275
+ next = encoder.encode(applied(text, file.hunks))
276
+ }
277
+ if (file.from !== undefined) {
278
+ if (byPath.has(file.path)) throw doesNotApply()
279
+ byPath.delete(source)
280
+ }
281
+ byPath.set(file.path, next)
282
+ }
283
+ return [...byPath].map(([path, bytes]) => ({ path, bytes })).toSorted((a, b) => pathOrder(a.path, b.path))
284
+ }
285
+
286
+ // About the bytes a patch read takes: the characters of its paths and of the
287
+ // lines its hunks hold, and the room past them each line takes (LINE_COST)
288
+ // and each file, hunk and part (HUNK_COST), as V8 takes it; so a patch of a
289
+ // few long lines (a minified file's) weighs about its size, and one of many
290
+ // short lines or tiny hunks many times it, as it takes.
291
+ const HUNK_COST = 256, LINE_COST = 40
292
+ const held = (lines: string[]) => lines.reduce((sum, line) => sum + LINE_COST + line.length, HUNK_COST)
293
+ export const patchWeight = (files: PatchedFile[]) => files.reduce((sum, file) => sum + HUNK_COST + file.path.length + (file.from?.length ?? 0)
294
+ + file.hunks.reduce((bytes, hunk) => bytes + HUNK_COST + hunk.parts.reduce((parts, part) => parts + held(part.lines), 0), 0), 1)
295
+
296
+ // Patches read lately, by their source and hash, as what a commit holds never
297
+ // changes: as many as MAX_KEPT_PATCHES of the bytes they take (patchWeight).
298
+ const MAX_KEPT_PATCHES = 64 * 1024 * 1024
299
+ const patches: Lru<PatchedFile[]> = lru(MAX_KEPT_PATCHES, patchWeight)
300
+
301
+ // The patch `patch` names, read as kept, else of repository `fullName` with
302
+ // `token`, held to its hash and read (parsePatch), and kept; `asked` told
303
+ // where GitHub was. Its file missing there, or other than its hash says, or
304
+ // past MAX_PATCH_BYTES, fails.
305
+ export async function readPatch(fullName: string, token: string, patch: NpmPatch, asked?: GithubAsked): Promise<PatchedFile[]> {
306
+ const key = `${patch.repoId}\0${patch.commit}\0${patch.path}\0${patch.hash}`
307
+ const known = patches.get(key)
308
+ if (known) return known
309
+ if (asked) asked.github = true
310
+ const text = await repositoryFile(fullName, token, patch.path, patch.commit)
311
+ if (text === null) throw new NpmPackageError(404, 'patch-not-found')
312
+ if (Buffer.byteLength(text) > MAX_PATCH_BYTES) throw new NpmPackageError(413, 'patch-too-large')
313
+ if (!isPatchOf(text, patch.hash)) throw new NpmPackageError(409, 'patch-mismatch')
314
+ const files = parsePatch(text)
315
+ patches.set(key, files)
316
+ return files
317
+ }
@@ -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}`)