@preventive/triage 1.0.0-alpha.6 → 1.0.0-alpha.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (409) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +17 -0
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +3 -0
  13. package/common/bundle-compare-diff.js +376 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-metadata.d.ts +15 -0
  20. package/common/bundle-metadata.js +226 -0
  21. package/common/bundle-pkg-of.d.ts +1 -0
  22. package/common/bundle-pkg-of.js +90 -0
  23. package/common/bundle-reasons.d.ts +2 -0
  24. package/common/bundle-reasons.js +21 -0
  25. package/common/bundle-source-links.d.ts +6 -0
  26. package/common/bundle-source-links.js +216 -0
  27. package/common/bundle-sourcemap.d.ts +10 -0
  28. package/common/bundle-sourcemap.js +100 -0
  29. package/common/bundle-sources.d.ts +7 -0
  30. package/common/bundle-sources.js +333 -0
  31. package/common/bundle-stats.js +41 -0
  32. package/common/bundle-tabs.js +1 -0
  33. package/common/code-language.js +65 -0
  34. package/common/default-scan-models.ts +36 -0
  35. package/common/dependency-reviews.d.ts +18 -0
  36. package/common/dependency-reviews.js +64 -0
  37. package/common/finding-duplicates.js +58 -0
  38. package/common/finding-filters.js +274 -0
  39. package/common/finding-id.js +47 -0
  40. package/common/finding-repo.d.ts +5 -0
  41. package/common/finding-repo.js +67 -0
  42. package/common/github-issue-labels.d.ts +1 -0
  43. package/common/github-issue-labels.js +11 -0
  44. package/common/github-pr.ts +56 -0
  45. package/common/gzip.js +59 -0
  46. package/common/line-diff.d.ts +8 -0
  47. package/common/line-diff.js +57 -0
  48. package/common/linked-workspace-groups.js +63 -0
  49. package/common/managed/agent-tasks.ts +292 -0
  50. package/common/managed/comments.ts +43 -0
  51. package/common/managed/finding-detail.d.ts +5 -0
  52. package/common/managed/finding-detail.js +75 -0
  53. package/common/managed/finding-values.d.ts +2 -0
  54. package/common/managed/finding-values.js +44 -0
  55. package/common/managed/github-agents.ts +114 -0
  56. package/common/managed/github-logins.ts +49 -0
  57. package/common/managed/lite-name.d.ts +2 -0
  58. package/common/managed/lite-name.js +20 -0
  59. package/common/managed/npm-packages.d.ts +7 -0
  60. package/common/managed/npm-packages.js +51 -0
  61. package/common/managed/permissions.ts +31 -0
  62. package/common/managed/report-content.ts +72 -0
  63. package/common/managed/report-filter.ts +120 -0
  64. package/common/managed/repository-alias.ts +65 -0
  65. package/common/managed/roles.ts +35 -0
  66. package/common/managed/routes.d.ts +2 -0
  67. package/common/managed/routes.js +363 -0
  68. package/common/managed/scan-models.ts +6 -0
  69. package/common/managed/team-app.d.ts +15 -0
  70. package/common/managed/team-app.js +100 -0
  71. package/common/managed/team-filters.js +26 -0
  72. package/common/managed/triage.ts +83 -0
  73. package/common/managed/upload-seal.ts +126 -0
  74. package/common/pretty-print.d.ts +5 -0
  75. package/common/pretty-print.js +24 -0
  76. package/common/repo-commit.d.ts +4 -0
  77. package/common/repo-commit.js +30 -0
  78. package/common/revalidation-conflicts.js +48 -0
  79. package/common/revalidation-input-groups.js +56 -0
  80. package/common/save-error-reason.ts +20 -7
  81. package/common/scan-server.ts +13 -0
  82. package/common/security-links.d.ts +5 -0
  83. package/common/security-links.js +33 -0
  84. package/common/server-info.ts +46 -0
  85. package/common/utf8.d.ts +3 -0
  86. package/common/utf8.js +45 -0
  87. package/common/workspace-app.js +71 -0
  88. package/common/workspace-groups.js +176 -0
  89. package/out/activity.js +4 -0
  90. package/out/brotli-fallback.js +3 -3
  91. package/out/chunk-2XUEZHIP.js +28 -0
  92. package/out/chunk-4EMM6UCD.js +1 -0
  93. package/out/chunk-4ISO5F7Y.js +7 -0
  94. package/out/chunk-4XIH7YTX.js +1 -0
  95. package/out/chunk-6CCSTJWB.js +1 -0
  96. package/out/chunk-74AEKRES.js +10 -0
  97. package/out/chunk-7BKKYVWR.js +7 -0
  98. package/out/chunk-7C7DWL7I.js +1 -0
  99. package/out/chunk-B3FNMHOE.js +1 -0
  100. package/out/chunk-BNH52UHC.js +2 -0
  101. package/out/chunk-BRO77PQY.js +42 -0
  102. package/out/chunk-C4Z6ZBXV.js +10 -0
  103. package/out/chunk-DEVAORP2.js +1 -0
  104. package/out/chunk-E3LFSUDJ.js +9 -0
  105. package/out/chunk-G3LY2FV4.js +1 -0
  106. package/out/chunk-GO7FT4OD.js +1 -0
  107. package/out/chunk-GRGIZOTP.js +4 -0
  108. package/out/chunk-HAZKDK4M.js +4 -0
  109. package/out/chunk-HOB3YPS5.js +1 -0
  110. package/out/chunk-IYPY47MC.js +1 -0
  111. package/out/chunk-IZ6MYRYB.js +3 -0
  112. package/out/chunk-J2FWBXFV.js +1 -0
  113. package/out/chunk-JCIIBLKR.js +1 -0
  114. package/out/chunk-JFL7WLRV.js +1 -0
  115. package/out/chunk-JJK5OZG2.js +15 -0
  116. package/out/chunk-JMG5DXII.js +2 -0
  117. package/out/chunk-JOXLZXMI.js +1 -0
  118. package/out/chunk-M37X4LCF.js +14 -0
  119. package/out/chunk-M3Y6SLC4.js +1 -0
  120. package/out/chunk-NRPC74AM.js +1 -0
  121. package/out/chunk-NXATZJQ2.js +1 -0
  122. package/out/chunk-OFZYEWBH.js +244 -0
  123. package/out/chunk-OIERSXON.js +1 -0
  124. package/out/chunk-OOJM4CTU.js +1 -0
  125. package/out/chunk-PAD2JHZT.js +1 -0
  126. package/out/chunk-PNHBZGDD.js +1 -0
  127. package/out/chunk-PTFQKLKO.js +1 -0
  128. package/out/chunk-PWFUOLZK.js +17 -0
  129. package/out/chunk-PXK7EU4V.js +1 -0
  130. package/out/chunk-QCOGVL37.js +52 -0
  131. package/out/chunk-QMVOEBWC.js +13 -0
  132. package/out/chunk-QRKFPLA4.js +80 -0
  133. package/out/chunk-R3NZFXVR.js +1 -0
  134. package/out/chunk-R5O6FAW4.js +2 -0
  135. package/out/chunk-RRBIJL2B.js +1 -0
  136. package/out/chunk-SYXT3SFP.js +2 -0
  137. package/out/chunk-TOXMUOIW.js +5 -0
  138. package/out/chunk-TUII34K2.js +1 -0
  139. package/out/chunk-UCP3JRE2.js +1 -0
  140. package/out/chunk-VFWMQ3LG.js +2 -0
  141. package/out/chunk-VRX2APNA.js +9 -0
  142. package/out/chunk-W3QFV4SP.js +3 -0
  143. package/out/chunk-W6VOKW2N.js +12 -0
  144. package/out/chunk-WCPJDAYA.js +10 -0
  145. package/out/chunk-WMFDQS2L.js +11 -0
  146. package/out/chunk-WREU7JAG.js +1 -0
  147. package/out/chunk-Y5ZHFNBD.js +2 -0
  148. package/out/chunk-YF4M5OCI.js +1 -0
  149. package/out/chunk-Z667U2UJ.js +1 -0
  150. package/out/chunk-ZQHLECTI.js +1 -0
  151. package/out/chunk-ZQNEWVGG.js +1 -0
  152. package/out/client-managed-import.js +4 -0
  153. package/out/client-managed.js +34 -0
  154. package/out/client-sync.js +11 -17
  155. package/out/compare.js +40 -0
  156. package/out/dialogs.js +40 -0
  157. package/out/github-issue-authorized.html +3 -0
  158. package/out/github-issue-authorized.js +1 -0
  159. package/out/graph.js +19 -4
  160. package/out/index.html +106 -8
  161. package/out/prism.js +14 -10
  162. package/out/scan.js +2 -0
  163. package/out/stasis.svg +20 -0
  164. package/out/terminal.js +366 -39
  165. package/out/view.css +1 -1
  166. package/out/view.js +19 -144
  167. package/package.json +383 -63
  168. package/risk/actions/findings.js +161 -0
  169. package/risk/actions/resolve.js +250 -0
  170. package/risk/actions/scripts/commands.js +182 -0
  171. package/risk/actions/scripts/grade.js +113 -0
  172. package/risk/actions/scripts/packages.js +123 -0
  173. package/risk/actions/scripts/shell.js +169 -0
  174. package/risk/actions/uses.js +76 -0
  175. package/risk/actions/workflow.js +110 -0
  176. package/risk/files/characters.js +196 -0
  177. package/risk/files/hosts.js +205 -0
  178. package/risk/files/readability.js +177 -0
  179. package/risk/files/runs-code.js +615 -0
  180. package/risk/files/script.js +118 -0
  181. package/risk/files/stamps.js +47 -0
  182. package/risk/index.d.ts +272 -0
  183. package/risk/index.js +11 -0
  184. package/risk/npm/assess.js +285 -0
  185. package/risk/npm/combined.js +68 -0
  186. package/risk/npm/compare.js +257 -0
  187. package/risk/npm/dependencies.js +172 -0
  188. package/risk/npm/diff.js +79 -0
  189. package/risk/npm/downloads.js +84 -0
  190. package/risk/npm/files.js +445 -0
  191. package/risk/npm/held.js +63 -0
  192. package/risk/npm/install-scripts.js +34 -0
  193. package/risk/npm/malware.js +38 -0
  194. package/risk/npm/manifest.js +65 -0
  195. package/risk/npm/new-dependency.js +60 -0
  196. package/risk/npm/old-version.js +108 -0
  197. package/risk/npm/registry.js +390 -0
  198. package/risk/npm/release.js +85 -0
  199. package/risk/npm/score.js +59 -0
  200. package/risk/npm/specs.js +124 -0
  201. package/risk/npm/tarball.js +96 -0
  202. package/server-common/database-config.ts +16 -0
  203. package/server-common/initialize.ts +18 -0
  204. package/server-common/npm-advisories.ts +101 -0
  205. package/{server → server-common}/origin.ts +5 -5
  206. package/server-common/reap.ts +48 -0
  207. package/server-common/scan-config.ts +19 -0
  208. package/server-common/standalone.ts +29 -0
  209. package/server-common/storage-crypto.ts +182 -0
  210. package/server-common/storage-log.ts +38 -0
  211. package/server-common/vercel-blob.ts +103 -0
  212. package/server-e2e/app.ts +487 -0
  213. package/{server → server-e2e}/bus-receiver.ts +2 -1
  214. package/{server → server-e2e}/cli.js +9 -4
  215. package/{server → server-e2e}/config.ts +50 -42
  216. package/{server → server-e2e}/db-neon.ts +2 -2
  217. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  218. package/{server → server-e2e}/db-stmt.ts +2 -2
  219. package/{server → server-e2e}/db.ts +7 -7
  220. package/{server → server-e2e}/http.ts +44 -13
  221. package/{server → server-e2e}/hub.ts +40 -9
  222. package/server-e2e/index.ts +17 -0
  223. package/server-e2e/lifecycle.ts +95 -0
  224. package/{server → server-e2e}/neon-driver.ts +2 -2
  225. package/{server → server-e2e}/npm-proxy.ts +12 -145
  226. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  227. package/{server → server-e2e}/objstore/blob.ts +1 -1
  228. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  229. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  230. package/{server → server-e2e}/objstore/init.ts +19 -27
  231. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  232. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  233. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  234. package/{server → server-e2e}/objstore/rest.ts +3 -3
  235. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  236. package/{server → server-e2e}/objstore/store.ts +7 -7
  237. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  238. package/{server → server-e2e}/pubsub.ts +12 -9
  239. package/{server → server-e2e}/sign.ts +4 -4
  240. package/{server → server-e2e}/sse-server.ts +60 -33
  241. package/{server → server-e2e}/static.ts +31 -21
  242. package/{server → server-e2e}/sync-handlers.ts +64 -30
  243. package/{server → server-e2e}/ws-server.ts +20 -9
  244. package/server-managed/activity.ts +238 -0
  245. package/server-managed/agent-merges.ts +109 -0
  246. package/server-managed/app-agents.ts +23 -0
  247. package/server-managed/avatar-store.ts +13 -0
  248. package/server-managed/blob-store.ts +26 -0
  249. package/server-managed/brotli.ts +10 -0
  250. package/server-managed/bundle-advisories.ts +103 -0
  251. package/server-managed/bundle-advisory-inventory.ts +77 -0
  252. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  253. package/server-managed/bundle-build-diagnostics.js +23 -0
  254. package/server-managed/bundle-build-leases.ts +41 -0
  255. package/server-managed/bundle-build-worker.js +238 -0
  256. package/server-managed/bundle-build.ts +240 -0
  257. package/server-managed/bundle-cache.ts +199 -0
  258. package/server-managed/bundle-catalog.ts +29 -0
  259. package/server-managed/bundle-commits.ts +133 -0
  260. package/server-managed/bundle-dependency-reviews.ts +68 -0
  261. package/server-managed/bundle-store.ts +24 -0
  262. package/server-managed/bundle-summary-cache.ts +139 -0
  263. package/server-managed/bundle-validation.ts +33 -0
  264. package/server-managed/bundle.ts +119 -0
  265. package/server-managed/cache-storage.ts +20 -0
  266. package/server-managed/cli.js +21 -0
  267. package/server-managed/combined.ts +43 -0
  268. package/server-managed/comments.ts +138 -0
  269. package/server-managed/commit-coauthors.ts +105 -0
  270. package/server-managed/commit-lockfiles.ts +77 -0
  271. package/server-managed/comparison.ts +50 -0
  272. package/server-managed/config.ts +163 -0
  273. package/server-managed/content-access.ts +15 -0
  274. package/server-managed/crypto.ts +25 -0
  275. package/server-managed/db-methods.ts +1877 -0
  276. package/server-managed/db-neon.ts +388 -0
  277. package/server-managed/db-schema.ts +253 -0
  278. package/server-managed/db-table-names.ts +22 -0
  279. package/server-managed/db.ts +146 -0
  280. package/server-managed/dependabot-access.ts +61 -0
  281. package/server-managed/dependabot-alerts.ts +180 -0
  282. package/server-managed/dependency-review-comments.ts +92 -0
  283. package/server-managed/dependency-reviews.ts +363 -0
  284. package/server-managed/github-accounts.ts +59 -0
  285. package/server-managed/github-actions.ts +71 -0
  286. package/server-managed/github-app.ts +347 -0
  287. package/server-managed/github-errors.ts +70 -0
  288. package/server-managed/github-graphql.ts +42 -0
  289. package/server-managed/github-issue-links.ts +264 -0
  290. package/server-managed/github-issue-oauth.ts +30 -0
  291. package/server-managed/github-issues.ts +157 -0
  292. package/server-managed/github-link-oauth.ts +56 -0
  293. package/server-managed/github-links.ts +204 -0
  294. package/server-managed/github-metadata.ts +213 -0
  295. package/server-managed/github-oauth.ts +264 -0
  296. package/server-managed/github-pulls.ts +257 -0
  297. package/server-managed/github-requests.ts +179 -0
  298. package/server-managed/github-users.ts +30 -0
  299. package/server-managed/github-values.ts +26 -0
  300. package/server-managed/history-windows.ts +172 -0
  301. package/server-managed/http-response.ts +76 -0
  302. package/server-managed/http.ts +5796 -0
  303. package/server-managed/import-triage.ts +51 -0
  304. package/server-managed/index.ts +204 -0
  305. package/server-managed/kept-briefly.ts +37 -0
  306. package/server-managed/kept.ts +28 -0
  307. package/server-managed/link-reports.ts +149 -0
  308. package/server-managed/listed-activity.ts +39 -0
  309. package/server-managed/locked-packages.ts +152 -0
  310. package/server-managed/lockfile-scope.ts +49 -0
  311. package/server-managed/lru.ts +30 -0
  312. package/server-managed/managed-issues.ts +92 -0
  313. package/server-managed/management-catalog.ts +45 -0
  314. package/server-managed/management.ts +110 -0
  315. package/server-managed/npm-delta-worker.js +23 -0
  316. package/server-managed/npm-delta.ts +159 -0
  317. package/server-managed/npm-insights.ts +455 -0
  318. package/server-managed/npm-kept.ts +234 -0
  319. package/server-managed/npm-loads.ts +259 -0
  320. package/server-managed/npm-manifest.ts +117 -0
  321. package/server-managed/npm-packages.ts +462 -0
  322. package/server-managed/npm-patch.ts +317 -0
  323. package/server-managed/npm-provenance.ts +127 -0
  324. package/server-managed/npm-risk.ts +287 -0
  325. package/server-managed/object-storage-disk.ts +147 -0
  326. package/server-managed/object-storage-vercel.ts +71 -0
  327. package/server-managed/object-storage.ts +82 -0
  328. package/server-managed/package-entry-points.ts +79 -0
  329. package/server-managed/pretty-print.ts +425 -0
  330. package/server-managed/public-workspace.ts +242 -0
  331. package/server-managed/pull-comment-reviews.ts +161 -0
  332. package/server-managed/pull-dependencies.ts +340 -0
  333. package/server-managed/pull-dependency-reviews.ts +327 -0
  334. package/server-managed/pull-reviews.ts +202 -0
  335. package/server-managed/queue.ts +53 -0
  336. package/server-managed/release-commits.ts +85 -0
  337. package/server-managed/rename-diff-worker.js +26 -0
  338. package/server-managed/rename-diff.ts +236 -0
  339. package/server-managed/repo-path.ts +21 -0
  340. package/server-managed/report-migration.ts +32 -0
  341. package/server-managed/report-query.ts +10 -0
  342. package/server-managed/report-response.ts +16 -0
  343. package/server-managed/report-sources.ts +181 -0
  344. package/server-managed/report-store.ts +77 -0
  345. package/server-managed/repository-actions.ts +220 -0
  346. package/server-managed/repository-agents.ts +422 -0
  347. package/server-managed/repository-aliases.ts +85 -0
  348. package/server-managed/repository-browser.ts +303 -0
  349. package/server-managed/repository-changes.ts +280 -0
  350. package/server-managed/repository-code.ts +215 -0
  351. package/server-managed/repository-dependency-reviews.ts +159 -0
  352. package/server-managed/repository-discovery.ts +83 -0
  353. package/server-managed/repository-history.ts +428 -0
  354. package/server-managed/repository-issues.ts +224 -0
  355. package/server-managed/repository-policy.ts +27 -0
  356. package/server-managed/repository-pulls.ts +207 -0
  357. package/server-managed/repository-pulse.ts +477 -0
  358. package/server-managed/repository-risk-assess.ts +108 -0
  359. package/server-managed/repository-risk-audit.ts +78 -0
  360. package/server-managed/repository-risk-read.ts +170 -0
  361. package/server-managed/repository-risk.ts +483 -0
  362. package/server-managed/repository-squashes.ts +160 -0
  363. package/server-managed/repository-stamp.ts +41 -0
  364. package/server-managed/request-timing.ts +63 -0
  365. package/server-managed/reviewed-dependencies.ts +149 -0
  366. package/server-managed/revisions.ts +35 -0
  367. package/server-managed/scan-downloads.ts +87 -0
  368. package/server-managed/session.ts +132 -0
  369. package/server-managed/slugs.ts +38 -0
  370. package/server-managed/solidity-entry-points.ts +71 -0
  371. package/server-managed/sql-postgres.ts +34 -0
  372. package/server-managed/sql.ts +107 -0
  373. package/server-managed/stasis-config.ts +55 -0
  374. package/server-managed/static.ts +28 -0
  375. package/server-managed/storage-command.ts +16 -0
  376. package/server-managed/storage-db.ts +183 -0
  377. package/server-managed/storage-encryption.ts +288 -0
  378. package/server-managed/storage-maintenance.ts +259 -0
  379. package/server-managed/storage-payload.ts +121 -0
  380. package/server-managed/storage-stores.ts +91 -0
  381. package/server-managed/storage.ts +82 -0
  382. package/server-managed/team-app-summaries.ts +54 -0
  383. package/server-managed/team-app.ts +154 -0
  384. package/server-managed/team-catalog.ts +7 -0
  385. package/server-managed/team-feed.ts +180 -0
  386. package/server-managed/team-npm-scopes.ts +103 -0
  387. package/server-managed/team-reports.ts +351 -0
  388. package/server-managed/triage-response.ts +16 -0
  389. package/server-managed/type-only-proof.js +108 -0
  390. package/server-managed/type-only-worker.js +31 -0
  391. package/server-managed/type-only.ts +115 -0
  392. package/server-managed/uploads.ts +106 -0
  393. package/server-managed/upstream-cache.ts +250 -0
  394. package/server-managed/view-as.ts +58 -0
  395. package/server-managed/worker-turns.ts +76 -0
  396. package/server-managed/workspace-shares.ts +170 -0
  397. package/server.ts +70 -0
  398. package/server/index.ts +0 -480
  399. package/server/lifecycle.ts +0 -208
  400. /package/{LICENSE → LICENSE-MIT} +0 -0
  401. /package/{server → server-e2e}/auth.ts +0 -0
  402. /package/{server → server-e2e}/config.example.json +0 -0
  403. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  404. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  405. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  406. /package/{server → server-e2e}/peer.ts +0 -0
  407. /package/{server → server-e2e}/sse-session.ts +0 -0
  408. /package/{server → server-e2e}/util.ts +0 -0
  409. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,462 @@
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 NPM_TOKEN on the server, and a reader with access to it: an admin or
6
+ // manager, or a member of a visible team listing its scope (team-npm-scopes.ts).
7
+ // For everyone else, a version is public only when the registry answers for
8
+ // it without credentials, asked on every request and never from a cache:
9
+ // upstream's caches, which bundle builds fill using the token, hold no
10
+ // answer here. Its tarball may come from them (npm-loads.ts), as only bytes
11
+ // matching the integrity that anonymous answer gives are served; else it is
12
+ // read without credentials too, and held to that integrity.
13
+ import { Buffer } from 'node:buffer'
14
+ import { createHash } from 'node:crypto'
15
+ import { rm } from 'node:fs/promises'
16
+ import { resolve } from 'node:path'
17
+ import { ArchiveError, type Entry, unpack } from '@preventive/archive/tar.js'
18
+ import { isExactVersion } from '@preventive/upstream/semver.js'
19
+ import { isNpmPackageName, isNpmPackageSpec, npmPackageScope } from '../common/managed/npm-packages.js'
20
+ import type { Role } from '../common/managed/roles.ts'
21
+ import { npmManifest, npmVersionFields, plainObject, stringRecord } from './npm-manifest.ts'
22
+ import { keepJson, readKeptJson, upstreamCachePath } from './upstream-cache.ts'
23
+
24
+ export const NPM_REGISTRY = 'https://registry.npmjs.org'
25
+ const VERSION_DOCUMENT_BYTES = 8 * 1024 * 1024
26
+ // Abbreviated packuments of packages with thousands of versions run to tens of MiB.
27
+ const PACKUMENT_BYTES = 64 * 1024 * 1024
28
+ // What registry documents being read at once may hold, each counted at its
29
+ // limit until it is read and parsed: four packuments, or 32 version documents.
30
+ const MAX_DOCUMENT_BYTES = 4 * PACKUMENT_BYTES
31
+ // What a package may unpack to: the files' bytes and their count; the tar
32
+ // stream holding them is bounded in npm-loads.ts. A repository directory's
33
+ // are its own (repository-code.ts).
34
+ export const MAX_NPM_PACKAGE_BYTES = 64 * 1024 * 1024
35
+ export const MAX_NPM_PACKAGE_FILES = 20_000
36
+ // The entries its tar stream may hold, read before any is counted as a file:
37
+ // a directory's too, though npm packs none.
38
+ export const MAX_NPM_TAR_ENTRIES = 2 * MAX_NPM_PACKAGE_FILES
39
+ // What the files may take as the viewer's JSON. Escaping grows a text up to
40
+ // six times (a control character becomes `\u0001`), so it is counted before
41
+ // anything is serialized.
42
+ export const MAX_NPM_JSON_LENGTH = 96 * 1024 * 1024
43
+ export class NpmPackageError extends Error {
44
+ status: number
45
+ constructor(status: number, code: string) { super(code); this.status = status }
46
+ }
47
+
48
+ // Who reads, as the session has it now: the role, and the scopes of the
49
+ // visible teams they are a member of, where those count (npmScopesCount).
50
+ export interface NpmReader { role: Role; scopes: ReadonlySet<string>; userId: string }
51
+
52
+ // Whether a reader may have a package read with the server's token.
53
+ export function canReadPrivateNpm(reader: NpmReader, name: string): boolean {
54
+ if (reader.role === 'admin' || reader.role === 'manage') return true
55
+ const scope = npmPackageScope(name)
56
+ return scope !== null && reader.scopes.has(scope)
57
+ }
58
+
59
+ // Whether a reader's team scopes count for any of `names`, as
60
+ // canReadPrivateNpm reads them: a scoped one, read by someone below manager.
61
+ export const npmScopesCount = (role: Role, names: readonly string[]): boolean =>
62
+ role !== 'admin' && role !== 'manage' && names.some(name => npmPackageScope(name) !== null)
63
+
64
+ export const npmToken = () => process.env['NPM_TOKEN'] || null
65
+
66
+ // Whether a read of `name` that npm answers none anonymously is asked again
67
+ // with the server's token: by a reader with private access (`privileged`),
68
+ // where there is a token and the package is scoped, as npm's private packages
69
+ // always are. Else the anonymous answer is the reader's.
70
+ export const npmTokenReads = (name: string, privileged: boolean): boolean => privileged && npmToken() !== null && npmPackageScope(name) !== null
71
+
72
+ function registryUrl(name: string, spec?: string): string {
73
+ return `${NPM_REGISTRY}/${name}${spec === undefined ? '' : `/${encodeURIComponent(spec)}`}`
74
+ }
75
+
76
+ // What an upstream (npm's registry and APIs, Socket, GitHub) answers, read
77
+ // whole: null where it says it has none (`absent`, 404 unless said). Asked
78
+ // without redirects, and given up on after `ms`, 30 seconds unless said, or
79
+ // once `signal` aborts, its abort rethrown as it is; a 502 where it can't be
80
+ // asked, answers otherwise or stops, and `upstream-too-large` past `limit`
81
+ // bytes (readLimited). `answered` sees the response first, its status and
82
+ // headers.
83
+ export async function askUpstream(url: string, { limit, ms = 30_000, signal, absent = [404], answered, ...init }: Omit<RequestInit, 'signal'>
84
+ & { limit: number; ms?: number; signal?: AbortSignal; absent?: number[]; answered?: (res: Response) => void }): Promise<Buffer | null> {
85
+ try {
86
+ const res = await fetch(url, { ...init, redirect: 'error', signal: AbortSignal.any([AbortSignal.timeout(ms), ...signal ? [signal] : []]) })
87
+ answered?.(res)
88
+ if (absent.includes(res.status)) { await res.body?.cancel(); return null }
89
+ if (!res.ok) { await res.body?.cancel(); throw new NpmPackageError(502, 'upstream-unavailable') }
90
+ return await readLimited(res, limit)
91
+ } catch (err) {
92
+ if (signal?.aborted || err instanceof NpmPackageError) throw err
93
+ throw new NpmPackageError(502, 'upstream-unavailable')
94
+ }
95
+ }
96
+
97
+ // The same, read as JSON (by `parse`, as one line of ndjson): a 502
98
+ // `upstream-invalid` where it isn't.
99
+ export async function askUpstreamJson(url: string, options: Parameters<typeof askUpstream>[1], parse = (text: string): unknown => JSON.parse(text)): Promise<unknown> {
100
+ const body = await askUpstream(url, options)
101
+ if (body === null) return null
102
+ try { return parse(body.toString('utf8')) } catch { throw new NpmPackageError(502, 'upstream-invalid') }
103
+ }
104
+
105
+ export async function readLimited(res: Response, limit: number): Promise<Buffer> {
106
+ const declared = Number(res.headers.get('content-length'))
107
+ if (declared > limit) { await res.body?.cancel(); throw new NpmPackageError(502, 'upstream-too-large') }
108
+ const chunks: Uint8Array[] = []
109
+ let size = 0
110
+ for await (const chunk of res.body ?? []) {
111
+ size += chunk.byteLength
112
+ if (size > limit) throw new NpmPackageError(502, 'upstream-too-large')
113
+ chunks.push(chunk)
114
+ }
115
+ return Buffer.concat(chunks)
116
+ }
117
+
118
+ // A registry document as npm wrote it, read as the JSON object it is: a 502
119
+ // `upstream-invalid` where it isn't one.
120
+ function documentOf(body: Buffer): Record<string, unknown> {
121
+ let json: unknown
122
+ try { json = JSON.parse(body.toString('utf8')) } catch { throw new NpmPackageError(502, 'upstream-invalid') }
123
+ if (!plainObject(json)) throw new NpmPackageError(502, 'upstream-invalid')
124
+ return json
125
+ }
126
+
127
+ // A registry document, or null where the registry has none for this caller:
128
+ // 404, or 401/403 as it answers some private packages asked anonymously.
129
+ // Credentials go only with `token`; nothing is cached on either side, but for
130
+ // public whole documents (publicWholeDocument).
131
+ async function registryDocument(url: string, { token, accept, limit, signal }: { token: string | null; accept: string; limit: number; signal: AbortSignal }): Promise<Record<string, unknown> | null> {
132
+ const body = await askUpstream(url, { headers: { accept, ...(token ? { authorization: `Bearer ${token}` } : {}) }, limit, signal, absent: [401, 403, 404] })
133
+ return body === null ? null : documentOf(body)
134
+ }
135
+
136
+ // Where public packages' whole documents are kept, off Vercel: the upstream
137
+ // cache dir, set at startup (index.ts); null keeps none.
138
+ let documentCache: string | null = null
139
+ export const setNpmDocumentCache = (dir: string | null) => { documentCache = dir === null ? null : resolve(dir) }
140
+
141
+ // A package's whole document as npm answers anyone (`url` its own), kept on
142
+ // disk where the server keeps them (setNpmDocumentCache) with npm's ETag, and
143
+ // asked for again each time with it: npm answers 304, and nothing more, while
144
+ // it is unchanged. Null where npm has none for anyone, nothing then kept.
145
+ async function publicWholeDocument(name: string, url: string, { limit, signal }: { limit: number; signal: AbortSignal }): Promise<Record<string, unknown> | null> {
146
+ const path = documentCache === null ? null : upstreamCachePath(documentCache, 'npm/packuments', `${name}.json.gz`)
147
+ const kept = path === null ? null : await readKeptJson(path, limit)
148
+ let etag: string | null = null, status = 0
149
+ const body = await askUpstream(url, { headers: { accept: 'application/json', ...kept && { 'if-none-match': kept.etag } }, limit, signal, absent: [304, 401, 403, 404],
150
+ answered: res => { status = res.status; etag = res.headers.get('etag') } })
151
+ if (status === 304 && kept) return kept.json
152
+ if (body === null) {
153
+ if (path !== null && kept) await rm(path, { force: true }).catch(() => {})
154
+ return null
155
+ }
156
+ const json = documentOf(body)
157
+ if (path !== null && etag !== null) await keepJson(path, etag, body)
158
+ return json
159
+ }
160
+
161
+ // Whole documents being asked of npm as anyone asks, by URL and limit:
162
+ // readers asking for one meanwhile share it, as opening a version asks for
163
+ // its package's for its versions, its advisories and its risk at once; each
164
+ // gives up on it alone once its own signal aborts, and it is given up on once
165
+ // they all have. None is asked with the token. Read alike by every reader,
166
+ // none changing it.
167
+ const wholeAsks = new Map<string, { asked: Promise<Record<string, unknown> | null>; controller: AbortController; readers: number }>()
168
+
169
+ function sharedWholeDocument(name: string, url: string, { limit, signal }: { limit: number; signal: AbortSignal }): Promise<Record<string, unknown> | null> {
170
+ if (signal.aborted) return Promise.reject(signal.reason)
171
+ const key = `${url} ${limit}`
172
+ let ask = wholeAsks.get(key)
173
+ if (!ask) {
174
+ const controller = new AbortController()
175
+ const created = { asked: publicWholeDocument(name, url, { limit, signal: controller.signal }), controller, readers: 0 }
176
+ const settle = () => { if (wholeAsks.get(key) === created) wholeAsks.delete(key) }
177
+ created.asked.then(settle, settle)
178
+ wholeAsks.set(key, ask = created)
179
+ }
180
+ const held = ask
181
+ held.readers++
182
+ return new Promise((answer, fail) => {
183
+ let left = false
184
+ const leave = () => {
185
+ if (left) return false
186
+ left = true
187
+ held.readers--
188
+ signal.removeEventListener('abort', onAbort)
189
+ return true
190
+ }
191
+ const onAbort = () => {
192
+ if (!leave()) return
193
+ if (held.readers === 0) {
194
+ if (wholeAsks.get(key) === held) wholeAsks.delete(key)
195
+ held.controller.abort(signal.reason)
196
+ }
197
+ fail(signal.reason)
198
+ }
199
+ const answered = (json: Record<string, unknown> | null) => { if (leave()) answer(json) }
200
+ const failed = (err: unknown) => { if (leave()) fail(err) }
201
+ signal.addEventListener('abort', onAbort, { once: true })
202
+ held.asked.then(answered, failed)
203
+ })
204
+ }
205
+
206
+ // Asked anonymously first, unless its caller knows npm has none for anyone
207
+ // (`anonymous` false): a reader without private access stops there. One
208
+ // with it asks again with the token where npmTokenReads says so, and the
209
+ // answer is private. A whole document (`whole`) anyone may read is kept
210
+ // (publicWholeDocument), and asked once for those asking at once
211
+ // (sharedWholeDocument).
212
+ async function readDocument(name: string, url: string, privileged: boolean,
213
+ { whole = false, anonymous = true, ...options }: { accept: string; limit: number; signal: AbortSignal; whole?: boolean; anonymous?: boolean }) {
214
+ const open = anonymous ? whole ? await sharedWholeDocument(name, url, options) : await registryDocument(url, { ...options, token: null }) : null
215
+ if (open) return { json: open, private: false }
216
+ if (!npmTokenReads(name, privileged)) return null
217
+ const json = await registryDocument(url, { ...options, token: npmToken() })
218
+ return json ? { json, private: true } : null
219
+ }
220
+
221
+ let documentBytes = 0
222
+
223
+ // A `spare` read, one no reader waits on, is made only where it leaves room
224
+ // for two of the largest documents more: readers' own reads come first.
225
+ async function withDocumentBudget<T>(limit: number, read: () => Promise<T>, spare = false): Promise<T> {
226
+ if (documentBytes + limit + (spare ? 2 * PACKUMENT_BYTES : 0) > MAX_DOCUMENT_BYTES) throw new NpmPackageError(429, 'npm-busy')
227
+ documentBytes += limit
228
+ try { return await read() } finally { documentBytes -= limit }
229
+ }
230
+
231
+ export interface NpmVersionDocument {
232
+ name: string
233
+ version: string
234
+ private: boolean
235
+ // `shasum`, the tarball's sha1 in hex, where npm tells it: held, with the
236
+ // integrity, to the tarball its files are read from (npm-loads.ts).
237
+ dist: { tarball: string; integrity: string; shasum: string | null; unpackedSize: number | null; fileCount: number | null }
238
+ manifest: Record<string, unknown>
239
+ }
240
+
241
+ const count = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0 ? value as number : null
242
+
243
+ // The version `json`, a document of package `name`, tells of.
244
+ function versionDocument(name: string, json: Record<string, unknown>, isPrivate: boolean): NpmVersionDocument {
245
+ const dist = json['dist']
246
+ if (json['name'] !== name || typeof json['version'] !== 'string' || !isNpmPackageSpec(json['version']) || !plainObject(dist)
247
+ || typeof dist['tarball'] !== 'string' || typeof dist['integrity'] !== 'string'
248
+ || (dist['shasum'] !== undefined && typeof dist['shasum'] !== 'string')) throw new NpmPackageError(502, 'upstream-invalid')
249
+ return {
250
+ name, version: json['version'], private: isPrivate,
251
+ dist: { tarball: dist['tarball'], integrity: dist['integrity'], shasum: typeof dist['shasum'] === 'string' ? dist['shasum'] : null,
252
+ unpackedSize: count(dist['unpackedSize']), fileCount: count(dist['fileCount']) },
253
+ manifest: npmManifest(json),
254
+ }
255
+ }
256
+
257
+ // Where public versions' documents are kept, of the fields read of them
258
+ // (npm-manifest.ts npmVersionFields), as the database keeps them (npm-kept.ts).
259
+ export interface NpmVersionStore {
260
+ read(name: string, version: string): Promise<{ at: number; json: Record<string, unknown> } | null>
261
+ // Those of `versions` kept, by `name@version`, in one read.
262
+ readMany?(versions: { name: string; version: string }[]): Promise<Map<string, { at: number; json: Record<string, unknown> }>>
263
+ write(name: string, version: string, json: Record<string, unknown>): Promise<void>
264
+ }
265
+
266
+ // The version a spec names, a dist-tag resolved by the registry, with its
267
+ // dist. Null where the registry has none for this reader. With `store`, an
268
+ // exact version kept there for less than a day (VERSION_KEPT_MS) is read from
269
+ // it, not asked of npm, and a public one npm answers is kept. npm never
270
+ // changes a version's files, but its document can change: a deprecation, the
271
+ // package made private (a scoped one can be), the version removed (which whoever
272
+ // reads it from a store learns elsewhere too: risk does). A day bounds each.
273
+ // One kept with no shasum, as none was before it was kept (npmVersionFields),
274
+ // is asked of npm again, which tells one of each version.
275
+ export const VERSION_KEPT_MS = 24 * 60 * 60_000
276
+ export function readNpmVersion(name: string, spec: string, privileged: boolean, signal: AbortSignal, store?: NpmVersionStore): Promise<NpmVersionDocument | null> {
277
+ if (!isNpmPackageName(name) || !isNpmPackageSpec(spec)) return Promise.reject(new NpmPackageError(400, 'bad-package'))
278
+ // A kept one is read within the same budget as npm's answer.
279
+ return withDocumentBudget(VERSION_DOCUMENT_BYTES, async () => {
280
+ const kept = store && isExactVersion(spec) ? await store.read(name, spec) : null
281
+ const keptDist = kept?.json['dist']
282
+ if (kept && Date.now() - kept.at < VERSION_KEPT_MS && plainObject(keptDist) && typeof keptDist['shasum'] === 'string') {
283
+ try { return versionDocument(name, kept.json, false) } catch {}
284
+ }
285
+ const found = await readDocument(name, registryUrl(name, spec), privileged, { accept: 'application/json', limit: VERSION_DOCUMENT_BYTES, signal })
286
+ if (!found) return null
287
+ const doc = versionDocument(name, found.json, found.private)
288
+ if (store && !found.private) await store.write(name, doc.version, npmVersionFields(found.json))
289
+ return doc
290
+ })
291
+ }
292
+
293
+ // `store`, where it reads many at once, with the exact ones of `versions`
294
+ // read from it in one read, for readNpmVersion to read each of those from as
295
+ // it asks: a version and the one it is compared with, read together.
296
+ export function readTogether(store: NpmVersionStore, versions: { name: string; version: string }[]): NpmVersionStore {
297
+ const exact = versions.filter(({ version }) => isExactVersion(version))
298
+ if (!store.readMany || exact.length < 2) return store
299
+ const keys = new Set(exact.map(({ name, version }) => `${name}@${version}`))
300
+ const kept = store.readMany(exact)
301
+ return { ...store, async read(name, version) {
302
+ const key = `${name}@${version}`
303
+ return keys.has(key) ? (await kept).get(key) ?? null : store.read(name, version)
304
+ } }
305
+ }
306
+
307
+ // The package's dist-tags and versions, newest published first, from its
308
+ // abbreviated document; with `times`, from its whole one, which alone has
309
+ // when each was published, `times` by version (ISO dates), and `created`,
310
+ // when its first version was, one since unpublished among them: the earliest
311
+ // time it lists, which npm's own `created` can postdate, as a placeholder's
312
+ // does for a package npm took down. With `spare`, as a read no reader waits
313
+ // on (withDocumentBudget). Null where the registry has none for this reader.
314
+ export function readNpmVersions(name: string, privileged: boolean, signal: AbortSignal, { times = false, spare = false } = {}) {
315
+ if (!isNpmPackageName(name)) return Promise.reject(new NpmPackageError(400, 'bad-package'))
316
+ return withDocumentBudget(PACKUMENT_BYTES, async () => {
317
+ const accept = times ? 'application/json' : 'application/vnd.npm.install-v1+json'
318
+ const found = await readDocument(name, registryUrl(name), privileged, { accept, limit: PACKUMENT_BYTES, signal, whole: times })
319
+ if (!found) return null
320
+ const { json } = found
321
+ if (json['name'] !== name || !plainObject(json['versions'])) throw new NpmPackageError(502, 'upstream-invalid')
322
+ const versions = Object.keys(json['versions']).filter(isNpmPackageSpec).toReversed()
323
+ const distTags = Object.fromEntries(Object.entries(stringRecord(json['dist-tags']) ?? {}).filter(([, version]) => versions.includes(version)))
324
+ const listed = { name, private: found.private, distTags, versions }
325
+ if (!times) return listed
326
+ const time = stringRecord(json['time']) ?? {}
327
+ const published = Object.fromEntries(versions.filter(version => isPublishTime(time[version])).map(version => [version, time[version]!]))
328
+ for (const [version, at] of Object.entries(published)) publishTimes.set(`${name}@${version}`, at)
329
+ while (publishTimes.size > PUBLISH_TIMES) publishTimes.delete(publishTimes.keys().next().value!)
330
+ const listedAt = Object.entries(time).filter(([key, at]) => key !== 'modified' && isPublishTime(at)).map(([, at]) => at)
331
+ const created = listedAt.reduce<string | null>((first, at) => first === null || Date.parse(at) < Date.parse(first) ? at : first, null)
332
+ return { ...listed, times: published, created }
333
+ }, spare)
334
+ }
335
+
336
+ // A package's whole document as npm has it for this reader, for risk
337
+ // (npm-risk.ts), within the bounds and budget every document read here is
338
+ // held to; null where npm has none for this reader, or the name is none npm
339
+ // takes. With `anonymous` false, where npm is known to have none for anyone,
340
+ // it is asked only with the token (readDocument).
341
+ export function readNpmPackument(name: string, privileged: boolean, signal: AbortSignal, { anonymous = true } = {}): Promise<Record<string, unknown> | null> {
342
+ if (!isNpmPackageName(name)) return Promise.resolve(null)
343
+ return withDocumentBudget(PACKUMENT_BYTES, async () => (await readDocument(name, registryUrl(name), privileged,
344
+ { accept: 'application/json', limit: PACKUMENT_BYTES, signal, whole: true, anonymous }))?.json ?? null)
345
+ }
346
+
347
+ const isPublishTime = (value: string | undefined) => typeof value === 'string' && value.length <= 40 && !Number.isNaN(Date.parse(value))
348
+
349
+ // When each version was published, by `name@version`, as whole documents read
350
+ // with `times` have said: a version keeps its time once published, so it is
351
+ // kept for as long as the server runs, the first noted going first past a
352
+ // bound, and answered only with the version, once its reader's access is.
353
+ const PUBLISH_TIMES = 100_000
354
+ const publishTimes = new Map<string, string>()
355
+
356
+ // Where public versions' publish times are kept beyond the instance, as the
357
+ // database keeps them (npm-kept.ts npmPublishTimeStore).
358
+ export interface NpmPublishTimeStore {
359
+ read(name: string, version: string): Promise<string | null>
360
+ write(name: string, version: string, at: string): Promise<void>
361
+ }
362
+
363
+ // When `doc` was published: as noted here, else as `store` keeps a public
364
+ // version's, so that another instance, or this one restarted, has it before
365
+ // it reads the whole document again. The store is read once, at once, beside
366
+ // whatever its caller reads meanwhile, a failure read as none; `read` looks
367
+ // here again as it is asked, as the whole document read meanwhile may have
368
+ // noted it by then, and `keep` keeps there the time noted here where it read
369
+ // none.
370
+ export function npmPublishTime(doc: Pick<NpmVersionDocument, 'name' | 'version' | 'private'>, store?: NpmPublishTimeStore) {
371
+ const noted = () => publishTimes.get(`${doc.name}@${doc.version}`) ?? null
372
+ const kept = store && !doc.private ? store.read(doc.name, doc.version).catch(() => null) : Promise.resolve(null)
373
+ return {
374
+ read: async (): Promise<string | null> => noted() ?? await kept ?? noted(),
375
+ async keep() {
376
+ const at = noted()
377
+ if (at !== null && store && !doc.private && await kept === null) await store.write(doc.name, doc.version, at)
378
+ },
379
+ }
380
+ }
381
+
382
+ export interface NpmPackageFile { path: string; bytes: Uint8Array }
383
+
384
+ // Paths in the order a package's files are read in (readNpmTar), and
385
+ // Compare's: by their UTF-16 code units, as a plain sort orders them.
386
+ export const pathOrder = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
387
+
388
+ // How a tar stream is read (readNpmTar): how far its symlinks may climb above
389
+ // it, and the entries, files and bytes it may hold, a package's unless given.
390
+ export interface TarReading { symlinksAbove?: number; maxEntries?: number; maxFiles?: number; maxBytes?: number }
391
+
392
+ // The regular files of a tar stream, by package path: npm drops the first
393
+ // component (`package/`, or whatever the archive used), and a file at the top
394
+ // is not extracted. The stream is read by @preventive/archive, which refuses
395
+ // one malformed, a name or a symlink that would climb out of it -- a symlink
396
+ // past `symlinksAbove` levels above it, none unless given -- and a name
397
+ // repeated as another entry, and gives up past `maxEntries` before reading
398
+ // on; a file under another top directory at the same path replaces an
399
+ // earlier one, as extraction would. Directories, links and devices hold no
400
+ // file content and are skipped.
401
+ export function readNpmTar(tar: Uint8Array, { symlinksAbove = 0, maxEntries = MAX_NPM_TAR_ENTRIES, maxFiles = MAX_NPM_PACKAGE_FILES,
402
+ maxBytes = MAX_NPM_PACKAGE_BYTES }: TarReading = {}): NpmPackageFile[] {
403
+ let entries: Entry[]
404
+ try { entries = unpack(tar, { maxEntries, symlinksAbove }) }
405
+ catch (err) {
406
+ if (err instanceof ArchiveError) throw err.limited ? new NpmPackageError(413, 'package-too-large') : new NpmPackageError(422, 'bad-tarball')
407
+ throw err
408
+ }
409
+ const files = new Map<string, Uint8Array>()
410
+ let total = 0
411
+ for (const { name, type, data } of entries) {
412
+ const slash = name.indexOf('/')
413
+ if ((type !== 'file' && type !== 'contiguous-file') || slash === -1) continue
414
+ const path = name.slice(slash + 1)
415
+ total += data.length - (files.get(path)?.length ?? 0)
416
+ files.set(path, data)
417
+ if (files.size > maxFiles || total > maxBytes) throw new NpmPackageError(413, 'package-too-large')
418
+ }
419
+ return [...files].map(([path, bytes]) => ({ path, bytes })).toSorted((a, b) => pathOrder(a.path, b.path))
420
+ }
421
+
422
+ const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
423
+
424
+ // A file's text, or null for bytes that are not UTF-8 text.
425
+ export function npmFileText(bytes: Uint8Array): string | null {
426
+ if (bytes.includes(0)) return null
427
+ try { return utf8.decode(bytes) } catch { return null }
428
+ }
429
+
430
+ // A string's length in JSON: quotes, backslashes and the control characters
431
+ // with a short escape take two characters, the other control characters six.
432
+ function jsonLength(text: string): number {
433
+ let length = text.length + 2
434
+ for (let i = 0; i < text.length; i++) {
435
+ const code = text.codePointAt(i)!
436
+ if (code === 0x22 || code === 0x5c) length += 1
437
+ else if (code < 0x20) length += code >= 0x08 && code <= 0x0d && code !== 0x0b ? 1 : 5
438
+ }
439
+ return length
440
+ }
441
+
442
+ // A row's brackets, size, null and digest, past its strings.
443
+ const ROW_LENGTH = 80
444
+
445
+ // The files as the viewer gets them: `[path, bytes, text]`, text null for a
446
+ // file that is not UTF-8, which instead carries its bytes' sha256, so a
447
+ // comparison of two versions tells a changed one from an unchanged one. They
448
+ // may take `maxLength` characters of JSON, a package's unless given.
449
+ export function npmFileRows(files: NpmPackageFile[], maxLength = MAX_NPM_JSON_LENGTH): ([string, number, string] | [string, number, null, string])[] {
450
+ let length = 0
451
+ return files.map(({ path, bytes }) => {
452
+ const text = npmFileText(bytes)
453
+ length += ROW_LENGTH + jsonLength(path) + (text === null ? 0 : jsonLength(text))
454
+ if (length > maxLength) throw new NpmPackageError(413, 'package-too-large')
455
+ return text === null ? [path, bytes.byteLength, null, `sha256-${createHash('sha256').update(bytes).digest('base64')}`] : [path, bytes.byteLength, text]
456
+ })
457
+ }
458
+
459
+ // The tarball's filename as `npm pack` writes it.
460
+ export function npmTarballFilename(name: string, version: string): string {
461
+ return `${name.replace(/^@/u, '').replace('/', '-')}-${version}.tgz`
462
+ }