@preventive/triage 1.0.0-alpha.9 → 1.0.0-alpha.90

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 (448) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +16 -78
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +6 -0
  13. package/common/bundle-compare-diff.js +378 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-imports.js +20 -0
  20. package/common/bundle-metadata.d.ts +15 -0
  21. package/common/bundle-metadata.js +226 -0
  22. package/common/bundle-pkg-of.d.ts +1 -0
  23. package/common/bundle-pkg-of.js +90 -0
  24. package/common/bundle-reasons.d.ts +6 -0
  25. package/common/bundle-reasons.js +58 -0
  26. package/common/bundle-source-links.d.ts +6 -0
  27. package/common/bundle-source-links.js +216 -0
  28. package/common/bundle-sourcemap.d.ts +10 -0
  29. package/common/bundle-sourcemap.js +100 -0
  30. package/common/bundle-sources.d.ts +10 -0
  31. package/common/bundle-sources.js +374 -0
  32. package/common/bundle-stats.js +41 -0
  33. package/common/bundle-tabs.js +1 -0
  34. package/common/code-language.js +80 -0
  35. package/common/default-scan-models.ts +37 -0
  36. package/common/dependency-reviews.d.ts +19 -0
  37. package/common/dependency-reviews.js +67 -0
  38. package/common/finding-duplicates.js +63 -0
  39. package/common/finding-filters.js +313 -0
  40. package/common/finding-id.js +47 -0
  41. package/common/finding-repo.d.ts +5 -0
  42. package/common/finding-repo.js +67 -0
  43. package/common/github-issue-labels.d.ts +3 -0
  44. package/common/github-issue-labels.js +42 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +15 -0
  48. package/common/line-diff.js +188 -0
  49. package/common/linked-workspace-groups.js +63 -0
  50. package/common/managed/agent-tasks.ts +292 -0
  51. package/common/managed/comments.ts +43 -0
  52. package/common/managed/dependency-routes.js +25 -0
  53. package/common/managed/directory-packages.ts +28 -0
  54. package/common/managed/finding-detail.d.ts +5 -0
  55. package/common/managed/finding-detail.js +75 -0
  56. package/common/managed/finding-values.d.ts +2 -0
  57. package/common/managed/finding-values.js +138 -0
  58. package/common/managed/github-agents.ts +114 -0
  59. package/common/managed/github-logins.ts +49 -0
  60. package/common/managed/lite-name.d.ts +2 -0
  61. package/common/managed/lite-name.js +20 -0
  62. package/common/managed/npm-packages.d.ts +9 -0
  63. package/common/managed/npm-packages.js +63 -0
  64. package/common/managed/permissions.ts +31 -0
  65. package/common/managed/report-content.ts +72 -0
  66. package/common/managed/report-filter.ts +120 -0
  67. package/common/managed/repository-alias.ts +65 -0
  68. package/common/managed/review-view-routes.js +23 -0
  69. package/common/managed/risk-routes.js +30 -0
  70. package/common/managed/roles.ts +48 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +386 -0
  73. package/common/managed/scan-models.ts +6 -0
  74. package/common/managed/stasis-config.ts +7 -0
  75. package/common/managed/team-app.d.ts +19 -0
  76. package/common/managed/team-app.js +129 -0
  77. package/common/managed/team-filters.js +26 -0
  78. package/common/managed/triage.ts +83 -0
  79. package/common/managed/upload-seal.ts +126 -0
  80. package/common/npm-token.d.ts +2 -0
  81. package/common/npm-token.js +14 -0
  82. package/common/pretty-json.js +123 -0
  83. package/common/pretty-kinds.js +20 -0
  84. package/common/pretty-print.d.ts +7 -0
  85. package/common/pretty-print.js +41 -0
  86. package/common/pretty-sourcemap.js +70 -0
  87. package/common/repo-commit.d.ts +4 -0
  88. package/common/repo-commit.js +30 -0
  89. package/common/revalidation-conflicts.js +48 -0
  90. package/common/revalidation-input-groups.js +56 -0
  91. package/common/scan-server.ts +13 -0
  92. package/common/security-links.d.ts +5 -0
  93. package/common/security-links.js +33 -0
  94. package/common/server-info.ts +46 -0
  95. package/common/sourcemap-listing.js +78 -0
  96. package/common/sourcemap-mappings.js +136 -0
  97. package/common/sourcemap-unlist.js +85 -0
  98. package/common/stasis-files.d.ts +5 -0
  99. package/common/stasis-files.js +20 -0
  100. package/common/stasis-tgz.d.ts +6 -0
  101. package/common/stasis-tgz.js +27 -0
  102. package/common/utf8.d.ts +3 -0
  103. package/common/utf8.js +45 -0
  104. package/common/whitespace-insensitive.js +19 -0
  105. package/common/workspace-app.js +91 -0
  106. package/common/workspace-groups.js +176 -0
  107. package/out/activity.js +2 -0
  108. package/out/brotli-fallback.js +3 -3
  109. package/out/chunk-2XUEZHIP.js +28 -0
  110. package/out/chunk-3DOSBILK.js +4 -0
  111. package/out/chunk-55YIWY3H.js +5 -0
  112. package/out/chunk-5AVGKFMR.js +1 -0
  113. package/out/chunk-5PWEAEA5.js +1 -0
  114. package/out/chunk-6VOB5WXX.js +2 -0
  115. package/out/chunk-6Y6PZ2BU.js +9 -0
  116. package/out/chunk-74JZTGTO.js +11 -0
  117. package/out/chunk-7BKKYVWR.js +7 -0
  118. package/out/chunk-7C7DWL7I.js +1 -0
  119. package/out/chunk-7HP2VYIC.js +2 -0
  120. package/out/chunk-7YFJUT2P.js +1 -0
  121. package/out/chunk-A4BBBHQU.js +1 -0
  122. package/out/chunk-B64CTMVU.js +4 -0
  123. package/out/chunk-BEKYZCPX.js +14 -0
  124. package/out/chunk-BZJU5EEV.js +1 -0
  125. package/out/chunk-C4Z6ZBXV.js +10 -0
  126. package/out/chunk-CJVMNJDZ.js +3 -0
  127. package/out/chunk-CU3FPB3P.js +1 -0
  128. package/out/chunk-DEVAORP2.js +1 -0
  129. package/out/chunk-DUASGS2O.js +8 -0
  130. package/out/chunk-EEJA7JBI.js +13 -0
  131. package/out/chunk-ESXA7KID.js +1 -0
  132. package/out/chunk-FSU2PLJL.js +1 -0
  133. package/out/chunk-GO7FT4OD.js +1 -0
  134. package/out/chunk-GX5UXWT4.js +1 -0
  135. package/out/chunk-HGWFRZNC.js +267 -0
  136. package/out/chunk-IYPY47MC.js +1 -0
  137. package/out/chunk-JZAROLQT.js +40 -0
  138. package/out/chunk-K4XJHM2T.js +1 -0
  139. package/out/chunk-KP2XM324.js +6 -0
  140. package/out/chunk-LRWB6QVO.js +1 -0
  141. package/out/chunk-LVSLM7HB.js +1 -0
  142. package/out/chunk-LVW7WWV4.js +1 -0
  143. package/out/chunk-N57OWFKY.js +15 -0
  144. package/out/chunk-NRPC74AM.js +1 -0
  145. package/out/chunk-OOJM4CTU.js +1 -0
  146. package/out/chunk-PKLVXUEI.js +11 -0
  147. package/out/chunk-PLGH63UC.js +2 -0
  148. package/out/chunk-PNHBZGDD.js +1 -0
  149. package/out/chunk-PWFUOLZK.js +17 -0
  150. package/out/chunk-PXK7EU4V.js +1 -0
  151. package/out/chunk-QD3IBSF4.js +7 -0
  152. package/out/chunk-QI66YA4F.js +1 -0
  153. package/out/chunk-QRKFPLA4.js +80 -0
  154. package/out/chunk-R3NZFXVR.js +1 -0
  155. package/out/chunk-R5O6FAW4.js +2 -0
  156. package/out/chunk-RAM3GDAD.js +1 -0
  157. package/out/chunk-RPNO56H2.js +1 -0
  158. package/out/chunk-SMNFBOLO.js +10 -0
  159. package/out/chunk-SSPDMA6D.js +1 -0
  160. package/out/chunk-SZTCJVZJ.js +55 -0
  161. package/out/chunk-SZWPYLPC.js +1 -0
  162. package/out/chunk-TKPNRQNN.js +3 -0
  163. package/out/chunk-TUII34K2.js +1 -0
  164. package/out/chunk-UJP4PQJA.js +1 -0
  165. package/out/chunk-UJSJMXEG.js +1 -0
  166. package/out/chunk-UR4WYMIP.js +1 -0
  167. package/out/chunk-UTYWTUTC.js +1 -0
  168. package/out/chunk-VHEXSGGP.js +1 -0
  169. package/out/chunk-VYYUMYVW.js +9 -0
  170. package/out/chunk-WBK5ZN4K.js +3 -0
  171. package/out/chunk-WCDYSIKG.js +1 -0
  172. package/out/chunk-XM4RLC4A.js +2 -0
  173. package/out/chunk-XRAAYXPR.js +1 -0
  174. package/out/chunk-ZQHLECTI.js +1 -0
  175. package/out/client-managed-import.js +4 -0
  176. package/out/client-managed.js +35 -0
  177. package/out/client-sync.js +11 -17
  178. package/out/compare.js +26 -0
  179. package/out/dialogs.js +40 -0
  180. package/out/github-issue-authorized.html +3 -0
  181. package/out/github-issue-authorized.js +1 -0
  182. package/out/graph.js +19 -5
  183. package/out/index.html +105 -25
  184. package/out/prism.js +14 -10
  185. package/out/scan.js +2 -0
  186. package/out/stasis.svg +20 -0
  187. package/out/terminal.js +367 -39
  188. package/out/view.css +1 -1
  189. package/out/view.js +19 -148
  190. package/package.json +416 -64
  191. package/risk/actions/findings.js +161 -0
  192. package/risk/actions/resolve.js +287 -0
  193. package/risk/actions/scripts/commands.js +182 -0
  194. package/risk/actions/scripts/grade.js +113 -0
  195. package/risk/actions/scripts/packages.js +123 -0
  196. package/risk/actions/scripts/shell.js +169 -0
  197. package/risk/actions/uses.js +94 -0
  198. package/risk/actions/workflow.js +183 -0
  199. package/risk/files/characters.js +354 -0
  200. package/risk/files/hosts.js +206 -0
  201. package/risk/files/readability.js +185 -0
  202. package/risk/files/runs-code.js +568 -0
  203. package/risk/files/script.js +420 -0
  204. package/risk/files/source-map-link.js +43 -0
  205. package/risk/files/stamps.js +47 -0
  206. package/risk/index.d.ts +309 -0
  207. package/risk/index.js +12 -0
  208. package/risk/npm/assess.js +303 -0
  209. package/risk/npm/combined.js +68 -0
  210. package/risk/npm/compare.js +236 -0
  211. package/risk/npm/dependencies.js +172 -0
  212. package/risk/npm/diff.js +79 -0
  213. package/risk/npm/downloads.js +84 -0
  214. package/risk/npm/files.js +445 -0
  215. package/risk/npm/held.js +67 -0
  216. package/risk/npm/install-scripts.js +34 -0
  217. package/risk/npm/malware.js +38 -0
  218. package/risk/npm/manifest.js +65 -0
  219. package/risk/npm/new-dependency.js +60 -0
  220. package/risk/npm/old-version.js +108 -0
  221. package/risk/npm/registry.js +401 -0
  222. package/risk/npm/release.js +85 -0
  223. package/risk/npm/score.js +59 -0
  224. package/risk/npm/specs.js +124 -0
  225. package/risk/npm/tarball.js +169 -0
  226. package/server-common/database-config.ts +16 -0
  227. package/server-common/initialize.ts +18 -0
  228. package/server-common/npm-advisories.ts +101 -0
  229. package/{server → server-common}/origin.ts +5 -5
  230. package/server-common/reap.ts +48 -0
  231. package/server-common/scan-config.ts +19 -0
  232. package/server-common/standalone.ts +29 -0
  233. package/server-common/storage-crypto.ts +182 -0
  234. package/server-common/storage-log.ts +38 -0
  235. package/server-common/vercel-blob.ts +103 -0
  236. package/server-e2e/app.ts +487 -0
  237. package/{server → server-e2e}/bus-receiver.ts +2 -1
  238. package/{server → server-e2e}/cli.js +9 -4
  239. package/{server → server-e2e}/config.ts +52 -42
  240. package/{server → server-e2e}/db-neon.ts +2 -2
  241. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  242. package/{server → server-e2e}/db-stmt.ts +2 -2
  243. package/{server → server-e2e}/db.ts +7 -7
  244. package/{server → server-e2e}/http.ts +44 -13
  245. package/{server → server-e2e}/hub.ts +40 -9
  246. package/server-e2e/index.ts +17 -0
  247. package/server-e2e/lifecycle.ts +95 -0
  248. package/{server → server-e2e}/neon-driver.ts +2 -2
  249. package/{server → server-e2e}/npm-proxy.ts +12 -145
  250. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  251. package/{server → server-e2e}/objstore/blob.ts +1 -1
  252. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  253. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  254. package/{server → server-e2e}/objstore/init.ts +19 -27
  255. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  257. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  258. package/{server → server-e2e}/objstore/rest.ts +3 -3
  259. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  260. package/{server → server-e2e}/objstore/store.ts +7 -7
  261. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  262. package/{server → server-e2e}/pubsub.ts +12 -9
  263. package/{server → server-e2e}/sign.ts +4 -4
  264. package/{server → server-e2e}/sse-server.ts +3 -3
  265. package/{server → server-e2e}/static.ts +18 -17
  266. package/{server → server-e2e}/sync-handlers.ts +56 -30
  267. package/{server → server-e2e}/ws-server.ts +20 -9
  268. package/server-managed/activity.ts +269 -0
  269. package/server-managed/agent-merges.ts +109 -0
  270. package/server-managed/app-agents.ts +23 -0
  271. package/server-managed/avatar-store.ts +21 -0
  272. package/server-managed/blob-store.ts +26 -0
  273. package/server-managed/brotli.ts +10 -0
  274. package/server-managed/bundle-advisories.ts +176 -0
  275. package/server-managed/bundle-advisory-inventory.ts +85 -0
  276. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  277. package/server-managed/bundle-build-diagnostics.js +23 -0
  278. package/server-managed/bundle-build-leases.ts +41 -0
  279. package/server-managed/bundle-build-worker.js +387 -0
  280. package/server-managed/bundle-build.ts +328 -0
  281. package/server-managed/bundle-cache.ts +261 -0
  282. package/server-managed/bundle-catalog.ts +29 -0
  283. package/server-managed/bundle-commits.ts +133 -0
  284. package/server-managed/bundle-dependency-reviews.ts +91 -0
  285. package/server-managed/bundle-store.ts +24 -0
  286. package/server-managed/bundle-summary-cache.ts +139 -0
  287. package/server-managed/bundle-validation.ts +33 -0
  288. package/server-managed/bundle.ts +151 -0
  289. package/server-managed/cache-storage.ts +20 -0
  290. package/server-managed/cli.js +21 -0
  291. package/server-managed/combined.ts +43 -0
  292. package/server-managed/comments.ts +138 -0
  293. package/server-managed/commit-coauthors.ts +105 -0
  294. package/server-managed/commit-lockfiles.ts +78 -0
  295. package/server-managed/comparison.ts +51 -0
  296. package/server-managed/config.ts +163 -0
  297. package/server-managed/content-access.ts +15 -0
  298. package/server-managed/crypto.ts +25 -0
  299. package/server-managed/db-methods.ts +1950 -0
  300. package/server-managed/db-neon.ts +401 -0
  301. package/server-managed/db-schema.ts +271 -0
  302. package/server-managed/db-table-names.ts +22 -0
  303. package/server-managed/db.ts +150 -0
  304. package/server-managed/dependabot-access.ts +85 -0
  305. package/server-managed/dependabot-alerts.ts +197 -0
  306. package/server-managed/dependency-review-comments.ts +158 -0
  307. package/server-managed/dependency-reviews.ts +369 -0
  308. package/server-managed/github-accounts.ts +59 -0
  309. package/server-managed/github-actions.ts +71 -0
  310. package/server-managed/github-app.ts +347 -0
  311. package/server-managed/github-errors.ts +92 -0
  312. package/server-managed/github-graphql.ts +42 -0
  313. package/server-managed/github-issue-links.ts +264 -0
  314. package/server-managed/github-issue-oauth.ts +30 -0
  315. package/server-managed/github-issues.ts +169 -0
  316. package/server-managed/github-link-oauth.ts +56 -0
  317. package/server-managed/github-links.ts +204 -0
  318. package/server-managed/github-metadata.ts +218 -0
  319. package/server-managed/github-oauth.ts +264 -0
  320. package/server-managed/github-pulls.ts +290 -0
  321. package/server-managed/github-requests.ts +181 -0
  322. package/server-managed/github-users.ts +53 -0
  323. package/server-managed/github-values.ts +26 -0
  324. package/server-managed/history-windows.ts +172 -0
  325. package/server-managed/http-response.ts +76 -0
  326. package/server-managed/http.ts +6722 -0
  327. package/server-managed/import-triage.ts +51 -0
  328. package/server-managed/index.ts +204 -0
  329. package/server-managed/kept-briefly.ts +37 -0
  330. package/server-managed/kept.ts +28 -0
  331. package/server-managed/known-listings.ts +112 -0
  332. package/server-managed/link-reports.ts +149 -0
  333. package/server-managed/listed-activity.ts +39 -0
  334. package/server-managed/locked-packages.ts +234 -0
  335. package/server-managed/lockfile-scope.ts +58 -0
  336. package/server-managed/lru.ts +30 -0
  337. package/server-managed/managed-issues.ts +92 -0
  338. package/server-managed/management-catalog.ts +45 -0
  339. package/server-managed/management.ts +116 -0
  340. package/server-managed/npm-delta-worker.js +203 -0
  341. package/server-managed/npm-delta.ts +277 -0
  342. package/server-managed/npm-insights.ts +455 -0
  343. package/server-managed/npm-kept.ts +274 -0
  344. package/server-managed/npm-loads.ts +259 -0
  345. package/server-managed/npm-manifest.ts +117 -0
  346. package/server-managed/npm-packages.ts +477 -0
  347. package/server-managed/npm-patch-paths.ts +86 -0
  348. package/server-managed/npm-patch.ts +457 -0
  349. package/server-managed/npm-provenance.ts +127 -0
  350. package/server-managed/npm-risk.ts +310 -0
  351. package/server-managed/object-storage-disk.ts +147 -0
  352. package/server-managed/object-storage-vercel.ts +71 -0
  353. package/server-managed/object-storage.ts +82 -0
  354. package/server-managed/package-entry-points.ts +127 -0
  355. package/server-managed/pretty-copies.ts +22 -0
  356. package/server-managed/pretty-format.d.ts +4 -0
  357. package/server-managed/pretty-format.js +27 -0
  358. package/server-managed/pretty-print.ts +444 -0
  359. package/server-managed/public-workspace.ts +242 -0
  360. package/server-managed/pull-comment-reviews.ts +161 -0
  361. package/server-managed/pull-dependencies.ts +370 -0
  362. package/server-managed/pull-dependency-reviews.ts +458 -0
  363. package/server-managed/pull-reviews.ts +202 -0
  364. package/server-managed/pulse-walk.ts +164 -0
  365. package/server-managed/queue.ts +54 -0
  366. package/server-managed/release-commits.ts +85 -0
  367. package/server-managed/rename-diff-worker.js +30 -0
  368. package/server-managed/rename-diff.ts +237 -0
  369. package/server-managed/repo-path.ts +21 -0
  370. package/server-managed/report-migration.ts +32 -0
  371. package/server-managed/report-opening.ts +77 -0
  372. package/server-managed/report-query.ts +10 -0
  373. package/server-managed/report-response.ts +16 -0
  374. package/server-managed/report-sources.ts +185 -0
  375. package/server-managed/report-store.ts +77 -0
  376. package/server-managed/repository-actions.ts +220 -0
  377. package/server-managed/repository-agents.ts +422 -0
  378. package/server-managed/repository-aliases.ts +119 -0
  379. package/server-managed/repository-browser.ts +362 -0
  380. package/server-managed/repository-changes.ts +280 -0
  381. package/server-managed/repository-code.ts +222 -0
  382. package/server-managed/repository-dependency-reviews.ts +220 -0
  383. package/server-managed/repository-discovery.ts +83 -0
  384. package/server-managed/repository-history.ts +444 -0
  385. package/server-managed/repository-issues.ts +293 -0
  386. package/server-managed/repository-policy.ts +27 -0
  387. package/server-managed/repository-pulls.ts +207 -0
  388. package/server-managed/repository-pulse.ts +409 -0
  389. package/server-managed/repository-risk-assess.ts +179 -0
  390. package/server-managed/repository-risk-audit.ts +145 -0
  391. package/server-managed/repository-risk-caches.ts +56 -0
  392. package/server-managed/repository-risk-kept.ts +86 -0
  393. package/server-managed/repository-risk-read.ts +296 -0
  394. package/server-managed/repository-risk-stasis.ts +61 -0
  395. package/server-managed/repository-risk-turn.ts +97 -0
  396. package/server-managed/repository-risk.ts +528 -0
  397. package/server-managed/repository-squashes.ts +160 -0
  398. package/server-managed/repository-stamp.ts +41 -0
  399. package/server-managed/request-timing.ts +63 -0
  400. package/server-managed/reviewed-dependencies.ts +170 -0
  401. package/server-managed/revisions.ts +35 -0
  402. package/server-managed/scan-downloads.ts +121 -0
  403. package/server-managed/session.ts +132 -0
  404. package/server-managed/slugs.ts +38 -0
  405. package/server-managed/solidity-entry-points.ts +71 -0
  406. package/server-managed/sql-postgres.ts +34 -0
  407. package/server-managed/sql.ts +107 -0
  408. package/server-managed/stasis-config.ts +147 -0
  409. package/server-managed/stasis-dependencies.ts +280 -0
  410. package/server-managed/static.ts +28 -0
  411. package/server-managed/storage-command.ts +16 -0
  412. package/server-managed/storage-db.ts +183 -0
  413. package/server-managed/storage-encryption.ts +288 -0
  414. package/server-managed/storage-maintenance.ts +259 -0
  415. package/server-managed/storage-payload.ts +121 -0
  416. package/server-managed/storage-stores.ts +91 -0
  417. package/server-managed/storage.ts +82 -0
  418. package/server-managed/team-app-summaries.ts +57 -0
  419. package/server-managed/team-app.ts +162 -0
  420. package/server-managed/team-catalog.ts +7 -0
  421. package/server-managed/team-feed.ts +180 -0
  422. package/server-managed/team-icons.ts +50 -0
  423. package/server-managed/team-npm-scopes.ts +103 -0
  424. package/server-managed/team-progress.ts +77 -0
  425. package/server-managed/team-reports.ts +369 -0
  426. package/server-managed/triage-response.ts +16 -0
  427. package/server-managed/type-only-proof.js +181 -0
  428. package/server-managed/type-only-worker.js +31 -0
  429. package/server-managed/type-only.ts +135 -0
  430. package/server-managed/uploads.ts +106 -0
  431. package/server-managed/upstream-cache.ts +275 -0
  432. package/server-managed/view-as.ts +58 -0
  433. package/server-managed/worker-turns.ts +76 -0
  434. package/server-managed/workspace-shares.ts +170 -0
  435. package/server.ts +70 -0
  436. package/strip-types-loader.js +13 -10
  437. package/server/index.ts +0 -480
  438. package/server/lifecycle.ts +0 -208
  439. /package/{LICENSE → LICENSE-MIT} +0 -0
  440. /package/{server → server-e2e}/auth.ts +0 -0
  441. /package/{server → server-e2e}/config.example.json +0 -0
  442. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  443. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  444. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  445. /package/{server → server-e2e}/peer.ts +0 -0
  446. /package/{server → server-e2e}/sse-session.ts +0 -0
  447. /package/{server → server-e2e}/util.ts +0 -0
  448. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,274 @@
1
+ // What the npm viewer and repository risk scans keep in the database
2
+ // (managed_upstream_cache, upstream-cache.ts), beyond the instance, so that
3
+ // neither asks for it again on every read, nor after a restart or on another
4
+ // instance: public versions' documents, of the fields read of them
5
+ // (npm-manifest.ts npmVersionFields), for a day (readNpmVersion asks npm again
6
+ // then, as a version can be deprecated, its package made private, or itself
7
+ // removed), and when each was published, for a month (npmPublishTimeStore);
8
+ // and, for scans, each package's risk line, for as long as a scan
9
+ // keeps it, and what a scan read of GitHub, for a day, and of npm's
10
+ // advisories, for an hour (repository-risk.ts); and what the code viewer read
11
+ // of a repository's GitHub, its issues, pull requests and agents' work, for a
12
+ // day (http.ts keptAnswer), and its history, a page from a commit at a time,
13
+ // for a month (repository-history.ts historyFrom), as are the files each of
14
+ // its commits changes and holds (repository-changes.ts), its trees as the
15
+ // code viewer reads them (codeTreeStore), the packages a pull request's
16
+ // lockfiles add (pull-dependencies.ts), and the lockfiles a commit lists and
17
+ // each one's packages, as its dependency review reads them
18
+ // (commit-lockfiles.ts); and the commit the code viewer keeps its
19
+ // directories at, for as long as it does (codeHeadStore); and what a team's
20
+ // Dependencies tab was last told of each repository, by its reader, for a
21
+ // week (teamDependencyStore). Each store removes
22
+ // its own rows kept longer than that as it writes, at most once an hour a
23
+ // database (pruneKept), so that rows no read will take again don't pile up.
24
+ // The database is an optimization: a failure reads as a miss, and writes
25
+ // nothing.
26
+ import { createHash } from 'node:crypto'
27
+ import { plainObject } from './npm-manifest.ts'
28
+ import { type NpmPublishTimeStore, type NpmVersionStore, VERSION_KEPT_MS } from './npm-packages.ts'
29
+ import type { KeptPatch } from './npm-patch.ts'
30
+ import type { UpstreamCacheStore } from './upstream-cache.ts'
31
+
32
+ // A value kept by key, as JSON, `at` when it was.
33
+ export interface KeptStore<T> {
34
+ read(key: string): Promise<{ at: number; value: T } | null>
35
+ // Those of `keys` kept, by key, in one read of the database.
36
+ readMany(keys: string[]): Promise<Map<string, { at: number; value: T }>>
37
+ // Those of `first` kept; where none is, those of `then`, in one read of the
38
+ // database (`first` whether they are `first`'s).
39
+ readFirst(first: string[], then: string[]): Promise<{ first: boolean; found: Map<string, { at: number; value: T }> }>
40
+ write(key: string, value: T, at: number): Promise<void>
41
+ // Removes what is kept by `key`.
42
+ remove(key: string): Promise<void>
43
+ }
44
+
45
+ // When each database last had the rows under each prefix removed.
46
+ const PRUNE_EVERY_MS = 60 * 60_000
47
+ const pruned = new WeakMap<UpstreamCacheStore, Map<string, number>>()
48
+ // Who sees each database's prunes through (index.ts: its app, which waits
49
+ // for them before closing it, and on serverless keeps its invocation alive
50
+ // till they settle), as a write no longer waits for one.
51
+ const pruneOwners = new WeakMap<UpstreamCacheStore, (prune: Promise<unknown>) => void>()
52
+ export function ownKeptPrunes(db: UpstreamCacheStore, own: (prune: Promise<unknown>) => void) {
53
+ pruneOwners.set(db, own)
54
+ }
55
+
56
+ // Removes the rows under `prefix` kept `keptMs` before `at`, at most once an
57
+ // hour a database, as rows under it are written: here, and risk's downloads
58
+ // (npm-risk.ts), each one run handed to the database's owner. A failure is
59
+ // `warn`ed of, and removes nothing.
60
+ export function pruneKept(db: UpstreamCacheStore, prefix: string, keptMs: number, at: number, warn: (error: unknown) => void): Promise<void> {
61
+ const times = pruned.get(db) ?? pruned.set(db, new Map()).get(db)!
62
+ if (at - (times.get(prefix) ?? -Infinity) < PRUNE_EVERY_MS) return Promise.resolve()
63
+ times.set(prefix, at)
64
+ const prune = (async () => { try { await db.deleteUpstreamCacheEntries(prefix, at - keptMs) } catch (error) { warn(error) } })()
65
+ pruneOwners.get(db)?.(prune)
66
+ return prune
67
+ }
68
+
69
+ // Values of `type`, each read for `keptMs` after it was kept.
70
+ function keptStore<T>(db: UpstreamCacheStore, type: string, keptMs: number, debug: boolean): KeptStore<T> {
71
+ const warn = (what: string, error: unknown) => { if (debug) console.warn(`managed: kept ${type} ${what} failed:`, error) }
72
+ // Kept for good (Infinity): none removed.
73
+ const prune = (at: number) => keptMs === Infinity ? Promise.resolve() : pruneKept(db, `${type}/`, keptMs, at, error => { warn('prune', error) })
74
+ // Keys of any length or character, as the database's: hashed.
75
+ const keyOf = (key: string) => `${type}/${createHash('sha256').update(key).digest('hex')}`
76
+ const valueOf = (row: string | null | undefined) => {
77
+ const kept: unknown = JSON.parse(row ?? 'null')
78
+ return plainObject(kept) && typeof kept['at'] === 'number' && 'value' in kept ? { at: kept['at'], value: kept['value'] as T } : null
79
+ }
80
+ // Those of `keys` kept among `rows`, by key.
81
+ const found = (keys: string[], rows: Map<string, string>) =>
82
+ new Map(keys.flatMap(key => { const kept = valueOf(rows.get(keyOf(key))); return kept ? [[key, kept] as const] : [] }))
83
+ return {
84
+ async read(key) {
85
+ try { return valueOf(await db.getUpstreamCacheEntry(keyOf(key))) } catch (error) { warn('read', error); return null }
86
+ },
87
+ async readMany(keys) {
88
+ try {
89
+ return found(keys, await db.getUpstreamCacheEntries(keys.map(keyOf)))
90
+ } catch (error) { warn('read', error); return new Map() }
91
+ },
92
+ async readFirst(first, then) {
93
+ try {
94
+ const { first: answered, entries } = await db.getFirstUpstreamCacheEntries(first.map(keyOf), then.map(keyOf))
95
+ return { first: answered, found: found(answered ? first : then, entries) }
96
+ } catch (error) { warn('read', error); return { first: false, found: new Map() } }
97
+ },
98
+ async write(key, value, at) {
99
+ try { await db.setUpstreamCacheEntry(keyOf(key), JSON.stringify({ at, value }), at) } catch (error) { warn('write', error) }
100
+ // Behind the write, not before it is done: the prune reads the whole
101
+ // table (no index serves its prefix), which no writer need wait on.
102
+ // Its hour is marked before it runs, so writes meanwhile start none,
103
+ // and its database's owner sees it through (ownKeptPrunes).
104
+ void prune(at)
105
+ },
106
+ async remove(key) {
107
+ try { await db.deleteUpstreamCacheEntries(keyOf(key), Number.MAX_SAFE_INTEGER) } catch (error) { warn('remove', error) }
108
+ },
109
+ }
110
+ }
111
+
112
+ export function npmVersionStore(db: UpstreamCacheStore, debug = false): NpmVersionStore {
113
+ const kept = keptStore<Record<string, unknown>>(db, 'npm/version-documents', VERSION_KEPT_MS, debug)
114
+ return {
115
+ async read(name, version) {
116
+ const hit = await kept.read(`${name}@${version}`)
117
+ return hit && plainObject(hit.value) ? { at: hit.at, json: hit.value } : null
118
+ },
119
+ async readMany(versions) {
120
+ const hits = await kept.readMany(versions.map(({ name, version }) => `${name}@${version}`))
121
+ return new Map([...hits].flatMap(([key, hit]) => plainObject(hit.value) ? [[key, { at: hit.at, json: hit.value }] as const] : []))
122
+ },
123
+ write: (name, version, json) => kept.write(`${name}@${version}`, json, Date.now()),
124
+ }
125
+ }
126
+
127
+ // When public versions were published (npm-packages.ts npmPublishTime), which
128
+ // never changes once they are: kept a month, and kept again by the next view
129
+ // of the version past it.
130
+ const PUBLISH_TIME_KEPT_MS = 30 * 24 * 60 * 60_000
131
+ export function npmPublishTimeStore(db: UpstreamCacheStore, debug = false): NpmPublishTimeStore {
132
+ const kept = keptStore<string>(db, 'npm/publish-times', PUBLISH_TIME_KEPT_MS, debug)
133
+ return {
134
+ async read(name, version) {
135
+ const hit = await kept.read(`${name}@${version}`)
136
+ return typeof hit?.value === 'string' ? hit.value : null
137
+ },
138
+ write: (name, version, at) => kept.write(`${name}@${version}`, at, Date.now()),
139
+ }
140
+ }
141
+
142
+ // Risk lines, each kept `keptMs`, for good where Infinity, a scan telling one
143
+ // past RISK_KEPT_MS as stale (repository-risk.ts).
144
+ export const riskLineStore = <T>(db: UpstreamCacheStore, keptMs: number, debug = false): KeptStore<T> => keptStore<T>(db, 'repository-risk/lines', keptMs, debug)
145
+ // What a scan read, each read for keptMs (repository-risk.ts): of GitHub, a
146
+ // repository's lockfiles as listed at a commit (`listings`) and a lockfile's
147
+ // packages by its blob (`lockfiles`), for SCAN_READ_KEPT_MS; of npm, a
148
+ // lockfile's advisories by its blob (`advisories`), for RISK_KEPT_MS; the
149
+ // repositories a scan in parts told whole (`progress`); a repository's
150
+ // Actions' files by the commit read (`action-files`), and the actions and
151
+ // reusable workflows of others they name, each resolved (`actions`), of
152
+ // public repositories alone (repository-actions.ts).
153
+ export const scanReadStore = <T>(db: UpstreamCacheStore, type: 'listings' | 'lockfiles' | 'advisories' | 'progress' | 'action-files' | 'actions', keptMs: number, debug = false): KeptStore<T> =>
154
+ keptStore<T>(db, `repository-risk/${type}`, keptMs, debug)
155
+ // What the code viewer read of a repository (http.ts readWholeRepository), by
156
+ // its id and what was asked, each kept REPOSITORY_READ_KEPT_MS.
157
+ export const REPOSITORY_READ_KEPT_MS = 24 * 60 * 60_000
158
+ export const repositoryReadStore = (db: UpstreamCacheStore, debug = false): KeptStore<object> =>
159
+ keptStore<object>(db, 'repository/reads', REPOSITORY_READ_KEPT_MS, debug)
160
+ // GitHub's answers to GETs that came with an ETag (github-requests.ts
161
+ // taggedRead), by their request's key, for any instance to ask again
162
+ // If-None-Match, kept as long as what was read of a repository is.
163
+ export const githubTagStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'github/tags', REPOSITORY_READ_KEPT_MS, debug)
164
+ // Pages of a repository's history (repository-history.ts historyFrom), by its
165
+ // id and the commit each starts at, which never change: kept a month after
166
+ // they were last read from GitHub.
167
+ const HISTORY_PAGE_KEPT_MS = 30 * 24 * 60 * 60_000
168
+ export const historyPageStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/history', HISTORY_PAGE_KEPT_MS, debug)
169
+ // What the Pulse's walks of a repository's year found (pulse-walk.ts
170
+ // keptWalk), as the history pages holding it, kept as those pages are.
171
+ export const pulseWalkStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/pulse-walk', HISTORY_PAGE_KEPT_MS, debug)
172
+ // The pull requests squashed into a repository's commits, by the commit
173
+ // (repository-squashes.ts squashedPulls): kept as its history's pages are.
174
+ export const historySquashStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/squashes', HISTORY_PAGE_KEPT_MS, debug)
175
+ // Whether a pull request brought a commit, by its repository and commit, as
176
+ // the Agents tab looks it up of those an agent marked (repository-agents.ts
177
+ // pulledCommits), kept as the history is.
178
+ export const commitPullStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/commit-pulls', HISTORY_PAGE_KEPT_MS, debug)
179
+ // A repository's pull requests, the most recently updated first, as the
180
+ // Pulse and the Agents tab read them (repository-pulls.ts readPulls), by its
181
+ // id: kept as its history's pages are, those updated since read on.
182
+ export const pullListStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/pulls', HISTORY_PAGE_KEPT_MS, debug)
183
+ // A branch's tip, by its repository and commit, as the Agents tab looks it
184
+ // up (repository-agents.ts agentBranches), and the commits the app agents'
185
+ // accounts authored from a head, by it (authoredCommits): kept as the
186
+ // history is, neither changing.
187
+ export const branchTipStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/branch-tips', HISTORY_PAGE_KEPT_MS, debug)
188
+ export const authoredCommitStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/agents-authored', HISTORY_PAGE_KEPT_MS, debug)
189
+ // A repository's issues, the most recently updated first, as the Pulse and
190
+ // the Agents tab read them (repository-pulls.ts readIssues): kept as its
191
+ // pull requests are.
192
+ export const issueListStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/issues-list', HISTORY_PAGE_KEPT_MS, debug)
193
+ // The files each of a repository's commits changes (repository-changes.ts
194
+ // repositoryChanges), by the commit, which never change: kept as its
195
+ // history's pages are.
196
+ export const historyChangeStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/changes', HISTORY_PAGE_KEPT_MS, debug)
197
+ // The files a repository's commit holds (repository-changes.ts
198
+ // repositoryTree), by the commit, which never change: kept as its history's
199
+ // pages are.
200
+ export const historyTreeStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/trees', HISTORY_PAGE_KEPT_MS, debug)
201
+ // What the code viewer read of a repository's trees (http.ts
202
+ // repositoryTreesOf), which never changes once a commit or tree names it: the
203
+ // tree at a directory of a commit, by the repository's id, the commit and the
204
+ // directory (`trees`), how many files a tree holds and their bytes, by
205
+ // the repository's id and the tree's (`tree-files`), and a directory's
206
+ // listing at a commit, by them (`listings`): kept as its history's pages are.
207
+ export const codeTreeStore = <T>(db: UpstreamCacheStore, type: 'trees' | 'tree-files' | 'listings', debug = false): KeptStore<T> =>
208
+ keptStore<T>(db, `repository/code-${type}`, HISTORY_PAGE_KEPT_MS, debug)
209
+ // The commit the code viewer keeps a repository's directories at in byte
210
+ // storage, its default branch's head as last read, and the repository's
211
+ // name they are kept under (repository-code.ts repositoryCodeKept), by the
212
+ // repository's id: kept until the head moves, the repository is renamed or
213
+ // it is removed, one for each repository.
214
+ export const codeHeadStore = (db: UpstreamCacheStore, debug = false): KeptStore<{ commit: string; repo: string }> =>
215
+ keptStore<{ commit: string; repo: string }>(db, 'repository/code-heads', Infinity, debug)
216
+ // The packages a repository's pull request's lockfiles add
217
+ // (pull-dependencies.ts), by the commits of its base and head, which never
218
+ // change: kept as its history's pages are.
219
+ export const pullDependencyStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/pull-dependencies', HISTORY_PAGE_KEPT_MS, debug)
220
+ // The lines a version changes against another, or none (npm-delta.ts), by
221
+ // both sides' integrities, each kept HISTORY_PAGE_KEPT_MS.
222
+ export const npmDeltaStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'npm/deltas', HISTORY_PAGE_KEPT_MS, debug)
223
+ // The same, of public versions alone, by their names and versions
224
+ // (npm-delta.ts versionDeltaKey), which npm never gives other files: read
225
+ // without their integrities, so without asking npm, or keeping what it tells
226
+ // of them, for them. Each read for VERSION_DELTA_KEPT_MS alone, pruned or not.
227
+ export const VERSION_DELTA_KEPT_MS = 30 * 24 * 60 * 60_000
228
+ export const npmVersionDeltaStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'npm/version-deltas', VERSION_DELTA_KEPT_MS, debug)
229
+ // The same of those of which either is private, kept apart: read only with
230
+ // the dependencies of a repository that locks the version, as anyone who
231
+ // reads those may be told its lines (npm-delta.ts countedDeltas), npm read
232
+ // with the server's one token whoever asks. Each read for VERSION_DELTA_KEPT_MS alone.
233
+ export const privateVersionDeltaStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'npm/private-version-deltas', VERSION_DELTA_KEPT_MS, debug)
234
+ // The versions a repository's lockfiles locked at the commit its dependencies
235
+ // are reviewed since (pull-dependency-reviews.ts reviewBaseline), by the
236
+ // commit, which never change: kept as its history's pages are, never stored
237
+ // as reviews.
238
+ export const reviewBaselineStore = (db: UpstreamCacheStore, debug = false): KeptStore<{ versions: string[]; unread: string[] }> =>
239
+ keptStore<{ versions: string[]; unread: string[] }>(db, 'repository/review-baselines', HISTORY_PAGE_KEPT_MS, debug)
240
+ // What a repository's dependency review read of GitHub (pull-dependencies.ts
241
+ // LockfileStore): the lockfiles a commit lists (`listings`), by the commit,
242
+ // and a lockfile's packages with what their reviews are held to
243
+ // (`lockfiles`), by its blob, which never change: kept as its history's
244
+ // pages are, apart from a scan's (scanReadStore), which reads them without
245
+ // what their reviews are held to.
246
+ export const lockfileReadStore = <T>(db: UpstreamCacheStore, type: 'listings' | 'lockfiles', debug = false): KeptStore<T> =>
247
+ keptStore<T>(db, `repository/review-${type}`, HISTORY_PAGE_KEPT_MS, debug)
248
+ // The pnpm patches a repository's dependency reviews read (npm-patch.ts), by
249
+ // the repository and each's hash, a sha256, which names its text wherever
250
+ // and whenever it is read: kept for good.
251
+ export const patchStore = (db: UpstreamCacheStore, debug = false): KeptStore<KeptPatch> => keptStore<KeptPatch>(db, 'repository/patches', Infinity, debug)
252
+ // A bundle's validations (bundle-validation.ts), by the bundle, where it is,
253
+ // what its reader could check and the rules they were made by: kept a month
254
+ // after they were made, as what they check never changes.
255
+ export const bundleValidationStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'bundles/validations', HISTORY_PAGE_KEPT_MS, debug)
256
+ // What a team's Dependencies tab (http.ts handleTeamDependencies) was last
257
+ // told whole of a repository, by its reader, the repository, its review's
258
+ // setting and what was asked: its default branch's line and its pull
259
+ // requests' dependencies, sent first as kept while they are read again, then
260
+ // replaced. Each kept TEAM_DEPENDENCIES_KEPT_MS, as one a week old still
261
+ // shows a reader more than nothing while it is read.
262
+ export const TEAM_DEPENDENCIES_KEPT_MS = 7 * 24 * 60 * 60_000
263
+ export const teamDependencyStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'teams/dependencies', TEAM_DEPENDENCIES_KEPT_MS, debug)
264
+ // What a risk scan told whole of a repository (repository-risk.ts
265
+ // KeptRepository), but its Dependabot alerts, by its reader, the repository
266
+ // and a team's directories in it, compressed: told first as a scan of it
267
+ // opens, while it is read again (http.ts handleRepositoryRisk). Kept as a
268
+ // team's Dependencies are.
269
+ export const riskKeptStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository-risk/kept', TEAM_DEPENDENCIES_KEPT_MS, debug)
270
+ // What a repository's stasis.config.json has Stasis reach at a commit
271
+ // (stasis-dependencies.ts): the versions, never the lockfile, by the
272
+ // repository, the commit and the file's path, kept as its history's pages are.
273
+ export const stasisDependencyStore = (db: UpstreamCacheStore, debug = false): KeptStore<unknown> =>
274
+ keptStore<unknown>(db, 'repository/stasis-dependencies', HISTORY_PAGE_KEPT_MS, debug)
@@ -0,0 +1,259 @@
1
+ // Loading a published version for the npm package viewer (npm-packages.ts):
2
+ // its tarball, kept on disk as bundle builds keep theirs, else read from the
3
+ // registry, its files unpacked from it, and the viewer's response built from
4
+ // them, each shared by the readers asking for it meanwhile and held to a few
5
+ // versions at once per process; its files kept a little while after.
6
+ import { Buffer } from 'node:buffer'
7
+ import { homedir } from 'node:os'
8
+ import { join, resolve } from 'node:path'
9
+ import { CompressionError, decompress } from '@preventive/archive/compression.js'
10
+ import { npmTokenFor } from '../common/npm-token.js'
11
+ import { encodeBrotli } from './brotli.ts'
12
+ import { keptBriefly } from './kept-briefly.ts'
13
+ import { MAX_NPM_PACKAGE_BYTES, MAX_NPM_PACKAGE_FILES, NPM_REGISTRY, NpmPackageError, type NpmPackageFile, type NpmVersionDocument, type TarReading,
14
+ askUpstream, npmExecutablePaths, npmFileRows, npmPublishTime, readNpmTar } from './npm-packages.ts'
15
+ import { keepFile, readKeptFile, upstreamCachePath } from './upstream-cache.ts'
16
+
17
+ // The tar stream a package's files may come in, headers and padding included.
18
+ // A tarball larger than that cannot unpack within it, so it is refused as it
19
+ // arrives.
20
+ export const MAX_TAR_BYTES = 96 * 1024 * 1024
21
+ const TARBALL_TIMEOUT_MS = 120_000
22
+ // Loads in flight per process, those of one version (its tarball, its files,
23
+ // its response) as one, as they read its tarball and unpack it once between
24
+ // them; each can hold a tarball, its tar, its files and their encoded JSON.
25
+ const MAX_ACTIVE_LOADS = 4
26
+ // How long a public version's files are kept once unpacked, and what they
27
+ // may take between them, the least lately read going first past it:
28
+ // Compare's requests for a pair of versions, and the Code tab's, come one
29
+ // after another, each loading the same files. A private version's are never
30
+ // kept, as nothing else of it is past its readers.
31
+ const UNPACKED_KEPT_MS = 60_000
32
+ const MAX_UNPACKED_BYTES = 128 * 1024 * 1024
33
+
34
+ // A load's result, shared by its readers, and a reader's release of it.
35
+ export interface NpmLoad<T> { result: Promise<T>; release: () => void }
36
+
37
+ interface Load { job: Promise<unknown>; readers: number; settled: boolean; slot: string }
38
+
39
+ // Loads by what they read; readers asking for the same share one. A load
40
+ // keeps its place among the active ones until its work is done and each
41
+ // reader has released it, as a reader does once its response is written or
42
+ // abandoned, so what responses still hold counts too. Places by the slot
43
+ // their loads share, with how many hold each and how many places it takes.
44
+ const loads = new Map<string, Load>()
45
+ const slots = new Map<string, { holding: number; places: number }>()
46
+ const placesTaken = () => [...slots.values()].reduce((sum, slot) => sum + slot.places, 0)
47
+
48
+ const refused = <T>(status: number, code: string): NpmLoad<T> => {
49
+ const result = Promise.reject(new NpmPackageError(status, code))
50
+ result.catch(() => {})
51
+ return { result, release() {} }
52
+ }
53
+
54
+ // What names a version's tarball, and so its files: its integrity, its
55
+ // shasum and URL, and whether it is read with the token.
56
+ const tarballKey = (doc: NpmVersionDocument) => `${doc.dist.integrity} ${doc.dist.shasum ?? ''} ${doc.dist.tarball} ${doc.private}`
57
+
58
+ function shared<T>(what: string, doc: NpmVersionDocument, work: () => Promise<T>): NpmLoad<T> {
59
+ const { unpackedSize, fileCount } = doc.dist
60
+ if ((unpackedSize ?? 0) > MAX_NPM_PACKAGE_BYTES || (fileCount ?? 0) > MAX_NPM_PACKAGE_FILES) return refused(413, 'package-too-large')
61
+ const slot = tarballKey(doc)
62
+ return sharedLoad(`${what} ${slot}`, work, 'npm-busy', { slot })
63
+ }
64
+
65
+ // The places among the active ones a load takes whose files hold `files` and
66
+ // `bytes`: as many as packages they would fill, up to every one, each place
67
+ // holding what a package may.
68
+ export function loadPlaces({ files, bytes }: { files: number; bytes: number }): number {
69
+ return Math.min(MAX_ACTIVE_LOADS, Math.max(1, Math.ceil(files / MAX_NPM_PACKAGE_FILES), Math.ceil(bytes / MAX_NPM_PACKAGE_BYTES)))
70
+ }
71
+
72
+ // A load among the active ones, by `key`, refused as `busy` past them: a
73
+ // repository directory's (repository-code.ts) as a package's, each holding
74
+ // alike a tarball, its tar, its files and their encoded JSON. Loads of one
75
+ // `slot` take one place between them, or `places` (loadPlaces) where they
76
+ // hold more.
77
+ export function sharedLoad<T>(key: string, work: () => Promise<T>, busy: string,
78
+ { slot = key, places = 1 }: { slot?: string; places?: number } = {}): NpmLoad<T> {
79
+ let load = loads.get(key)
80
+ if (!load) {
81
+ if (!slots.has(slot) && placesTaken() + places > MAX_ACTIVE_LOADS) return refused(429, busy)
82
+ const created: Load = { job: work(), readers: 0, settled: false, slot }
83
+ const finish = () => { created.settled = true; done(key, created) }
84
+ created.job.then(finish, finish)
85
+ loads.set(key, created)
86
+ const taken = slots.get(slot)
87
+ slots.set(slot, { holding: (taken?.holding ?? 0) + 1, places: taken?.places ?? places })
88
+ load = created
89
+ }
90
+ const held = load
91
+ held.readers++
92
+ let released = false
93
+ return {
94
+ result: held.job as Promise<T>,
95
+ release() {
96
+ if (released) return
97
+ released = true
98
+ held.readers--
99
+ done(key, held)
100
+ },
101
+ }
102
+ }
103
+
104
+ // A load gone from the active ones, and its place with it, once its work is
105
+ // done and its readers have released it.
106
+ function done(key: string, load: Load) {
107
+ if (load.readers !== 0 || !load.settled || loads.get(key) !== load) return
108
+ loads.delete(key)
109
+ const taken = slots.get(load.slot)!
110
+ if (taken.holding === 1) slots.delete(load.slot)
111
+ else taken.holding--
112
+ }
113
+
114
+ // The sha512 an integrity names, in base64, or null where it names none.
115
+ const sha512Of = (integrity: string) => /(?:^|\s)sha512-([\d+/A-Za-z]{86}==)(?=\s|$)/u.exec(integrity)?.[1] ?? null
116
+ // Hashed off the event loop: a tarball runs to tens of MiB.
117
+ const digest = async (algorithm: string, bytes: Uint8Array) => Buffer.from(await crypto.subtle.digest(algorithm, bytes as Uint8Array<ArrayBuffer>))
118
+ // Whether `bytes` are those of the sha512 an integrity names and, where there
119
+ // is one, of the shasum (a sha1, in hex).
120
+ async function hashedAs(bytes: Uint8Array, sha512: string, shasum: string | null): Promise<boolean> {
121
+ const [own512, own1] = await Promise.all([digest('SHA-512', bytes), shasum === null ? null : digest('SHA-1', bytes)])
122
+ return own512.toString('base64') === sha512 && (own1 === null || own1.toString('hex') === shasum)
123
+ }
124
+
125
+ // Upstream's disk cache (setCacheDir), where tarballs are kept between
126
+ // loads, or null to keep none and read none.
127
+ let tarballCache: string | null = null
128
+
129
+ export function setNpmTarballCache(dir: string | null) {
130
+ tarballCache = dir === null ? null : resolve(dir)
131
+ }
132
+
133
+ // Where npm's own cache files content by its sha512, short of an .npmrc
134
+ // moving the cache.
135
+ function npmCachePath(hash: string): string | null {
136
+ const configured = process.env['npm_config_cache'] || process.env['NPM_CONFIG_CACHE']
137
+ let root
138
+ try {
139
+ root = configured ? resolve(configured.replace(/^~(?=[/\\])/u, homedir()))
140
+ : process.platform === 'win32' ? join(process.env['LOCALAPPDATA'] || homedir(), 'npm-cache') : join(homedir(), '.npm')
141
+ } catch { return null }
142
+ const hex = Buffer.from(hash, 'base64').toString('hex')
143
+ return join(root, '_cacache', 'content-v2', 'sha512', hex.slice(0, 2), hex.slice(2, 4), hex.slice(4))
144
+ }
145
+
146
+ // The version's tarball from the registry, at the package's own path, its
147
+ // size bounded as it arrives.
148
+ async function downloadTarball(url: string, token: string | null): Promise<Buffer> {
149
+ const bytes = await askUpstream(url, { headers: token ? { authorization: `Bearer ${token}` } : {}, limit: MAX_TAR_BYTES, ms: TARBALL_TIMEOUT_MS, absent: [401, 403, 404] })
150
+ .catch((err: unknown) => { throw err instanceof NpmPackageError && err.message === 'upstream-too-large' ? new NpmPackageError(413, 'package-too-large') : err })
151
+ if (bytes === null) throw new NpmPackageError(404, 'package-not-found')
152
+ return bytes
153
+ }
154
+
155
+ // The version's tarball, its bytes held to the document's sha512, and to its
156
+ // shasum where it tells one, wherever they come from: kept in the cache,
157
+ // where bundle builds keep what they fetch with the token, or in npm's; else
158
+ // downloaded, and then kept. Bytes matching the hashes the reader's own
159
+ // document names are the tarball that reader may download, wherever they
160
+ // were kept and whoever fetched them.
161
+ async function readTarball(doc: NpmVersionDocument): Promise<Uint8Array> {
162
+ const expected = sha512Of(doc.dist.integrity), shasum = doc.dist.shasum, url = doc.dist.tarball
163
+ if (!url.startsWith(`${NPM_REGISTRY}/${doc.name}/-/`) || URL.parse(url)?.href !== url || expected === null
164
+ || (shasum !== null && !/^[\da-f]{40}$/u.test(shasum))) throw new NpmPackageError(502, 'upstream-invalid')
165
+ const kept = tarballCache === null ? null : upstreamCachePath(tarballCache, 'npm/tarballs', `${doc.name}@${doc.version}.tgz`)
166
+ if (kept !== null) {
167
+ for (const path of [kept, npmCachePath(expected)]) {
168
+ const bytes = path === null ? null : await readKeptFile(path, MAX_TAR_BYTES)
169
+ if (bytes && await hashedAs(bytes, expected, shasum)) return bytes
170
+ }
171
+ }
172
+ const bytes = await downloadTarball(url, doc.private ? npmTokenFor(doc.name) : null)
173
+ if (!await hashedAs(bytes, expected, shasum)) throw new NpmPackageError(502, 'upstream-invalid')
174
+ if (kept !== null) await keepFile(kept, bytes)
175
+ return bytes
176
+ }
177
+
178
+ // Tarballs being read, and versions' files being unpacked, by what names
179
+ // them (tarballKey): readers asking for one meanwhile share it, its bytes
180
+ // those each one's own document names.
181
+ const reading = new Map<string, Promise<Uint8Array>>()
182
+ const unpacking = new Map<string, Promise<Unpacked>>()
183
+
184
+ function sharedRead<T>(pending: Map<string, Promise<T>>, key: string, read: () => Promise<T>): Promise<T> {
185
+ let job = pending.get(key)
186
+ if (!job) {
187
+ const started = read().finally(() => { if (pending.get(key) === started) pending.delete(key) })
188
+ pending.set(key, job = started)
189
+ }
190
+ return job
191
+ }
192
+
193
+ const sharedTarball = (doc: NpmVersionDocument) => sharedRead(reading, tarballKey(doc), () => readTarball(doc))
194
+
195
+ // A version's files, and the size of the tarball they came in.
196
+ interface Unpacked { files: NpmPackageFile[]; tarballSize: number }
197
+
198
+ // Public versions' files lately unpacked, by tarballKey.
199
+ const unpacked = keptBriefly<Unpacked>({ keptMs: UNPACKED_KEPT_MS, maxBytes: MAX_UNPACKED_BYTES })
200
+
201
+ // The version's files, kept from a load of them a little while since, else
202
+ // unpacked from its tarball (and kept, a public version's): bytes its
203
+ // reader's own document names, as its tarball's are.
204
+ function unpackedOf(doc: NpmVersionDocument): Promise<Unpacked> {
205
+ const key = tarballKey(doc)
206
+ const kept = unpacked.get(key)
207
+ if (kept) return Promise.resolve(kept)
208
+ return sharedRead(unpacking, key, async () => {
209
+ const tarball = await sharedTarball(doc)
210
+ const value = { files: await readTarballFiles(tarball), tarballSize: tarball.byteLength }
211
+ if (!doc.private) unpacked.keep(key, value, value.files.reduce((sum, file) => sum + file.path.length + file.bytes.byteLength, 0))
212
+ return value
213
+ })
214
+ }
215
+
216
+ // A gzipped tarball's files, its top directory left out, as npm extracts
217
+ // a package's: a repository tree's as GitHub archives it, too, its symlinks
218
+ // let climb as readNpmTar's `symlinksAbove` says, and its tar stream and
219
+ // files bounded as `options` give, a package's bounds unless given.
220
+ export async function readTarballFiles(tarball: Uint8Array, { maxTarBytes = MAX_TAR_BYTES, ...options }: TarReading & { maxTarBytes?: number } = {}): Promise<NpmPackageFile[]> {
221
+ let tar: Uint8Array
222
+ try { tar = await decompress(tarball, 'gzip', { limit: maxTarBytes }) }
223
+ catch (err) {
224
+ const limited = err instanceof CompressionError && err.limited
225
+ throw new NpmPackageError(limited ? 413 : 422, limited ? 'package-too-large' : 'bad-tarball')
226
+ }
227
+ return readNpmTar(tar, options)
228
+ }
229
+
230
+ // The version's tarball, for download.
231
+ export function loadNpmTarball(doc: NpmVersionDocument): NpmLoad<Uint8Array> {
232
+ return shared('tarball', doc, () => sharedTarball(doc))
233
+ }
234
+
235
+ // The version's files, for one of them to be pretty-printed (pretty-print.ts).
236
+ export function loadNpmFiles(doc: NpmVersionDocument): NpmLoad<NpmPackageFile[]> {
237
+ return shared('files', doc, async () => (await unpackedOf(doc)).files)
238
+ }
239
+
240
+ // The version as the viewer reads it, as brotli-encoded JSON: `{ name,
241
+ // version, private, integrity, tarballSize, published, manifest, files,
242
+ // known }`, its files as npmFileRows gives them, and with them, as its files
243
+ // are encoded, when it was published where that is kept (`published`, asked
244
+ // then, else null) and what `known` gives: what is kept about its package
245
+ // (npm-insights.ts npmKnown), which the viewer need not then ask for. Encoding
246
+ // is where a load holds the most, so it takes its place among the active
247
+ // loads until its body is done, and readers asking meanwhile share that body,
248
+ // the first one's manifest, `published` and `known` in it; the body is not
249
+ // kept once its readers are done, its files a little while (unpackedOf).
250
+ export function loadNpmPackageBody(doc: NpmVersionDocument, known: () => object = () => ({}),
251
+ published: () => Promise<string | null> = npmPublishTime(doc).read): NpmLoad<Buffer> {
252
+ return shared('package', doc, async () => {
253
+ const { files, tarballSize } = await unpackedOf(doc)
254
+ return encodeBrotli(Buffer.from(JSON.stringify({
255
+ name: doc.name, version: doc.version, private: doc.private, integrity: doc.dist.integrity, tarballSize,
256
+ published: await published(), manifest: doc.manifest, files: npmFileRows(files), executable: npmExecutablePaths(files), known: known(),
257
+ })))
258
+ })
259
+ }