@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,117 @@
1
+ // What a published version's document tells of it as the npm viewer's
2
+ // Overview shows it (npmManifest), and the fields of the document read for it
3
+ // and for the version itself (npm-packages.ts readNpmVersion), the rest
4
+ // stripped where it is kept (npmVersionFields).
5
+ import publishers from '@preventive/publishers/npm.js'
6
+ import { getRepo } from '@preventive/upstream/package.js'
7
+
8
+ export const plainObject = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
9
+ export const stringRecord = (value: unknown) => plainObject(value)
10
+ ? Object.fromEntries(Object.entries(value).filter(([, item]) => typeof item === 'string')) as Record<string, string> : undefined
11
+
12
+ interface NpmPerson { name: string | null; email: string | null }
13
+ const NPM_ACCOUNT = /^[\w.-]{1,214}$/u
14
+ // The npm accounts known to publish: those with standing on one of npm's
15
+ // most downloaded packages (@preventive/publishers).
16
+ const KNOWN_PUBLISHERS = new Set(publishers.map(name => name.toLowerCase()))
17
+
18
+ // One of package.json's people: `{ name, email, url }`, or `Name <email>
19
+ // (url)` in one string.
20
+ function npmPerson(value: unknown): NpmPerson | null {
21
+ const text = (part: unknown) => typeof part === 'string' && part.trim() !== '' ? part.trim() : null
22
+ if (plainObject(value)) return { name: text(value['name']), email: text(value['email']) }
23
+ if (typeof value !== 'string') return null
24
+ const parts = /^([^<(]*)(?:<([^>]*)>)?\s*(?:\([^)]*\))?\s*$/u.exec(value)
25
+ return parts ? { name: text(parts[1]), email: text(parts[2]) } : { name: text(value), email: null }
26
+ }
27
+
28
+ // The GitLab project (`group/project`, subgroups and all) a package names as
29
+ // its repository, in any of the forms npm takes (`gitlab:group/project`,
30
+ // `git@gitlab.com:…`, `git+https://gitlab.com/….git`); null for another.
31
+ // GitLab's are only on gitlab.com, as npm's provenance has them.
32
+ function gitlabProject(repository: unknown): string | null {
33
+ const url = typeof repository === 'string' ? repository : plainObject(repository) && typeof repository['url'] === 'string' ? repository['url'] : ''
34
+ if (url.length > 2048) return null
35
+ const project = /^(?:gitlab:|git@gitlab\.com:|(?:git\+)?(?:https|ssh|git):\/\/(?:git@)?gitlab\.com\/)([\w.-]+(?:\/[\w.-]+)+)\/?$/u
36
+ .exec(url.split('/-/')[0]!)?.[1]?.replace(/\.git$/u, '')
37
+ return project && !project.split('/').some(part => /^\.+$/u.test(part)) ? project : null
38
+ }
39
+
40
+ // The fields the Overview shows, in the shapes package.json gives them; each
41
+ // left out where the document has none, or has another shape. A homepage that
42
+ // leads only where its repository does (the repository, its directory there,
43
+ // or its readme, npm's homepage where the package names none) is left out.
44
+ export function npmManifest(json: Record<string, unknown>): Record<string, unknown> {
45
+ const pick: Record<string, unknown> = {}
46
+ for (const key of ['description', 'license', 'homepage', 'main', 'module', 'types', 'type', 'deprecated', 'gitHead']) {
47
+ if (typeof json[key] === 'string') pick[key] = json[key]
48
+ }
49
+ // Its author's name, and their npm account where it can be told: the
50
+ // publisher's or a maintainer's whose email or name is the author's. Emails
51
+ // only match people up; none is kept.
52
+ const author = npmPerson(json['author'])
53
+ if (author?.name) pick['author'] = author.name
54
+ const accounts = [json['_npmUser'], ...Array.isArray(json['maintainers']) ? json['maintainers'] : []].map(npmPerson)
55
+ .filter((person): person is NpmPerson & { name: string } => person?.name != null && NPM_ACCOUNT.test(person.name))
56
+ // The npm account that published it, for its profile; or, published by
57
+ // a CI npm trusts (npm's trusted publishing), the CI, as npm names it
58
+ // (`GitHub Actions`).
59
+ const publisher = npmPerson(json['_npmUser'])?.name
60
+ if (publisher && NPM_ACCOUNT.test(publisher)) pick['publisher'] = publisher
61
+ else if (publisher && publisher.length <= 64 && plainObject(json['_npmUser']) && plainObject(json['_npmUser']['trustedPublisher'])) pick['trustedPublisher'] = publisher
62
+ const same = (a: string | null, b: string | null) => a !== null && b !== null && a.toLowerCase() === b.toLowerCase()
63
+ const account = author && accounts.find(person => same(person.email, author.email) || same(person.name, author.name))
64
+ if (account) pick['authorAccount'] = account.name
65
+ // Which of those accounts are known to publish, for the Overview to tell
66
+ // them from the rest.
67
+ const known = [...new Set([publisher, account?.name])].filter(name => name && KNOWN_PUBLISHERS.has(name.toLowerCase()))
68
+ if (known.length > 0) pick['knownAccounts'] = known
69
+ if (Array.isArray(json['keywords'])) pick['keywords'] = json['keywords'].filter(item => typeof item === 'string').slice(0, 50)
70
+ if (typeof json['bin'] === 'string') pick['bin'] = { [String(json['name'])]: json['bin'] }
71
+ else if (stringRecord(json['bin'])) pick['bin'] = stringRecord(json['bin'])
72
+ for (const key of ['dependencies', 'peerDependencies', 'optionalDependencies', 'engines']) {
73
+ const record = stringRecord(json[key])
74
+ if (record && Object.keys(record).length > 0) pick[key] = record
75
+ }
76
+ if (json['hasInstallScript'] === true) pick['hasInstallScript'] = true
77
+ if (hasProvenance(json['dist'])) pick['provenance'] = true
78
+ // The scripts npm runs installing it from the registry; not `prepare`,
79
+ // which runs only for a local or git install.
80
+ const scripts = stringRecord(json['scripts'])
81
+ const install = scripts ? INSTALL_SCRIPTS.filter(script => script in scripts) : []
82
+ if (install.length > 0) pick['installScripts'] = Object.fromEntries(install.map(script => [script, scripts![script]]))
83
+ // A GitLab project it names, as its provenance's source is matched with
84
+ // the repository it names, GitHub's below.
85
+ const gitlab = gitlabProject(json['repository'])
86
+ if (gitlab) pick['gitlab'] = gitlab
87
+ try {
88
+ const repo = getRepo(json)
89
+ if (repo.github) {
90
+ pick['github'] = { github: repo.github, ...(repo.directory === undefined ? {} : { directory: repo.directory }) }
91
+ const home = typeof pick['homepage'] === 'string' ? getRepo({ homepage: pick['homepage'] }) : {}
92
+ if (home.github?.toLowerCase() === repo.github.toLowerCase() && (home.directory ?? '') === (repo.directory ?? '')) delete pick['homepage']
93
+ }
94
+ } catch {}
95
+ return pick
96
+ }
97
+
98
+ // Of a version's document, the fields readNpmVersion and npmManifest read,
99
+ // of `dist` and `scripts` only theirs, and of a provenance statement only that
100
+ // there is one: what is kept of it (npm-kept.ts), so that both read a kept one
101
+ // as they read npm's.
102
+ const VERSION_FIELDS = ['name', 'version', 'description', 'license', 'homepage', 'main', 'module', 'types', 'type', 'deprecated', 'gitHead', 'author', '_npmUser',
103
+ 'maintainers', 'keywords', 'bin', 'dependencies', 'peerDependencies', 'optionalDependencies', 'engines', 'hasInstallScript', 'repository', 'bugs']
104
+ const DIST_FIELDS = ['tarball', 'integrity', 'shasum', 'unpackedSize', 'fileCount']
105
+ const INSTALL_SCRIPTS = ['preinstall', 'install', 'postinstall']
106
+ const picked = (json: Record<string, unknown>, keys: string[]) => Object.fromEntries(keys.filter(key => Object.hasOwn(json, key)).map(key => [key, json[key]]))
107
+ // Whether a version's `dist` tells of a provenance statement npm keeps for it
108
+ // (npm-provenance.ts).
109
+ const hasProvenance = (dist: unknown) => plainObject(dist) && plainObject(dist['attestations']) && plainObject(dist['attestations']['provenance'])
110
+
111
+ export function npmVersionFields(json: Record<string, unknown>): Record<string, unknown> {
112
+ const dist = plainObject(json['dist']) ? json['dist'] : {}
113
+ const provenance = hasProvenance(dist)
114
+ const scripts = picked(stringRecord(json['scripts']) ?? {}, INSTALL_SCRIPTS)
115
+ return { ...picked(json, VERSION_FIELDS), dist: { ...picked(dist, DIST_FIELDS), ...provenance && { attestations: { provenance: {} } } },
116
+ ...Object.keys(scripts).length > 0 && { scripts } }
117
+ }
@@ -0,0 +1,477 @@
1
+ // The managed npm package viewer: a published version's files, read from the
2
+ // registry's tarball, for the Overview and Code tabs the bundle view shows.
3
+ //
4
+ // Anyone with workspace access may read a public package. A private one also
5
+ // needs an npm token for its scope on the server (npm-token.js), and a reader
6
+ // with access to it: an admin or manager, or a member of a visible team
7
+ // listing its scope (team-npm-scopes.ts).
8
+ // For everyone else, a version is public only when the registry answers for
9
+ // it without credentials, asked on every request and never from a cache:
10
+ // upstream's caches, which bundle builds fill using the token, hold no
11
+ // answer here. Its tarball may come from them (npm-loads.ts), as only bytes
12
+ // matching the integrity that anonymous answer gives are served; else it is
13
+ // read without credentials too, and held to that integrity.
14
+ import { Buffer } from 'node:buffer'
15
+ import { createHash } from 'node:crypto'
16
+ import { rm } from 'node:fs/promises'
17
+ import { resolve } from 'node:path'
18
+ import { ArchiveError, type Entry, unpack } from '@preventive/archive/tar.js'
19
+ import { isExactVersion } from '@preventive/upstream/semver.js'
20
+ import { isNpmPackageName, isNpmPackageSpec, npmPackageScope } from '../common/managed/npm-packages.js'
21
+ import { npmTokenFor } from '../common/npm-token.js'
22
+ import { NPM_SYMLINKS_ABOVE, npmTarLayout } from '../risk/index.js'
23
+ import type { Role } from '../common/managed/roles.ts'
24
+ import { npmManifest, npmVersionFields, plainObject, stringRecord } from './npm-manifest.ts'
25
+ import { keepJson, readKeptJson, upstreamCachePath } from './upstream-cache.ts'
26
+
27
+ export const NPM_REGISTRY = 'https://registry.npmjs.org'
28
+ const VERSION_DOCUMENT_BYTES = 8 * 1024 * 1024
29
+ // Abbreviated packuments of packages with thousands of versions run to tens of MiB.
30
+ const PACKUMENT_BYTES = 64 * 1024 * 1024
31
+ // What registry documents being read at once may hold, each counted at its
32
+ // limit until it is read and parsed: four packuments, or 32 version documents.
33
+ const MAX_DOCUMENT_BYTES = 4 * PACKUMENT_BYTES
34
+ // What a package may unpack to: the files' bytes and their count; the tar
35
+ // stream holding them is bounded in npm-loads.ts. A repository directory's
36
+ // are its own (repository-code.ts).
37
+ export const MAX_NPM_PACKAGE_BYTES = 64 * 1024 * 1024
38
+ export const MAX_NPM_PACKAGE_FILES = 20_000
39
+ // The entries its tar stream may hold, read before any is counted as a file:
40
+ // a directory's too, though npm packs none.
41
+ export const MAX_NPM_TAR_ENTRIES = 2 * MAX_NPM_PACKAGE_FILES
42
+ // What the files may take as the viewer's JSON. Escaping grows a text up to
43
+ // six times (a control character becomes `\u0001`), so it is counted before
44
+ // anything is serialized.
45
+ export const MAX_NPM_JSON_LENGTH = 96 * 1024 * 1024
46
+ export class NpmPackageError extends Error {
47
+ status: number
48
+ constructor(status: number, code: string) { super(code); this.status = status }
49
+ }
50
+
51
+ // Who reads, as the session has it now: the role, and the scopes of the
52
+ // visible teams they are a member of, where those count (npmScopesCount).
53
+ export interface NpmReader { role: Role; scopes: ReadonlySet<string>; userId: string }
54
+
55
+ // Whether a reader may have a package read with the server's token.
56
+ export function canReadPrivateNpm(reader: NpmReader, name: string): boolean {
57
+ if (reader.role === 'admin' || reader.role === 'manage') return true
58
+ const scope = npmPackageScope(name)
59
+ return scope !== null && reader.scopes.has(scope)
60
+ }
61
+
62
+ // Whether a reader's team scopes count for any of `names`, as
63
+ // canReadPrivateNpm reads them: a scoped one, read by someone below manager.
64
+ export const npmScopesCount = (role: Role, names: readonly string[]): boolean =>
65
+ role !== 'admin' && role !== 'manage' && names.some(name => npmPackageScope(name) !== null)
66
+
67
+ // Whether a read of `name` that npm answers none anonymously is asked again
68
+ // with the server's token: by a reader with private access (`privileged`),
69
+ // where there is a token and the package is scoped, as npm's private packages
70
+ // always are. Else the anonymous answer is the reader's.
71
+ export const npmTokenReads = (name: string, privileged: boolean): boolean => privileged && npmPackageScope(name) !== null && npmTokenFor(name) !== null
72
+
73
+ function registryUrl(name: string, spec?: string): string {
74
+ return `${NPM_REGISTRY}/${name}${spec === undefined ? '' : `/${encodeURIComponent(spec)}`}`
75
+ }
76
+
77
+ // What an upstream (npm's registry and APIs, Socket, GitHub) answers, read
78
+ // whole: null where it says it has none (`absent`, 404 unless said). Asked
79
+ // without redirects, and given up on after `ms`, 30 seconds unless said, or
80
+ // once `signal` aborts, its abort rethrown as it is; a 502 where it can't be
81
+ // asked, answers otherwise or stops, and `upstream-too-large` past `limit`
82
+ // bytes (readLimited). `answered` sees the response first, its status and
83
+ // headers.
84
+ export async function askUpstream(url: string, { limit, ms = 30_000, signal, absent = [404], answered, ...init }: Omit<RequestInit, 'signal'>
85
+ & { limit: number; ms?: number; signal?: AbortSignal; absent?: number[]; answered?: (res: Response) => void }): Promise<Buffer | null> {
86
+ try {
87
+ const res = await fetch(url, { ...init, redirect: 'error', signal: AbortSignal.any([AbortSignal.timeout(ms), ...signal ? [signal] : []]) })
88
+ answered?.(res)
89
+ if (absent.includes(res.status)) { await res.body?.cancel(); return null }
90
+ if (!res.ok) { await res.body?.cancel(); throw new NpmPackageError(502, 'upstream-unavailable') }
91
+ return await readLimited(res, limit)
92
+ } catch (err) {
93
+ if (signal?.aborted || err instanceof NpmPackageError) throw err
94
+ throw new NpmPackageError(502, 'upstream-unavailable')
95
+ }
96
+ }
97
+
98
+ // The same, read as JSON (by `parse`, as one line of ndjson): a 502
99
+ // `upstream-invalid` where it isn't.
100
+ export async function askUpstreamJson(url: string, options: Parameters<typeof askUpstream>[1], parse = (text: string): unknown => JSON.parse(text)): Promise<unknown> {
101
+ const body = await askUpstream(url, options)
102
+ if (body === null) return null
103
+ try { return parse(body.toString('utf8')) } catch { throw new NpmPackageError(502, 'upstream-invalid') }
104
+ }
105
+
106
+ export async function readLimited(res: Response, limit: number): Promise<Buffer> {
107
+ const declared = Number(res.headers.get('content-length'))
108
+ if (declared > limit) { await res.body?.cancel(); throw new NpmPackageError(502, 'upstream-too-large') }
109
+ const chunks: Uint8Array[] = []
110
+ let size = 0
111
+ for await (const chunk of res.body ?? []) {
112
+ size += chunk.byteLength
113
+ if (size > limit) throw new NpmPackageError(502, 'upstream-too-large')
114
+ chunks.push(chunk)
115
+ }
116
+ return Buffer.concat(chunks)
117
+ }
118
+
119
+ // A registry document as npm wrote it, read as the JSON object it is: a 502
120
+ // `upstream-invalid` where it isn't one.
121
+ function documentOf(body: Buffer): Record<string, unknown> {
122
+ let json: unknown
123
+ try { json = JSON.parse(body.toString('utf8')) } catch { throw new NpmPackageError(502, 'upstream-invalid') }
124
+ if (!plainObject(json)) throw new NpmPackageError(502, 'upstream-invalid')
125
+ return json
126
+ }
127
+
128
+ // A registry document, or null where the registry has none for this caller:
129
+ // 404, or 401/403 as it answers some private packages asked anonymously.
130
+ // Credentials go only with `token`; nothing is cached on either side, but for
131
+ // public whole documents (publicWholeDocument).
132
+ async function registryDocument(url: string, { token, accept, limit, signal }: { token: string | null; accept: string; limit: number; signal: AbortSignal }): Promise<Record<string, unknown> | null> {
133
+ const body = await askUpstream(url, { headers: { accept, ...(token ? { authorization: `Bearer ${token}` } : {}) }, limit, signal, absent: [401, 403, 404] })
134
+ return body === null ? null : documentOf(body)
135
+ }
136
+
137
+ // Where public packages' whole documents are kept, off Vercel: the upstream
138
+ // cache dir, set at startup (index.ts); null keeps none.
139
+ let documentCache: string | null = null
140
+ export const setNpmDocumentCache = (dir: string | null) => { documentCache = dir === null ? null : resolve(dir) }
141
+
142
+ // A package's whole document as npm answers anyone (`url` its own), kept on
143
+ // disk where the server keeps them (setNpmDocumentCache) with npm's ETag, and
144
+ // asked for again each time with it: npm answers 304, and nothing more, while
145
+ // it is unchanged. Null where npm has none for anyone, nothing then kept.
146
+ async function publicWholeDocument(name: string, url: string, { limit, signal }: { limit: number; signal: AbortSignal }): Promise<Record<string, unknown> | null> {
147
+ const path = documentCache === null ? null : upstreamCachePath(documentCache, 'npm/packuments', `${name}.json.gz`)
148
+ const kept = path === null ? null : await readKeptJson(path, limit)
149
+ let etag: string | null = null, status = 0
150
+ const body = await askUpstream(url, { headers: { accept: 'application/json', ...kept && { 'if-none-match': kept.etag } }, limit, signal, absent: [304, 401, 403, 404],
151
+ answered: res => { status = res.status; etag = res.headers.get('etag') } })
152
+ if (status === 304 && kept) return kept.json
153
+ if (body === null) {
154
+ if (path !== null && kept) await rm(path, { force: true }).catch(() => {})
155
+ return null
156
+ }
157
+ const json = documentOf(body)
158
+ if (path !== null && etag !== null) await keepJson(path, etag, body)
159
+ return json
160
+ }
161
+
162
+ // Whole documents being asked of npm as anyone asks, by URL and limit:
163
+ // readers asking for one meanwhile share it, as opening a version asks for
164
+ // its package's for its versions, its advisories and its risk at once; each
165
+ // gives up on it alone once its own signal aborts, and it is given up on once
166
+ // they all have. None is asked with the token. Read alike by every reader,
167
+ // none changing it.
168
+ const wholeAsks = new Map<string, { asked: Promise<Record<string, unknown> | null>; controller: AbortController; readers: number }>()
169
+
170
+ function sharedWholeDocument(name: string, url: string, { limit, signal }: { limit: number; signal: AbortSignal }): Promise<Record<string, unknown> | null> {
171
+ if (signal.aborted) return Promise.reject(signal.reason)
172
+ const key = `${url} ${limit}`
173
+ let ask = wholeAsks.get(key)
174
+ if (!ask) {
175
+ const controller = new AbortController()
176
+ const created = { asked: publicWholeDocument(name, url, { limit, signal: controller.signal }), controller, readers: 0 }
177
+ const settle = () => { if (wholeAsks.get(key) === created) wholeAsks.delete(key) }
178
+ created.asked.then(settle, settle)
179
+ wholeAsks.set(key, ask = created)
180
+ }
181
+ const held = ask
182
+ held.readers++
183
+ return new Promise((answer, fail) => {
184
+ let left = false
185
+ const leave = () => {
186
+ if (left) return false
187
+ left = true
188
+ held.readers--
189
+ signal.removeEventListener('abort', onAbort)
190
+ return true
191
+ }
192
+ const onAbort = () => {
193
+ if (!leave()) return
194
+ if (held.readers === 0) {
195
+ if (wholeAsks.get(key) === held) wholeAsks.delete(key)
196
+ held.controller.abort(signal.reason)
197
+ }
198
+ fail(signal.reason)
199
+ }
200
+ const answered = (json: Record<string, unknown> | null) => { if (leave()) answer(json) }
201
+ const failed = (err: unknown) => { if (leave()) fail(err) }
202
+ signal.addEventListener('abort', onAbort, { once: true })
203
+ held.asked.then(answered, failed)
204
+ })
205
+ }
206
+
207
+ // Asked anonymously first, unless its caller knows npm has none for anyone
208
+ // (`anonymous` false): a reader without private access stops there. One
209
+ // with it asks again with the token where npmTokenReads says so, and the
210
+ // answer is private. A whole document (`whole`) anyone may read is kept
211
+ // (publicWholeDocument), and asked once for those asking at once
212
+ // (sharedWholeDocument).
213
+ async function readDocument(name: string, url: string, privileged: boolean,
214
+ { whole = false, anonymous = true, ...options }: { accept: string; limit: number; signal: AbortSignal; whole?: boolean; anonymous?: boolean }) {
215
+ const open = anonymous ? whole ? await sharedWholeDocument(name, url, options) : await registryDocument(url, { ...options, token: null }) : null
216
+ if (open) return { json: open, private: false }
217
+ if (!npmTokenReads(name, privileged)) return null
218
+ const json = await registryDocument(url, { ...options, token: npmTokenFor(name) })
219
+ return json ? { json, private: true } : null
220
+ }
221
+
222
+ let documentBytes = 0
223
+
224
+ // A `spare` read, one no reader waits on, is made only where it leaves room
225
+ // for two of the largest documents more: readers' own reads come first.
226
+ async function withDocumentBudget<T>(limit: number, read: () => Promise<T>, spare = false): Promise<T> {
227
+ if (documentBytes + limit + (spare ? 2 * PACKUMENT_BYTES : 0) > MAX_DOCUMENT_BYTES) throw new NpmPackageError(429, 'npm-busy')
228
+ documentBytes += limit
229
+ try { return await read() } finally { documentBytes -= limit }
230
+ }
231
+
232
+ export interface NpmVersionDocument {
233
+ name: string
234
+ version: string
235
+ private: boolean
236
+ // `shasum`, the tarball's sha1 in hex, where npm tells it: held, with the
237
+ // integrity, to the tarball its files are read from (npm-loads.ts).
238
+ dist: { tarball: string; integrity: string; shasum: string | null; unpackedSize: number | null; fileCount: number | null }
239
+ manifest: Record<string, unknown>
240
+ }
241
+
242
+ const count = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0 ? value as number : null
243
+
244
+ // The version `json`, a document of package `name`, tells of.
245
+ function versionDocument(name: string, json: Record<string, unknown>, isPrivate: boolean): NpmVersionDocument {
246
+ const dist = json['dist']
247
+ if (json['name'] !== name || typeof json['version'] !== 'string' || !isNpmPackageSpec(json['version']) || !plainObject(dist)
248
+ || typeof dist['tarball'] !== 'string' || typeof dist['integrity'] !== 'string'
249
+ || (dist['shasum'] !== undefined && typeof dist['shasum'] !== 'string')) throw new NpmPackageError(502, 'upstream-invalid')
250
+ return {
251
+ name, version: json['version'], private: isPrivate,
252
+ dist: { tarball: dist['tarball'], integrity: dist['integrity'], shasum: typeof dist['shasum'] === 'string' ? dist['shasum'] : null,
253
+ unpackedSize: count(dist['unpackedSize']), fileCount: count(dist['fileCount']) },
254
+ manifest: npmManifest(json),
255
+ }
256
+ }
257
+
258
+ // Where public versions' documents are kept, of the fields read of them
259
+ // (npm-manifest.ts npmVersionFields), as the database keeps them (npm-kept.ts).
260
+ export interface NpmVersionStore {
261
+ read(name: string, version: string): Promise<{ at: number; json: Record<string, unknown> } | null>
262
+ // Those of `versions` kept, by `name@version`, in one read.
263
+ readMany?(versions: { name: string; version: string }[]): Promise<Map<string, { at: number; json: Record<string, unknown> }>>
264
+ write(name: string, version: string, json: Record<string, unknown>): Promise<void>
265
+ }
266
+
267
+ // The version a spec names, a dist-tag resolved by the registry, with its
268
+ // dist. Null where the registry has none for this reader. With `store`, an
269
+ // exact version kept there for less than a day (VERSION_KEPT_MS) is read from
270
+ // it, not asked of npm, and a public one npm answers is kept. npm never
271
+ // changes a version's files, but its document can change: a deprecation, the
272
+ // package made private (a scoped one can be), the version removed (which whoever
273
+ // reads it from a store learns elsewhere too: risk does). A day bounds each.
274
+ // One kept with no shasum, as none was before it was kept (npmVersionFields),
275
+ // is asked of npm again, which tells one of each version.
276
+ export const VERSION_KEPT_MS = 24 * 60 * 60_000
277
+ export function readNpmVersion(name: string, spec: string, privileged: boolean, signal: AbortSignal, store?: NpmVersionStore): Promise<NpmVersionDocument | null> {
278
+ if (!isNpmPackageName(name) || !isNpmPackageSpec(spec)) return Promise.reject(new NpmPackageError(400, 'bad-package'))
279
+ // A kept one is read within the same budget as npm's answer.
280
+ return withDocumentBudget(VERSION_DOCUMENT_BYTES, async () => {
281
+ const kept = store && isExactVersion(spec) ? await store.read(name, spec) : null
282
+ const keptDist = kept?.json['dist']
283
+ if (kept && Date.now() - kept.at < VERSION_KEPT_MS && plainObject(keptDist) && typeof keptDist['shasum'] === 'string') {
284
+ try { return versionDocument(name, kept.json, false) } catch {}
285
+ }
286
+ const found = await readDocument(name, registryUrl(name, spec), privileged, { accept: 'application/json', limit: VERSION_DOCUMENT_BYTES, signal })
287
+ if (!found) return null
288
+ const doc = versionDocument(name, found.json, found.private)
289
+ if (store && !found.private) await store.write(name, doc.version, npmVersionFields(found.json))
290
+ return doc
291
+ })
292
+ }
293
+
294
+ // `store`, where it reads many at once, with the exact ones of `versions`
295
+ // read from it in one read, for readNpmVersion to read each of those from as
296
+ // it asks: a version and the one it is compared with, read together.
297
+ export function readTogether(store: NpmVersionStore, versions: { name: string; version: string }[]): NpmVersionStore {
298
+ const exact = versions.filter(({ version }) => isExactVersion(version))
299
+ if (!store.readMany || exact.length < 2) return store
300
+ const keys = new Set(exact.map(({ name, version }) => `${name}@${version}`))
301
+ const kept = store.readMany(exact)
302
+ return { ...store, async read(name, version) {
303
+ const key = `${name}@${version}`
304
+ return keys.has(key) ? (await kept).get(key) ?? null : store.read(name, version)
305
+ } }
306
+ }
307
+
308
+ // Each version package `name`'s document `json` lists, newest published
309
+ // first, its abbreviated document's and its whole one's alike; a document of
310
+ // another package, or of no versions, is npm's answer gone wrong
311
+ // (`upstream-invalid`).
312
+ export function npmListedVersions(name: string, json: Record<string, unknown>): string[] {
313
+ if (json['name'] !== name || !plainObject(json['versions'])) throw new NpmPackageError(502, 'upstream-invalid')
314
+ return Object.keys(json['versions']).filter(isNpmPackageSpec).toReversed()
315
+ }
316
+
317
+ // The package's dist-tags and versions, newest published first, from its
318
+ // abbreviated document; with `times`, from its whole one, which alone has
319
+ // when each was published, `times` by version (ISO dates), and `created`,
320
+ // when its first version was, one since unpublished among them: the earliest
321
+ // time it lists, which npm's own `created` can postdate, as a placeholder's
322
+ // does for a package npm took down. With `spare`, as a read no reader waits
323
+ // on (withDocumentBudget). Null where the registry has none for this reader.
324
+ export function readNpmVersions(name: string, privileged: boolean, signal: AbortSignal, { times = false, spare = false } = {}) {
325
+ if (!isNpmPackageName(name)) return Promise.reject(new NpmPackageError(400, 'bad-package'))
326
+ return withDocumentBudget(PACKUMENT_BYTES, async () => {
327
+ const accept = times ? 'application/json' : 'application/vnd.npm.install-v1+json'
328
+ const found = await readDocument(name, registryUrl(name), privileged, { accept, limit: PACKUMENT_BYTES, signal, whole: times })
329
+ if (!found) return null
330
+ const { json } = found
331
+ const versions = npmListedVersions(name, json)
332
+ const distTags = Object.fromEntries(Object.entries(stringRecord(json['dist-tags']) ?? {}).filter(([, version]) => versions.includes(version)))
333
+ const listed = { name, private: found.private, distTags, versions }
334
+ if (!times) return listed
335
+ const time = stringRecord(json['time']) ?? {}
336
+ const published = Object.fromEntries(versions.filter(version => isPublishTime(time[version])).map(version => [version, time[version]!]))
337
+ for (const [version, at] of Object.entries(published)) publishTimes.set(`${name}@${version}`, at)
338
+ while (publishTimes.size > PUBLISH_TIMES) publishTimes.delete(publishTimes.keys().next().value!)
339
+ const listedAt = Object.entries(time).filter(([key, at]) => key !== 'modified' && isPublishTime(at)).map(([, at]) => at)
340
+ const created = listedAt.reduce<string | null>((first, at) => first === null || Date.parse(at) < Date.parse(first) ? at : first, null)
341
+ return { ...listed, times: published, created }
342
+ }, spare)
343
+ }
344
+
345
+ // A package's whole document as npm has it for this reader, for risk
346
+ // (npm-risk.ts), within the bounds and budget every document read here is
347
+ // held to; null where npm has none for this reader, or the name is none npm
348
+ // takes. With `anonymous` false, where npm is known to have none for anyone,
349
+ // it is asked only with the token (readDocument).
350
+ export function readNpmPackument(name: string, privileged: boolean, signal: AbortSignal, { anonymous = true } = {}): Promise<Record<string, unknown> | null> {
351
+ if (!isNpmPackageName(name)) return Promise.resolve(null)
352
+ return withDocumentBudget(PACKUMENT_BYTES, async () => (await readDocument(name, registryUrl(name), privileged,
353
+ { accept: 'application/json', limit: PACKUMENT_BYTES, signal, whole: true, anonymous }))?.json ?? null)
354
+ }
355
+
356
+ const isPublishTime = (value: string | undefined) => typeof value === 'string' && value.length <= 40 && !Number.isNaN(Date.parse(value))
357
+
358
+ // When each version was published, by `name@version`, as whole documents read
359
+ // with `times` have said: a version keeps its time once published, so it is
360
+ // kept for as long as the server runs, the first noted going first past a
361
+ // bound, and answered only with the version, once its reader's access is.
362
+ const PUBLISH_TIMES = 100_000
363
+ const publishTimes = new Map<string, string>()
364
+
365
+ // Where public versions' publish times are kept beyond the instance, as the
366
+ // database keeps them (npm-kept.ts npmPublishTimeStore).
367
+ export interface NpmPublishTimeStore {
368
+ read(name: string, version: string): Promise<string | null>
369
+ write(name: string, version: string, at: string): Promise<void>
370
+ }
371
+
372
+ // When `doc` was published: as noted here, else as `store` keeps a public
373
+ // version's, so that another instance, or this one restarted, has it before
374
+ // it reads the whole document again. The store is read once, at once, beside
375
+ // whatever its caller reads meanwhile, a failure read as none; `read` looks
376
+ // here again as it is asked, as the whole document read meanwhile may have
377
+ // noted it by then, and `keep` keeps there the time noted here where it read
378
+ // none.
379
+ export function npmPublishTime(doc: Pick<NpmVersionDocument, 'name' | 'version' | 'private'>, store?: NpmPublishTimeStore) {
380
+ const noted = () => publishTimes.get(`${doc.name}@${doc.version}`) ?? null
381
+ const kept = store && !doc.private ? store.read(doc.name, doc.version).catch(() => null) : Promise.resolve(null)
382
+ return {
383
+ read: async (): Promise<string | null> => noted() ?? await kept ?? noted(),
384
+ async keep() {
385
+ const at = noted()
386
+ if (at !== null && store && !doc.private && await kept === null) await store.write(doc.name, doc.version, at)
387
+ },
388
+ }
389
+ }
390
+
391
+ // A symlink's `link` is its target as stored, its bytes that target's: no text, whatever they spell.
392
+ // One with an execute bit is `executable`.
393
+ export interface NpmPackageFile { path: string; bytes: Uint8Array; link?: string; executable?: true }
394
+
395
+ // The paths of `files` that are executable, as the viewer gets them beside their rows.
396
+ export const npmExecutablePaths = (files: NpmPackageFile[]) => files.flatMap(file => file.executable ? [file.path] : [])
397
+
398
+ // Paths in the order a package's files are read in (readNpmTar), and
399
+ // Compare's: by their UTF-16 code units, as a plain sort orders them.
400
+ export const pathOrder = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
401
+
402
+ // How a tar stream is read (readNpmTar): how far its symlinks may climb above
403
+ // it, and the entries, files and bytes it may hold, a package's unless given;
404
+ // and whether two paths one on macOS or Windows conflict (`foldPaths`), as they do unless given.
405
+ export interface TarReading { symlinksAbove?: number; maxEntries?: number; maxFiles?: number; maxBytes?: number; foldPaths?: boolean }
406
+
407
+ // The regular files of a tar stream, by package path, as npm and pnpm install
408
+ // them (risk's npmTarLayout): each name as stored past its first component,
409
+ // whatever the archive used (`package/`, a release's own directory, `.`), and
410
+ // a file under no directory at its name, as pnpm installs it. The stream is
411
+ // read by @preventive/archive, which refuses one malformed, a name that would
412
+ // climb out of it, an absolute symlink or one past `symlinksAbove` levels
413
+ // above it, any unless given, and a name repeated as another entry, and
414
+ // gives up past `maxEntries` before reading on. Every file is read, whether
415
+ // or not an installer installs it, a hard link as its target's bytes, a
416
+ // symlink for where it points. Where
417
+ // the files conflict (two that differ at one path, as under two top
418
+ // directories, or at two paths one on macOS or Windows unless `foldPaths` is
419
+ // false, a file within another), it is refused as `tarball-conflict`,
420
+ // never read as one installer does. Directories and devices hold no file
421
+ // content and are skipped.
422
+ export function readNpmTar(tar: Uint8Array, { symlinksAbove = NPM_SYMLINKS_ABOVE, maxEntries = MAX_NPM_TAR_ENTRIES, maxFiles = MAX_NPM_PACKAGE_FILES,
423
+ maxBytes = MAX_NPM_PACKAGE_BYTES, foldPaths = true }: TarReading = {}): NpmPackageFile[] {
424
+ let entries: Entry[]
425
+ try { entries = unpack(tar, { maxEntries, symlinksAbove }) }
426
+ catch (err) {
427
+ if (err instanceof ArchiveError) throw err.limited ? new NpmPackageError(413, 'package-too-large') : new NpmPackageError(422, 'bad-tarball')
428
+ throw err
429
+ }
430
+ const files = npmTarLayout(entries, { maxFiles, maxBytes, foldPaths }, (code) => { throw new NpmPackageError(code === 'package-too-large' ? 413 : 422, code) })
431
+ return [...files].map(([path, file]) => ({ path, ...file })).toSorted((a, b) => pathOrder(a.path, b.path))
432
+ }
433
+
434
+ const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
435
+
436
+ // A file's text, or null for bytes that are not UTF-8 text.
437
+ export function npmFileText(bytes: Uint8Array): string | null {
438
+ if (bytes.includes(0)) return null
439
+ try { return utf8.decode(bytes) } catch { return null }
440
+ }
441
+
442
+ // A string's length in JSON: quotes, backslashes and the control characters
443
+ // with a short escape take two characters, the other control characters six.
444
+ function jsonLength(text: string): number {
445
+ let length = text.length + 2
446
+ for (let i = 0; i < text.length; i++) {
447
+ const code = text.codePointAt(i)!
448
+ if (code === 0x22 || code === 0x5c) length += 1
449
+ else if (code < 0x20) length += code >= 0x08 && code <= 0x0d && code !== 0x0b ? 1 : 5
450
+ }
451
+ return length
452
+ }
453
+
454
+ // A row's brackets, size, null and digest, past its strings.
455
+ const ROW_LENGTH = 80
456
+
457
+ // The files as the viewer gets them: `[path, bytes, text]`, text null for a
458
+ // file that is not UTF-8, which instead carries its bytes' sha256, so a
459
+ // comparison of two versions tells a changed one from an unchanged one; a
460
+ // symlink so too, its target last. They may take `maxLength` characters of
461
+ // JSON, a package's unless given.
462
+ export function npmFileRows(files: NpmPackageFile[], maxLength = MAX_NPM_JSON_LENGTH): ([string, number, string] | [string, number, null, string, string?])[] {
463
+ let length = 0
464
+ return files.map(({ path, bytes, link }) => {
465
+ const text = link === undefined ? npmFileText(bytes) : null
466
+ length += ROW_LENGTH + jsonLength(path) + jsonLength(text ?? link ?? '')
467
+ if (length > maxLength) throw new NpmPackageError(413, 'package-too-large')
468
+ const digest = () => `sha256-${createHash('sha256').update(bytes).digest('base64')}`
469
+ if (text !== null) return [path, bytes.byteLength, text]
470
+ return link === undefined ? [path, bytes.byteLength, null, digest()] : [path, bytes.byteLength, null, digest(), link]
471
+ })
472
+ }
473
+
474
+ // The tarball's filename as `npm pack` writes it.
475
+ export function npmTarballFilename(name: string, version: string): string {
476
+ return `${name.replace(/^@/u, '').replace('/', '-')}-${version}.tgz`
477
+ }