@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,159 @@
1
+ // The lines a version of a package changes against another, or against none,
2
+ // its whole package's (GET /api/npm/delta), as a list of versions wanting
3
+ // reviews tells them beside each: added and removed (`additions`,
4
+ // `deletions`), as git's --numstat counts them, of their text files, a
5
+ // renamed one diffed with what it was; and, where some of the files changed
6
+ // are declaration files @preventive/compare's compareTrees proves changed in
7
+ // types alone (`typeOnly`, proveTypeOnly: types and comments alone erased,
8
+ // the runtime they leave as it was, an added one's empty or a single bare
9
+ // `export {}`), those of the rest (`typeless`), what a reviewer may pass by
10
+ // leaving those out; and whether a binary file, which they count none of,
11
+ // was added, removed or changed (`binary`), one moved as it was not. Worked
12
+ // out in a worker, off the event loop, as many at once per process as
13
+ // MAX_ACTIVE, both sides' files read together only once their turn has come,
14
+ // those waiting past MAX_WAITING refused, each waiting a minute at most and
15
+ // counting in a minute at most; one asked again meanwhile sharing the
16
+ // first's; and kept by both sides' integrities, in this instance and beyond
17
+ // it (`kept`), what a version holds never changing. Access is the caller's
18
+ // to check.
19
+ import { createHash } from 'node:crypto'
20
+ import type { KeptStore } from './npm-kept.ts'
21
+ import { type Lru, lru } from './lru.ts'
22
+ import { NpmPackageError, type NpmPackageFile, npmFileText } from './npm-packages.ts'
23
+ import { workerTurns } from './worker-turns.ts'
24
+
25
+ export interface NpmDelta { additions: number; deletions: number; typeless: { additions: number; deletions: number } | null; binary: boolean }
26
+
27
+ const MAX_ACTIVE = 2
28
+ const MAX_WAITING = 64
29
+ const DELTA_TIMEOUT_MS = 60_000
30
+ // The text the two sides may hold together, past which none is counted.
31
+ const MAX_TEXT_LENGTH = 64 * 1024 * 1024
32
+
33
+ const deltas: Lru<NpmDelta> = lru(20_000)
34
+ const working = new Map<string, Promise<NpmDelta>>()
35
+ const workers = workerTurns({ what: 'package delta', active: MAX_ACTIVE, waiting: MAX_WAITING, error: NpmPackageError,
36
+ busy: 'delta-busy', timeout: 'delta-timeout', failed: 'delta-failed' })
37
+
38
+ const lines = (told: unknown): told is { additions: number; deletions: number } => typeof told === 'object' && told !== null
39
+ && Number.isSafeInteger((told as { additions?: unknown }).additions) && Number.isSafeInteger((told as { deletions?: unknown }).deletions)
40
+ // A delta as kept, none where it isn't one, or was kept before it told of
41
+ // binary files.
42
+ function deltaOf(told: unknown): NpmDelta | null {
43
+ if (!lines(told)) return null
44
+ const { typeless, binary } = told as { typeless?: unknown; binary?: unknown }
45
+ return (typeless === null || lines(typeless)) && typeof binary === 'boolean' ? { additions: told.additions, deletions: told.deletions, typeless, binary } : null
46
+ }
47
+
48
+ type Counted = { additions: number; deletions: number; typeAdditions: number; typeDeletions: number; typeFiles: number }
49
+ const isCounted = (told: unknown): told is Counted => typeof told === 'object' && told !== null
50
+ && ['additions', 'deletions', 'typeAdditions', 'typeDeletions', 'typeFiles'].every(key => Number.isSafeInteger((told as Record<string, unknown>)[key]))
51
+
52
+ // What the worker counts of `base` against `other`, each its text files' paths and texts.
53
+ function counted(base: [string, string][], other: [string, string][], deadline: number): Promise<Counted> {
54
+ return workers.run(new URL('./npm-delta-worker.js', import.meta.url), {
55
+ workerData: { base, other }, execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1536 },
56
+ }, told => (isCounted(told) ? told : null), deadline)
57
+ }
58
+
59
+ // A side's text files, by path, how long their texts are, and its other,
60
+ // binary, files.
61
+ function texts(files: NpmPackageFile[] | null) {
62
+ let length = 0
63
+ const binaries: NpmPackageFile[] = []
64
+ const read = (files ?? []).flatMap(file => {
65
+ const text = npmFileText(file.bytes)
66
+ if (text === null) { binaries.push(file); return [] }
67
+ length += text.length
68
+ return [[file.path, text] as [string, string]]
69
+ })
70
+ return { read, length, binaries }
71
+ }
72
+
73
+ const same = (a: Uint8Array, b: Uint8Array) => Buffer.from(a.buffer, a.byteOffset, a.byteLength).equals(b)
74
+ const digest = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('base64')
75
+
76
+ // Whether `news`, a side's binary files, differ from `olds`, the other's:
77
+ // one added, removed or changed, one moved where it is the same as one that
78
+ // was elsewhere not, matched by their digests, each file looked at once.
79
+ function binaryChanged(olds: NpmPackageFile[], news: NpmPackageFile[]): boolean {
80
+ if (olds.length !== news.length) return true
81
+ const left = new Map(olds.map(({ path, bytes }) => [path, bytes]))
82
+ const moved: Uint8Array[] = []
83
+ for (const { path, bytes } of news) {
84
+ const was = left.get(path)
85
+ if (was && same(was, bytes)) left.delete(path)
86
+ else moved.push(bytes)
87
+ }
88
+ // Those not where they were, by their digests, as many of each as there are.
89
+ const unmoved = new Map<string, number>()
90
+ for (const bytes of left.values()) {
91
+ const key = digest(bytes)
92
+ unmoved.set(key, (unmoved.get(key) ?? 0) + 1)
93
+ }
94
+ return moved.some(bytes => {
95
+ const key = digest(bytes)
96
+ const count = unmoved.get(key) ?? 0
97
+ if (count === 0) return true
98
+ unmoved.set(key, count - 1)
99
+ return false
100
+ })
101
+ }
102
+
103
+ type Side = { integrity: string; files: () => Promise<NpmPackageFile[]> }
104
+ // A delta's key: the integrities of the version it is against, or none, and
105
+ // of the version.
106
+ export const deltaKey = (base: string | null, other: string) => `${base ?? '(empty)'}\0${other}`
107
+
108
+ // The delta of `other` (its integrity, and how to read its files) against
109
+ // `base`, or none, as held, else shared with one asked before it, else
110
+ // looked for where it is kept, else worked out and kept: shared from before
111
+ // it is looked for, lest those asked together each look, find none, and work
112
+ // it out.
113
+ export function npmDelta(base: Side | null, other: Side, kept: KeptStore<NpmDelta> | null = null): Promise<NpmDelta> {
114
+ const key = deltaKey(base?.integrity ?? null, other.integrity)
115
+ const known = deltas.get(key)
116
+ if (known) return Promise.resolve(known)
117
+ const shared = working.get(key)
118
+ if (shared) return shared
119
+ const work = worked(key, base, other, kept).finally(() => working.delete(key))
120
+ working.set(key, work)
121
+ return work
122
+ }
123
+
124
+ // The deltas of those of `sides` (each the integrities of the version it is
125
+ // against, or none, and of the version) held or kept, by their keys
126
+ // (npmDelta's), in one read of `kept` for those not held: none worked out.
127
+ export async function keptNpmDeltas(sides: [string | null, string][], kept: KeptStore<NpmDelta>): Promise<Map<string, NpmDelta>> {
128
+ const keys = [...new Set(sides.map(([base, other]) => deltaKey(base, other)))]
129
+ const found = new Map(keys.flatMap(key => { const known = deltas.get(key); return known ? [[key, known] as const] : [] }))
130
+ const unheld = keys.filter(key => !found.has(key))
131
+ for (const [key, row] of unheld.length > 0 ? await kept.readMany(unheld) : []) {
132
+ const known = deltaOf(row.value)
133
+ if (!known) continue
134
+ deltas.set(key, known)
135
+ found.set(key, known)
136
+ }
137
+ return found
138
+ }
139
+
140
+ // As kept, else its turn awaited, then both sides' files read, counted and kept.
141
+ async function worked(key: string, base: Side | null, other: Side, kept: KeptStore<NpmDelta> | null): Promise<NpmDelta> {
142
+ const known = deltaOf((await kept?.read(key))?.value)
143
+ if (known) { deltas.set(key, known); return known }
144
+ const delta = await workers.inTurn(Date.now() + DELTA_TIMEOUT_MS, async (): Promise<NpmDelta> => {
145
+ // Its turn held till both sides are read, or have failed.
146
+ const [baseRead, otherRead] = await Promise.allSettled([base ? base.files() : Promise.resolve(null), other.files()])
147
+ if (baseRead.status === 'rejected') throw baseRead.reason
148
+ if (otherRead.status === 'rejected') throw otherRead.reason
149
+ const [olds, news] = [texts(baseRead.value), texts(otherRead.value)]
150
+ if (olds.length + news.length > MAX_TEXT_LENGTH) throw new NpmPackageError(413, 'package-too-large')
151
+ const binary = binaryChanged(olds.binaries, news.binaries)
152
+ const told = await counted(olds.read, news.read, Date.now() + DELTA_TIMEOUT_MS)
153
+ return { additions: told.additions, deletions: told.deletions,
154
+ typeless: told.typeFiles > 0 ? { additions: told.additions - told.typeAdditions, deletions: told.deletions - told.typeDeletions } : null, binary }
155
+ })
156
+ deltas.set(key, delta)
157
+ await kept?.write(key, delta, Date.now())
158
+ return delta
159
+ }
@@ -0,0 +1,455 @@
1
+ // Figures and advisories for the npm package viewer's Overview, beside a
2
+ // version's files (npm-packages.ts, npm-loads.ts): the package's downloads
3
+ // over the last year, from npm's public downloads API; its GitHub
4
+ // repository's stars, forks and open issues; and its advisories across every
5
+ // published version, as `npm audit` has them and as its repository publishes
6
+ // them on GitHub, asked as bundle advisories ask (bundle-advisories.ts); and
7
+ // Socket's scores and alerts for a version. All of it is public: npm is asked
8
+ // without the server's token, Socket only about a version npm answers for
9
+ // without one (http.ts), and a repository's figures, tags and advisories are
10
+ // asked for, and kept, only where GitHub says it is public. Each
11
+ // answer is kept for an hour, a failure not at all; the reader's access to
12
+ // the package is checked on every request before any of it is answered
13
+ // (http.ts handleNpm).
14
+ import type { Advisory, CacheStore } from '@preventive/upstream/advisories.js'
15
+ import { type Client, HttpError, createClient } from '@preventive/upstream/github.js'
16
+ import { ADVISORIES_TIMEOUT_MS, fetchBundleAdvisories } from './bundle-advisories.ts'
17
+ import { isExactVersion } from '@preventive/upstream/semver.js'
18
+ import { USER_AGENT, repoApi } from './github-requests.ts'
19
+ import { kept } from './kept.ts'
20
+ import { type NpmProvenance, keptNpmProvenance } from './npm-provenance.ts'
21
+ import { plainObject } from './npm-manifest.ts'
22
+ import { NpmPackageError, askUpstreamJson, readLimited } from './npm-packages.ts'
23
+
24
+ const DOWNLOADS_API = 'https://api.npmjs.org/downloads/range'
25
+ // What npm's range API may answer for each package asked: a year of days is
26
+ // some 16 KiB.
27
+ const DOWNLOADS_BYTES = 64 * 1024
28
+ // Socket's answer for a package version, by its purl, as Socket Firewall
29
+ // asks it: no key needed. Its scores are cut to two decimals; its badge's,
30
+ // the supply chain score, is rounded (askSocketBadge).
31
+ const SOCKET_API = 'https://firewall-api.socket.dev/purl'
32
+ const SOCKET_BADGE = 'https://badge.socket.dev/npm/package'
33
+ const BADGE_BYTES = 16 * 1024
34
+ const API_TIMEOUT_MS = 30_000
35
+ const API_BYTES = 1024 * 1024
36
+ const DAY_MS = 24 * 60 * 60_000
37
+ const SEVERITY_RANK: Record<string, number> = { critical: 0, high: 1, moderate: 2, low: 3 }
38
+ const rank = (severity: string | undefined) => SEVERITY_RANK[severity ?? ''] ?? 4
39
+
40
+ const count = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0 ? value as number : 0
41
+ const isDay = (value: unknown): value is string => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/u.test(value) && !Number.isNaN(Date.parse(value))
42
+
43
+ // A package's downloads, one count a day from `start` to `end` (UTC dates),
44
+ // none for a day npm leaves out; null where npm has none for it.
45
+ export interface NpmDownloads { start: string; end: string; days: number[] }
46
+
47
+ const isoDay = (time: number) => new Date(time).toISOString().slice(0, 10)
48
+
49
+ // Its last year, as npm counts it (to the last day it has counted), from
50
+ // the first of the month that year starts in, so that month is whole too.
51
+ async function askDownloads(name: string): Promise<NpmDownloads | null> {
52
+ const year = await askDownloadRange('last-year', name)
53
+ const start = new Date(year?.start ?? 0)
54
+ if (year === null || start.getUTCDate() === 1) return year
55
+ const first = Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), 1)
56
+ const before = await askDownloadRange(`${isoDay(first)}:${isoDay(start.getTime() - DAY_MS)}`, name).catch(() => null)
57
+ return before?.start === isoDay(first) && before.days.length === (start.getTime() - first) / DAY_MS
58
+ ? { start: before.start, end: year.end, days: [...before.days, ...year.days] } : year
59
+ }
60
+
61
+ // npm's downloads of `name` over `range`: null where npm has none.
62
+ async function askDownloadRange(range: string, name: string): Promise<NpmDownloads | null> {
63
+ const json = await askUpstreamJson(`${DOWNLOADS_API}/${range}/${name.replace('/', '%2f')}`, { headers: { accept: 'application/json' }, limit: DOWNLOADS_BYTES })
64
+ return json === null ? null : readDownloads(json)
65
+ }
66
+
67
+ // One package's downloads as npm's range API gives them.
68
+ function readDownloads(json: unknown): NpmDownloads {
69
+ if (!plainObject(json) || !isDay(json['start']) || !isDay(json['end']) || !Array.isArray(json['downloads'])) throw new NpmPackageError(502, 'upstream-invalid')
70
+ const start = Date.parse(json['start'])
71
+ const length = (Date.parse(json['end']) - start) / DAY_MS + 1
72
+ if (!Number.isSafeInteger(length) || length < 1 || length > 400) throw new NpmPackageError(502, 'upstream-invalid')
73
+ const days = Array.from({ length }, () => 0)
74
+ for (const row of json['downloads']) {
75
+ if (!plainObject(row) || !isDay(row['day'])) continue
76
+ const at = (Date.parse(row['day']) - start) / DAY_MS
77
+ if (Number.isSafeInteger(at) && at >= 0 && at < length) days[at] = count(row['downloads'])
78
+ }
79
+ return { start: json['start'], end: json['end'], days }
80
+ }
81
+
82
+ const downloads = kept<NpmDownloads | null>(500)
83
+ // The repository each package's latest version names (owner/name, null where
84
+ // it names none), as its figures were first asked with within the hour: what
85
+ // npmKnown finds them by.
86
+ const latestRepos = kept<string | null>(500)
87
+
88
+ export const npmLatestRepo = (name: string, repo: string | null): void => void latestRepos(name, () => Promise.resolve(repo))
89
+
90
+ export function npmDownloads(name: string): Promise<NpmDownloads | null> {
91
+ return downloads(name, () => askDownloads(name))
92
+ }
93
+
94
+ const SOCKET_SCORES = ['overall', 'supplyChain', 'vulnerability', 'quality', 'maintenance', 'license'] as const
95
+ const SOCKET_SEVERITY_RANK: Record<string, number> = { critical: 0, high: 1, middle: 2, low: 3 }
96
+ const SOCKET_ALERTS = 50
97
+ const SOCKET_NOTE_CHARS = 4000
98
+
99
+ // Socket's report on a version: its scores, each 0 to 1 (null where Socket
100
+ // gave none), and the alerts it raises, such as malware, most severe first,
101
+ // each with the file it was found in, by its path in the package (the
102
+ // tarball's root left out, as the package's files have it), where it names
103
+ // one, and Socket's note on it.
104
+ export interface NpmSocketAlert { type: string; severity: string; category: string | null; file: string | null; note: string | null }
105
+ export interface NpmSocketReport { scores: Record<typeof SOCKET_SCORES[number], number> | null; alerts: NpmSocketAlert[] }
106
+
107
+ const text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null
108
+
109
+ // The supply chain score, out of 100, that the version's badge shows; null
110
+ // where it shows none, and undefined where it can't be had, as while Socket
111
+ // limits how often it's asked.
112
+ async function askSocketBadge(name: string, version: string): Promise<number | null | undefined> {
113
+ try {
114
+ const res = await fetch(`${SOCKET_BADGE}/${name}/${encodeURIComponent(version)}`,
115
+ { headers: { accept: 'image/svg+xml' }, redirect: 'error', signal: AbortSignal.timeout(API_TIMEOUT_MS) })
116
+ if (!res.ok) { await res.body?.cancel(); return res.status === 429 || res.status >= 500 ? undefined : null }
117
+ const shown = /<title>Socket: (\d{1,3})<\/title>/u.exec((await readLimited(res, BADGE_BYTES)).toString('utf8'))
118
+ return shown ? Number(shown[1]) : null
119
+ } catch { return undefined }
120
+ }
121
+
122
+ // Scores the badge couldn't round: Socket's own, a point low at most, their
123
+ // report answered but not kept, so the next view asks again.
124
+ const unbadged = new WeakSet<object>()
125
+
126
+ async function askSocket(name: string, version: string): Promise<NpmSocketReport | null> {
127
+ const badge = askSocketBadge(name, version)
128
+ // One line, as one purl was asked.
129
+ const json = await askUpstreamJson(`${SOCKET_API}/${encodeURIComponent(`pkg:npm/${name}@${version}`)}`,
130
+ { headers: { accept: 'application/x-ndjson' }, limit: API_BYTES }, body => JSON.parse(body.split('\n', 1)[0]!))
131
+ if (json === null) return null
132
+ if (!plainObject(json) || json['version'] !== version || [json['namespace'], json['name']].filter(Boolean).join('/') !== name) throw new NpmPackageError(502, 'upstream-invalid')
133
+ // A version Socket hasn't seen is answered with a made-up id and nothing else.
134
+ if (String(json['id']).startsWith('synthetic:')) return null
135
+ const score = json['score']
136
+ const scores = plainObject(score) && SOCKET_SCORES.every(key => typeof score[key] === 'number' && score[key] >= 0 && score[key] <= 1)
137
+ ? Object.fromEntries(SOCKET_SCORES.map(key => [key, score[key]])) as NpmSocketReport['scores'] : null
138
+ // The supply chain score as the badge rounds it, at most one more than the
139
+ // score cut to two decimals; lower where the badge is, as when the score
140
+ // has fallen since.
141
+ const shown = await badge
142
+ if (scores && typeof shown === 'number') scores.supplyChain = Math.min(Math.round(scores.supplyChain * 100) + 1, shown) / 100
143
+ else if (scores && shown === undefined) unbadged.add(scores)
144
+ const alerts = (Array.isArray(json['alerts']) ? json['alerts'] : [])
145
+ .filter((alert): alert is Record<string, unknown> => plainObject(alert) && text(alert['type']) !== null && typeof alert['severity'] === 'string' && alert['severity'] in SOCKET_SEVERITY_RANK)
146
+ .slice(0, SOCKET_ALERTS)
147
+ .map(alert => ({
148
+ type: alert['type'] as string, severity: alert['severity'] as string, category: text(alert['category']),
149
+ file: text(text(alert['file'])?.replace(/^[^/]*\//u, '')),
150
+ note: text(plainObject(alert['props']) ? alert['props']['note'] : null)?.slice(0, SOCKET_NOTE_CHARS) ?? null,
151
+ }))
152
+ .toSorted((a, b) => SOCKET_SEVERITY_RANK[a.severity]! - SOCKET_SEVERITY_RANK[b.severity]!)
153
+ return scores === null && alerts.length === 0 ? null : { scores, alerts }
154
+ }
155
+
156
+ const socketReports = kept<NpmSocketReport | null>(1000, report => !report?.scores || !unbadged.has(report.scores))
157
+
158
+ // Socket's report on a version of a public package; null where Socket has
159
+ // none. Its name goes to Socket: never ask it about a private one.
160
+ export function npmSocketReport(name: string, version: string): Promise<NpmSocketReport | null> {
161
+ return socketReports(`${name}@${version}`, () => askSocket(name, version))
162
+ }
163
+
164
+ // A public repository's figures: GitHub's `openIssues` takes in its open pull
165
+ // requests, which `openPulls` counts on their own, null where GitHub didn't
166
+ // say.
167
+ export interface NpmGithubStats {
168
+ repo: string; stars: number; forks: number; openIssues: number; openPulls: number | null; archived: boolean; pushedAt: string | null
169
+ }
170
+
171
+ // How many pull requests a repository has open: the last page of their list,
172
+ // one a page, as its Link header names it, or the one page's length.
173
+ async function countOpenPulls(repo: string, token: string | null): Promise<number | null> {
174
+ let res: Response
175
+ try {
176
+ res = await fetch(`${repoApi(repo)}/pulls?state=open&per_page=1`, {
177
+ headers: { accept: 'application/vnd.github+json', 'user-agent': USER_AGENT, ...token && { authorization: `Bearer ${token}` } },
178
+ redirect: 'error', signal: AbortSignal.timeout(API_TIMEOUT_MS),
179
+ })
180
+ } catch { return null }
181
+ if (!res.ok) { await res.body?.cancel(); return null }
182
+ const last = /[?&]page=(\d+)>;\s*rel="last"/u.exec(res.headers.get('link') ?? '')?.[1]
183
+ if (last !== undefined) { await res.body?.cancel(); return Number(last) }
184
+ try {
185
+ const json = JSON.parse((await readLimited(res, API_BYTES)).toString('utf8')) as unknown
186
+ return Array.isArray(json) ? json.length : null
187
+ } catch { return null }
188
+ }
189
+
190
+ // GitHub has no repository to show: none by that name, or a redirect upstream
191
+ // won't follow, anywhere but to the repository by its id, or a second.
192
+ const NONE = new Set([301, 302, 307, 308, 404])
193
+
194
+ // What GitHub answers for `repo`, or where it was renamed or transferred, for
195
+ // the repository it is now (its `full_name`), where it says it is public,
196
+ // with the token it was asked with: `token`, or none where that is revoked.
197
+ // Upstream follows GitHub's redirect for such a repository to it by its id
198
+ // (`followRedirect`), once, with the same token. Null where GitHub has no such
199
+ // repository to show, or it is not public; anything else fails, to be asked
200
+ // again next time. Public is `visibility: 'public'`, as github-app.ts
201
+ // requires: an internal repository answers `private: false`.
202
+ async function publicRepo(repo: string, token: string | null): Promise<{ json: Record<string, unknown> & { full_name: string }; auth: string | null } | null> {
203
+ const ask = (auth: string | null) => createClient({ token: auth, userAgent: USER_AGENT }).getRepo({ repo, followRedirect: true }) as Promise<unknown>
204
+ let auth = token, json: unknown
205
+ try { json = await ask(token) }
206
+ catch (error) {
207
+ if (!(error instanceof HttpError) || !(error.status === 401 || NONE.has(error.status))) throw error
208
+ if (error.status !== 401 || token === null) return null
209
+ auth = null
210
+ try { json = await ask(null) }
211
+ catch (retry) { if (retry instanceof HttpError && NONE.has(retry.status)) return null; throw retry }
212
+ }
213
+ if (!plainObject(json) || json['private'] !== false || json['visibility'] !== 'public' || typeof json['full_name'] !== 'string') return null
214
+ return { json: json as Record<string, unknown> & { full_name: string }, auth }
215
+ }
216
+
217
+ async function askGithub(repo: string, token: string | null): Promise<NpmGithubStats | null> {
218
+ const found = await publicRepo(repo, token)
219
+ if (found === null) return null
220
+ const { json, auth } = found
221
+ return {
222
+ repo: json['full_name'], stars: count(json['stargazers_count']), forks: count(json['forks_count']), openIssues: count(json['open_issues_count']),
223
+ openPulls: await countOpenPulls(json['full_name'], auth),
224
+ archived: json['archived'] === true, pushedAt: typeof json['pushed_at'] === 'string' ? json['pushed_at'] : null,
225
+ }
226
+ }
227
+
228
+ const repositories = kept<NpmGithubStats | null>(1000)
229
+
230
+ // `repo` as a package's manifest names it (owner/name); `githubToken` the
231
+ // reader's own, where they have one, for GitHub's rate limits, never for what
232
+ // it shows, asked for only where the figures aren't kept.
233
+ export function npmGithubStats(repo: string, githubToken: () => Promise<string | null>): Promise<NpmGithubStats | null> {
234
+ return repositories(repo.toLowerCase(), async () => askGithub(repo, await githubToken()))
235
+ }
236
+
237
+ const GITHUB_GRAPHQL = 'https://api.github.com/graphql'
238
+ // A ref's target is a commit, or for an annotated tag a tag object, which may
239
+ // itself name another tag before the commit.
240
+ const TAGS_QUERY = `query($owner: String!, $name: String!, $query: String!) {
241
+ repository(owner: $owner, name: $name) {
242
+ visibility
243
+ refs(refPrefix: "refs/tags/", query: $query, first: 100) {
244
+ nodes { name target { __typename oid ... on Tag { target { __typename oid ... on Tag { target { __typename oid } } } } } }
245
+ }
246
+ }
247
+ }`
248
+
249
+ function taggedCommit(target: unknown): unknown {
250
+ let at = target
251
+ for (let depth = 0; depth < 3 && plainObject(at) && at['__typename'] === 'Tag'; depth++) at = at['target']
252
+ return plainObject(at) && at['__typename'] === 'Commit' ? at['oid'] : null
253
+ }
254
+
255
+ async function askTags(repo: string, sha: string, version: string, token: string): Promise<string[]> {
256
+ const [owner, name] = repo.split('/')
257
+ const json = await askUpstreamJson(GITHUB_GRAPHQL, {
258
+ method: 'POST', limit: API_BYTES, absent: [],
259
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': USER_AGENT },
260
+ body: JSON.stringify({ query: TAGS_QUERY, variables: { owner, name, query: version } }),
261
+ })
262
+ const data = plainObject(json) ? json['data'] : null
263
+ const repository = plainObject(data) ? data['repository'] : null
264
+ // A repository gone, or not public (private, or internal to an enterprise),
265
+ // has none to show anyone.
266
+ if (!plainObject(repository) || repository['visibility'] !== 'PUBLIC') return []
267
+ const refs = repository['refs']
268
+ const nodes = plainObject(refs) && Array.isArray(refs['nodes']) ? refs['nodes'] as unknown[] : []
269
+ return nodes.filter((node): node is { name: string; target: unknown } => plainObject(node) && typeof node['name'] === 'string' && node['name'] !== '')
270
+ .filter(node => taggedCommit(node.target) === sha).map(node => node.name).toSorted()
271
+ }
272
+
273
+ // Null where no token asked: nothing to keep for a reader who has one; kept
274
+ // by the repository, the commit and the version asked.
275
+ const commitTags = kept<string[] | null>(500, tags => tags !== null)
276
+ const tagsKey = (repo: string, sha: string, version: string) => `${repo.toLowerCase()}\0${sha}\0${version}`
277
+
278
+ // The tags of a public repository (owner/name) that point to `sha`, a
279
+ // version's publish commit, among those naming its `version` (`v1.2.3`,
280
+ // `pkg@1.2.3`, …), as GitHub's GraphQL API finds them by name. GraphQL needs
281
+ // a token: the reader's own (`githubToken`, asked for only where the tags
282
+ // aren't kept), where they have one; without, none are asked.
283
+ export async function npmCommitTags(repo: string, sha: string, version: string, githubToken: () => Promise<string | null>): Promise<string[]> {
284
+ return await commitTags(tagsKey(repo, sha, version), async () => {
285
+ const token = await githubToken()
286
+ return token === null ? null : askTags(repo, sha, version, token)
287
+ }) ?? []
288
+ }
289
+
290
+ // An advisory on the package, with the versions it covers as their indexes in
291
+ // the list it was asked with: npm's (`registry`), or one its repository
292
+ // publishes on GitHub before GitHub reviews it into npm's (`repository`); its
293
+ // text (markdown) where its source has one; `malware` where upstream tells it
294
+ // is of malware, any of its rows.
295
+ export interface NpmAdvisory {
296
+ id: string; source: Advisory['source']; ghsa?: string; url?: string; title?: string; severity?: string; cvss?: number; cwe: string[]; range?: string
297
+ details?: string; malware?: true; affected: number[]
298
+ }
299
+
300
+ // `versions` those `affected` indexes; `repository` false where the
301
+ // repository's advisories could not be had (GitHub refusing, its rate limit
302
+ // spent), leaving npm's alone; `keptAt`, where GitHub couldn't give them but
303
+ // their listing was kept before, however long ago, when it was.
304
+ export interface NpmAdvisoryList { versions: string[]; advisories: NpmAdvisory[]; repository: boolean; keptAt?: string }
305
+
306
+ export interface NpmAdvisoryOptions {
307
+ // The reader's GitHub token, and the repository the package names (owner/
308
+ // name, null where it names none), each asked for only where the list is
309
+ // not kept.
310
+ githubToken: () => Promise<string | null>
311
+ repo: () => Promise<string | null>
312
+ // Where repositories' listings are kept, as bundle advisories keep them
313
+ // (upstream-cache.ts auditCache), for as long as `signal` asks; and a
314
+ // repository's as last kept there, however old (lastListing).
315
+ cache: (signal: AbortSignal) => CacheStore | undefined
316
+ lastListing: (repo: string) => Promise<{ at: number; cache: CacheStore } | null>
317
+ debug?: boolean
318
+ }
319
+
320
+ async function askAdvisories(name: string, versions: string[], { githubToken, repo, cache, lastListing, debug = false }: NpmAdvisoryOptions): Promise<NpmAdvisoryList> {
321
+ // Every version upstream takes, as it checks each one it is asked about.
322
+ const asked = versions.filter(version => isExactVersion(version))
323
+ if (asked.length === 0) return { versions, advisories: [], repository: true }
324
+ // Its repository's own advisories are asked for only where GitHub says, now
325
+ // and not from an answer kept, that it is public, and that repository is the
326
+ // one asked, by the name GitHub gives it now where it was renamed or
327
+ // transferred: the list is kept for every reader of the package, and the
328
+ // reader's token could read a private repository's, or a listing of one
329
+ // kept for another reader.
330
+ let github: string | null = null, named: string | null = null, repository = true
331
+ try {
332
+ named = await repo()
333
+ github = named === null ? null : (await publicRepo(named, await githubToken()))?.json.full_name ?? null
334
+ } catch { repository = false }
335
+ // With the advisories `listed` publishes, where it isn't null, GitHub asked
336
+ // with the reader's token or by a client of the caller's.
337
+ const ask = (listed: string | null, store: (signal: AbortSignal) => CacheStore | undefined, client: { githubToken: string | null } | { github: Client }) => {
338
+ const signal = AbortSignal.timeout(ADVISORIES_TIMEOUT_MS)
339
+ const packages = [{ ecosystem: 'npm' as const, name, versions: asked, ...listed !== null && { github: listed } }]
340
+ return fetchBundleAdvisories(packages, signal, { debug, repoAdvisories: listed !== null, details: true, ...client, cache: store(signal) })
341
+ }
342
+ let result = repository ? await ask(github, cache, { githubToken: github === null ? null : await githubToken() }) : null
343
+ // Where GitHub can't say whether it is public, or refuses its listing, its
344
+ // listing as last kept is taken instead, however old (lastListing), as
345
+ // audits take a kept listing for any reader: only public repositories
346
+ // publish advisories (upstream-cache.ts). GitHub is asked nothing for it:
347
+ // upstream asks for a listing only once npm has answered, and where it
348
+ // won't take the kept one, which leaves npm's alone, as where none is kept.
349
+ // An audit failing otherwise is npm's, not asked a third time. Neither list
350
+ // is kept, so GitHub is asked again next time.
351
+ let keptAt: string | undefined
352
+ if (result === null || (result.status !== 200 && github !== null)) {
353
+ const unreached = github ?? named
354
+ const last = unreached === null ? null : await lastListing(unreached)
355
+ let untaken = false
356
+ const offline: Client = { ...createClient({ token: null, userAgent: USER_AGENT }),
357
+ listRepoAdvisories: () => { untaken = true; return Promise.reject(new Error('GitHub can\'t be reached')) } }
358
+ const listed = last && await ask(unreached, () => last.cache, { github: offline })
359
+ if (last && listed?.status === 200) {
360
+ result = listed
361
+ repository = true
362
+ keptAt = new Date(last.at).toISOString()
363
+ } else {
364
+ result = listed && !untaken ? listed : await ask(null, cache, { githubToken: null })
365
+ repository = false
366
+ }
367
+ }
368
+ if (result.status !== 200) throw new NpmPackageError(502, 'upstream-unavailable')
369
+ return { versions, repository, ...keptAt && { keptAt }, advisories: mergedAdvisories(result.body, versions) }
370
+ }
371
+
372
+ // Upstream's advisories as NpmAdvisory tells them, those covering none of
373
+ // `versions` left out, the worst first. npm's registry answers an advisory
374
+ // once a range it covers, and upstream answers the versions OSV's record of
375
+ // it, or its repository, covers beyond npm's under the same id, in a row of
376
+ // their own (as hermes-engine's GHSA-f5x2-xv93-4p23: npm's `<=0.4.3`, OSV's
377
+ // fixed in 0.5.2): here it is one row, the first's (npm's, then OSV's, then
378
+ // the repository's, as upstream orders them) with what it lacks taken from
379
+ // the rest, its ranges joined as semver joins them, the versions and CWEs
380
+ // they cover together, and the worst severity and highest score of them: a
381
+ // version only the repository reports keeps the severity it gives.
382
+ function mergedAdvisories(rows: Advisory[], versions: string[]): NpmAdvisory[] {
383
+ const index = new Map(versions.map((version, i) => [version, i]))
384
+ const merged = new Map<string, NpmAdvisory>()
385
+ for (const row of rows) {
386
+ const affected = row.versions.map(version => index.get(version)).filter(at => at !== undefined)
387
+ const own: NpmAdvisory = {
388
+ id: row.id, source: row.source, ...row.ghsa && { ghsa: row.ghsa }, ...row.url && { url: row.url }, ...row.title && { title: row.title },
389
+ ...row.severity && { severity: row.severity }, ...row.cvss !== undefined && { cvss: row.cvss }, cwe: row.cwe, ...row.range && { range: row.range },
390
+ ...row.details && { details: row.details }, ...row.malware && { malware: true }, affected,
391
+ }
392
+ const known = merged.get(row.id)
393
+ if (!known) {
394
+ merged.set(row.id, own)
395
+ continue
396
+ }
397
+ const range = [known.range, row.range].filter(Boolean).join(' || ')
398
+ const cvss = Math.max(known.cvss ?? -1, row.cvss ?? -1)
399
+ const severity = rank(row.severity) < rank(known.severity) ? row.severity : known.severity
400
+ merged.set(row.id, { ...own, ...known, ...range && { range }, ...severity && { severity }, ...cvss >= 0 && { cvss }, cwe: [...new Set([...known.cwe, ...row.cwe])],
401
+ affected: [...known.affected, ...affected] })
402
+ }
403
+ return [...merged.values()].map(row => ({ ...row, affected: [...new Set(row.affected)].toSorted((a, b) => a - b) })).filter(row => row.affected.length > 0)
404
+ .toSorted((a, b) => rank(a.severity) - rank(b.severity) || a.id.localeCompare(b.id))
405
+ }
406
+
407
+ const ADVISORY_LISTS = 100
408
+ const advisoryLists = kept<NpmAdvisoryList>(ADVISORY_LISTS, list => list.repository && !list.keptAt)
409
+ // What each package's list was last asked by, for npmKnown.
410
+ const advisoryKeys = new Map<string, string>()
411
+
412
+ // The package's advisories, `versions` its published versions as the version
413
+ // list has them; asked again once a version is published, and a list without
414
+ // its repository's, next time.
415
+ export function npmAdvisories(name: string, versions: string[], options: NpmAdvisoryOptions): Promise<NpmAdvisoryList> {
416
+ const key = `${name}\0${versions.length}\0${versions[0] ?? ''}`
417
+ advisoryKeys.delete(name)
418
+ advisoryKeys.set(name, key)
419
+ while (advisoryKeys.size > ADVISORY_LISTS) advisoryKeys.delete(advisoryKeys.keys().next().value!)
420
+ return advisoryLists(key, () => askAdvisories(name, versions, options))
421
+ }
422
+
423
+ // What is kept about a version's package, each part as its own route answers
424
+ // it (http.ts handleNpm), for the version's response to carry: its figures,
425
+ // where those of the repository its latest version names are kept too; its
426
+ // advisories, where kept for a version list that has this version; the tags
427
+ // of its publish commit (`sha`, in `repo`, the repository it names);
428
+ // Socket's report on it; and npm's provenance for it (npm-provenance.ts).
429
+ // Nothing is asked for: what isn't kept is left out, for the viewer to ask
430
+ // for. A private package's name never leaves for Socket, so its report is
431
+ // none, nor is it asked for provenance.
432
+ export interface NpmKnown {
433
+ stats?: { name: string; downloads: NpmDownloads | null; github: NpmGithubStats | null }
434
+ advisories?: { name: string } & NpmAdvisoryList
435
+ tags?: { name: string; version: string; tags: string[] }
436
+ socket?: { name: string; version: string; socket: NpmSocketReport | null }
437
+ provenance?: { name: string; version: string; provenance: NpmProvenance | null }
438
+ }
439
+
440
+ export function npmKnown(name: string, version: string, isPrivate: boolean, repo: string | null, sha: string | null): NpmKnown {
441
+ const known: NpmKnown = {}
442
+ const days = downloads.peek(name), latest = latestRepos.peek(name)
443
+ const github = latest === null ? null : latest === undefined ? undefined : repositories.peek(latest.toLowerCase())
444
+ if (days !== undefined && github !== undefined) known.stats = { name, downloads: days, github }
445
+ const key = advisoryKeys.get(name)
446
+ const list = key === undefined ? undefined : advisoryLists.peek(key)
447
+ if (list?.versions.includes(version)) known.advisories = { name, ...list }
448
+ const tags = repo === null || sha === null ? [] : commitTags.peek(tagsKey(repo, sha, version))
449
+ if (tags) known.tags = { name, version, tags }
450
+ const socket = isPrivate ? null : socketReports.peek(`${name}@${version}`)
451
+ if (socket !== undefined) known.socket = { name, version, socket }
452
+ const provenance = isPrivate ? null : keptNpmProvenance(name, version)
453
+ if (provenance !== undefined) known.provenance = { name, version, provenance }
454
+ return known
455
+ }