@preventive/triage 1.0.0-alpha.8 → 1.0.0-alpha.81

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 (442) 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 +377 -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 +66 -0
  35. package/common/default-scan-models.ts +36 -0
  36. package/common/dependency-reviews.d.ts +18 -0
  37. package/common/dependency-reviews.js +64 -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 +1 -0
  44. package/common/github-issue-labels.js +11 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +14 -0
  48. package/common/line-diff.js +181 -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 +41 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +385 -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/pretty-json.js +98 -0
  81. package/common/pretty-kinds.js +20 -0
  82. package/common/pretty-print.d.ts +6 -0
  83. package/common/pretty-print.js +36 -0
  84. package/common/pretty-sourcemap.js +70 -0
  85. package/common/repo-commit.d.ts +4 -0
  86. package/common/repo-commit.js +30 -0
  87. package/common/revalidation-conflicts.js +48 -0
  88. package/common/revalidation-input-groups.js +56 -0
  89. package/common/save-error-reason.ts +20 -7
  90. package/common/scan-server.ts +13 -0
  91. package/common/security-links.d.ts +5 -0
  92. package/common/security-links.js +33 -0
  93. package/common/server-info.ts +46 -0
  94. package/common/sourcemap-listing.js +78 -0
  95. package/common/sourcemap-mappings.js +136 -0
  96. package/common/sourcemap-unlist.js +85 -0
  97. package/common/stasis-files.d.ts +5 -0
  98. package/common/stasis-files.js +20 -0
  99. package/common/stasis-tgz.d.ts +6 -0
  100. package/common/stasis-tgz.js +27 -0
  101. package/common/utf8.d.ts +3 -0
  102. package/common/utf8.js +45 -0
  103. package/common/whitespace-insensitive.js +19 -0
  104. package/common/workspace-app.js +91 -0
  105. package/common/workspace-groups.js +176 -0
  106. package/out/activity.js +2 -0
  107. package/out/brotli-fallback.js +3 -3
  108. package/out/chunk-2XUEZHIP.js +28 -0
  109. package/out/chunk-55YIWY3H.js +5 -0
  110. package/out/chunk-563V5VVT.js +266 -0
  111. package/out/chunk-5AVGKFMR.js +1 -0
  112. package/out/chunk-5EAVJAD2.js +3 -0
  113. package/out/chunk-5M2X3QPK.js +6 -0
  114. package/out/chunk-5QWPKTCE.js +40 -0
  115. package/out/chunk-5UJHJWFU.js +4 -0
  116. package/out/chunk-6CCSTJWB.js +1 -0
  117. package/out/chunk-6VOB5WXX.js +2 -0
  118. package/out/chunk-6WMQVUT2.js +3 -0
  119. package/out/chunk-6Y6PZ2BU.js +9 -0
  120. package/out/chunk-74JZTGTO.js +11 -0
  121. package/out/chunk-7BKKYVWR.js +7 -0
  122. package/out/chunk-7C7DWL7I.js +1 -0
  123. package/out/chunk-7HP2VYIC.js +2 -0
  124. package/out/chunk-7YFJUT2P.js +1 -0
  125. package/out/chunk-7YO4QV5P.js +1 -0
  126. package/out/chunk-A4BBBHQU.js +1 -0
  127. package/out/chunk-B64CTMVU.js +4 -0
  128. package/out/chunk-BEKYZCPX.js +14 -0
  129. package/out/chunk-C4Z6ZBXV.js +10 -0
  130. package/out/chunk-CU3FPB3P.js +1 -0
  131. package/out/chunk-DEVAORP2.js +1 -0
  132. package/out/chunk-DOYTKRIR.js +53 -0
  133. package/out/chunk-DUASGS2O.js +8 -0
  134. package/out/chunk-EEJA7JBI.js +13 -0
  135. package/out/chunk-FSU2PLJL.js +1 -0
  136. package/out/chunk-GO7FT4OD.js +1 -0
  137. package/out/chunk-GX5UXWT4.js +1 -0
  138. package/out/chunk-H4FEC57K.js +1 -0
  139. package/out/chunk-ITUKKCCK.js +10 -0
  140. package/out/chunk-IYPY47MC.js +1 -0
  141. package/out/chunk-K4XJHM2T.js +1 -0
  142. package/out/chunk-LBD3M3J6.js +1 -0
  143. package/out/chunk-LVSLM7HB.js +1 -0
  144. package/out/chunk-LVW7WWV4.js +1 -0
  145. package/out/chunk-N57OWFKY.js +15 -0
  146. package/out/chunk-NRPC74AM.js +1 -0
  147. package/out/chunk-OAWQNDAO.js +3 -0
  148. package/out/chunk-OOJM4CTU.js +1 -0
  149. package/out/chunk-PEE47ANR.js +1 -0
  150. package/out/chunk-PKLVXUEI.js +11 -0
  151. package/out/chunk-PLGH63UC.js +2 -0
  152. package/out/chunk-PNHBZGDD.js +1 -0
  153. package/out/chunk-PTFYDJUP.js +1 -0
  154. package/out/chunk-PWFUOLZK.js +17 -0
  155. package/out/chunk-PXK7EU4V.js +1 -0
  156. package/out/chunk-QD3IBSF4.js +7 -0
  157. package/out/chunk-QI66YA4F.js +1 -0
  158. package/out/chunk-QRKFPLA4.js +80 -0
  159. package/out/chunk-R3NZFXVR.js +1 -0
  160. package/out/chunk-R5O6FAW4.js +2 -0
  161. package/out/chunk-RPNO56H2.js +1 -0
  162. package/out/chunk-SSPDMA6D.js +1 -0
  163. package/out/chunk-SZWPYLPC.js +1 -0
  164. package/out/chunk-TUII34K2.js +1 -0
  165. package/out/chunk-UJP4PQJA.js +1 -0
  166. package/out/chunk-UJSJMXEG.js +1 -0
  167. package/out/chunk-UR4WYMIP.js +1 -0
  168. package/out/chunk-VHEXSGGP.js +1 -0
  169. package/out/chunk-VYYUMYVW.js +9 -0
  170. package/out/chunk-WCDYSIKG.js +1 -0
  171. package/out/chunk-WFBVS4QI.js +1 -0
  172. package/out/chunk-XM4RLC4A.js +2 -0
  173. package/out/chunk-ZQHLECTI.js +1 -0
  174. package/out/client-managed-import.js +4 -0
  175. package/out/client-managed.js +37 -0
  176. package/out/client-sync.js +11 -17
  177. package/out/compare.js +26 -0
  178. package/out/dialogs.js +40 -0
  179. package/out/github-issue-authorized.html +3 -0
  180. package/out/github-issue-authorized.js +1 -0
  181. package/out/graph.js +19 -4
  182. package/out/index.html +104 -24
  183. package/out/prism.js +14 -10
  184. package/out/scan.js +2 -0
  185. package/out/stasis.svg +20 -0
  186. package/out/terminal.js +367 -39
  187. package/out/view.css +1 -1
  188. package/out/view.js +19 -147
  189. package/package.json +409 -64
  190. package/risk/actions/findings.js +161 -0
  191. package/risk/actions/resolve.js +287 -0
  192. package/risk/actions/scripts/commands.js +182 -0
  193. package/risk/actions/scripts/grade.js +113 -0
  194. package/risk/actions/scripts/packages.js +123 -0
  195. package/risk/actions/scripts/shell.js +169 -0
  196. package/risk/actions/uses.js +94 -0
  197. package/risk/actions/workflow.js +183 -0
  198. package/risk/files/characters.js +354 -0
  199. package/risk/files/hosts.js +206 -0
  200. package/risk/files/readability.js +185 -0
  201. package/risk/files/runs-code.js +568 -0
  202. package/risk/files/script.js +410 -0
  203. package/risk/files/source-map-link.js +43 -0
  204. package/risk/files/stamps.js +47 -0
  205. package/risk/index.d.ts +294 -0
  206. package/risk/index.js +12 -0
  207. package/risk/npm/assess.js +285 -0
  208. package/risk/npm/combined.js +68 -0
  209. package/risk/npm/compare.js +236 -0
  210. package/risk/npm/dependencies.js +172 -0
  211. package/risk/npm/diff.js +79 -0
  212. package/risk/npm/downloads.js +84 -0
  213. package/risk/npm/files.js +445 -0
  214. package/risk/npm/held.js +67 -0
  215. package/risk/npm/install-scripts.js +34 -0
  216. package/risk/npm/malware.js +38 -0
  217. package/risk/npm/manifest.js +65 -0
  218. package/risk/npm/new-dependency.js +60 -0
  219. package/risk/npm/old-version.js +108 -0
  220. package/risk/npm/registry.js +393 -0
  221. package/risk/npm/release.js +85 -0
  222. package/risk/npm/score.js +59 -0
  223. package/risk/npm/specs.js +124 -0
  224. package/risk/npm/tarball.js +169 -0
  225. package/server-common/database-config.ts +16 -0
  226. package/server-common/initialize.ts +18 -0
  227. package/server-common/npm-advisories.ts +101 -0
  228. package/{server → server-common}/origin.ts +5 -5
  229. package/server-common/reap.ts +48 -0
  230. package/server-common/scan-config.ts +19 -0
  231. package/server-common/standalone.ts +29 -0
  232. package/server-common/storage-crypto.ts +182 -0
  233. package/server-common/storage-log.ts +38 -0
  234. package/server-common/vercel-blob.ts +103 -0
  235. package/server-e2e/app.ts +487 -0
  236. package/{server → server-e2e}/bus-receiver.ts +2 -1
  237. package/{server → server-e2e}/cli.js +9 -4
  238. package/{server → server-e2e}/config.ts +50 -42
  239. package/{server → server-e2e}/db-neon.ts +2 -2
  240. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  241. package/{server → server-e2e}/db-stmt.ts +2 -2
  242. package/{server → server-e2e}/db.ts +7 -7
  243. package/{server → server-e2e}/http.ts +44 -13
  244. package/{server → server-e2e}/hub.ts +40 -9
  245. package/server-e2e/index.ts +17 -0
  246. package/server-e2e/lifecycle.ts +95 -0
  247. package/{server → server-e2e}/neon-driver.ts +2 -2
  248. package/{server → server-e2e}/npm-proxy.ts +12 -145
  249. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  250. package/{server → server-e2e}/objstore/blob.ts +1 -1
  251. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  252. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  253. package/{server → server-e2e}/objstore/init.ts +19 -27
  254. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  255. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  257. package/{server → server-e2e}/objstore/rest.ts +3 -3
  258. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  259. package/{server → server-e2e}/objstore/store.ts +7 -7
  260. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  261. package/{server → server-e2e}/pubsub.ts +12 -9
  262. package/{server → server-e2e}/sign.ts +4 -4
  263. package/{server → server-e2e}/sse-server.ts +60 -33
  264. package/{server → server-e2e}/static.ts +18 -17
  265. package/{server → server-e2e}/sync-handlers.ts +64 -30
  266. package/{server → server-e2e}/ws-server.ts +20 -9
  267. package/server-managed/activity.ts +269 -0
  268. package/server-managed/agent-merges.ts +109 -0
  269. package/server-managed/app-agents.ts +23 -0
  270. package/server-managed/avatar-store.ts +13 -0
  271. package/server-managed/blob-store.ts +26 -0
  272. package/server-managed/brotli.ts +10 -0
  273. package/server-managed/bundle-advisories.ts +79 -0
  274. package/server-managed/bundle-advisory-inventory.ts +85 -0
  275. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  276. package/server-managed/bundle-build-diagnostics.js +23 -0
  277. package/server-managed/bundle-build-leases.ts +41 -0
  278. package/server-managed/bundle-build-worker.js +380 -0
  279. package/server-managed/bundle-build.ts +326 -0
  280. package/server-managed/bundle-cache.ts +261 -0
  281. package/server-managed/bundle-catalog.ts +29 -0
  282. package/server-managed/bundle-commits.ts +133 -0
  283. package/server-managed/bundle-dependency-reviews.ts +91 -0
  284. package/server-managed/bundle-store.ts +24 -0
  285. package/server-managed/bundle-summary-cache.ts +139 -0
  286. package/server-managed/bundle-validation.ts +33 -0
  287. package/server-managed/bundle.ts +151 -0
  288. package/server-managed/cache-storage.ts +20 -0
  289. package/server-managed/cli.js +21 -0
  290. package/server-managed/combined.ts +43 -0
  291. package/server-managed/comments.ts +138 -0
  292. package/server-managed/commit-coauthors.ts +105 -0
  293. package/server-managed/commit-lockfiles.ts +78 -0
  294. package/server-managed/comparison.ts +51 -0
  295. package/server-managed/config.ts +163 -0
  296. package/server-managed/content-access.ts +15 -0
  297. package/server-managed/crypto.ts +25 -0
  298. package/server-managed/db-methods.ts +1915 -0
  299. package/server-managed/db-neon.ts +398 -0
  300. package/server-managed/db-schema.ts +263 -0
  301. package/server-managed/db-table-names.ts +22 -0
  302. package/server-managed/db.ts +149 -0
  303. package/server-managed/dependabot-access.ts +61 -0
  304. package/server-managed/dependabot-alerts.ts +180 -0
  305. package/server-managed/dependency-review-comments.ts +158 -0
  306. package/server-managed/dependency-reviews.ts +369 -0
  307. package/server-managed/github-accounts.ts +59 -0
  308. package/server-managed/github-actions.ts +71 -0
  309. package/server-managed/github-app.ts +347 -0
  310. package/server-managed/github-errors.ts +92 -0
  311. package/server-managed/github-graphql.ts +42 -0
  312. package/server-managed/github-issue-links.ts +264 -0
  313. package/server-managed/github-issue-oauth.ts +30 -0
  314. package/server-managed/github-issues.ts +157 -0
  315. package/server-managed/github-link-oauth.ts +56 -0
  316. package/server-managed/github-links.ts +204 -0
  317. package/server-managed/github-metadata.ts +213 -0
  318. package/server-managed/github-oauth.ts +264 -0
  319. package/server-managed/github-pulls.ts +257 -0
  320. package/server-managed/github-requests.ts +181 -0
  321. package/server-managed/github-users.ts +30 -0
  322. package/server-managed/github-values.ts +26 -0
  323. package/server-managed/history-windows.ts +172 -0
  324. package/server-managed/http-response.ts +76 -0
  325. package/server-managed/http.ts +6327 -0
  326. package/server-managed/import-triage.ts +51 -0
  327. package/server-managed/index.ts +204 -0
  328. package/server-managed/kept-briefly.ts +37 -0
  329. package/server-managed/kept.ts +28 -0
  330. package/server-managed/link-reports.ts +149 -0
  331. package/server-managed/listed-activity.ts +39 -0
  332. package/server-managed/locked-packages.ts +234 -0
  333. package/server-managed/lockfile-scope.ts +58 -0
  334. package/server-managed/lru.ts +30 -0
  335. package/server-managed/managed-issues.ts +92 -0
  336. package/server-managed/management-catalog.ts +45 -0
  337. package/server-managed/management.ts +116 -0
  338. package/server-managed/npm-delta-worker.js +142 -0
  339. package/server-managed/npm-delta.ts +277 -0
  340. package/server-managed/npm-insights.ts +455 -0
  341. package/server-managed/npm-kept.ts +265 -0
  342. package/server-managed/npm-loads.ts +259 -0
  343. package/server-managed/npm-manifest.ts +117 -0
  344. package/server-managed/npm-packages.ts +469 -0
  345. package/server-managed/npm-patch-paths.ts +86 -0
  346. package/server-managed/npm-patch.ts +455 -0
  347. package/server-managed/npm-provenance.ts +127 -0
  348. package/server-managed/npm-risk.ts +287 -0
  349. package/server-managed/object-storage-disk.ts +147 -0
  350. package/server-managed/object-storage-vercel.ts +71 -0
  351. package/server-managed/object-storage.ts +82 -0
  352. package/server-managed/package-entry-points.ts +127 -0
  353. package/server-managed/pretty-copies.ts +22 -0
  354. package/server-managed/pretty-format.d.ts +3 -0
  355. package/server-managed/pretty-format.js +13 -0
  356. package/server-managed/pretty-print.ts +442 -0
  357. package/server-managed/public-workspace.ts +243 -0
  358. package/server-managed/pull-comment-reviews.ts +161 -0
  359. package/server-managed/pull-dependencies.ts +370 -0
  360. package/server-managed/pull-dependency-reviews.ts +407 -0
  361. package/server-managed/pull-reviews.ts +202 -0
  362. package/server-managed/queue.ts +54 -0
  363. package/server-managed/release-commits.ts +85 -0
  364. package/server-managed/rename-diff-worker.js +30 -0
  365. package/server-managed/rename-diff.ts +237 -0
  366. package/server-managed/repo-path.ts +21 -0
  367. package/server-managed/report-migration.ts +32 -0
  368. package/server-managed/report-opening.ts +77 -0
  369. package/server-managed/report-query.ts +10 -0
  370. package/server-managed/report-response.ts +16 -0
  371. package/server-managed/report-sources.ts +185 -0
  372. package/server-managed/report-store.ts +77 -0
  373. package/server-managed/repository-actions.ts +220 -0
  374. package/server-managed/repository-agents.ts +422 -0
  375. package/server-managed/repository-aliases.ts +119 -0
  376. package/server-managed/repository-browser.ts +361 -0
  377. package/server-managed/repository-changes.ts +280 -0
  378. package/server-managed/repository-code.ts +222 -0
  379. package/server-managed/repository-dependency-reviews.ts +182 -0
  380. package/server-managed/repository-discovery.ts +83 -0
  381. package/server-managed/repository-history.ts +428 -0
  382. package/server-managed/repository-issues.ts +293 -0
  383. package/server-managed/repository-policy.ts +27 -0
  384. package/server-managed/repository-pulls.ts +207 -0
  385. package/server-managed/repository-pulse.ts +477 -0
  386. package/server-managed/repository-risk-assess.ts +108 -0
  387. package/server-managed/repository-risk-audit.ts +78 -0
  388. package/server-managed/repository-risk-caches.ts +37 -0
  389. package/server-managed/repository-risk-read.ts +260 -0
  390. package/server-managed/repository-risk-stasis.ts +61 -0
  391. package/server-managed/repository-risk-turn.ts +97 -0
  392. package/server-managed/repository-risk.ts +516 -0
  393. package/server-managed/repository-squashes.ts +160 -0
  394. package/server-managed/repository-stamp.ts +41 -0
  395. package/server-managed/request-timing.ts +63 -0
  396. package/server-managed/reviewed-dependencies.ts +170 -0
  397. package/server-managed/revisions.ts +35 -0
  398. package/server-managed/scan-downloads.ts +121 -0
  399. package/server-managed/session.ts +132 -0
  400. package/server-managed/slugs.ts +38 -0
  401. package/server-managed/solidity-entry-points.ts +71 -0
  402. package/server-managed/sql-postgres.ts +34 -0
  403. package/server-managed/sql.ts +107 -0
  404. package/server-managed/stasis-config.ts +147 -0
  405. package/server-managed/stasis-dependencies.ts +221 -0
  406. package/server-managed/static.ts +28 -0
  407. package/server-managed/storage-command.ts +16 -0
  408. package/server-managed/storage-db.ts +183 -0
  409. package/server-managed/storage-encryption.ts +288 -0
  410. package/server-managed/storage-maintenance.ts +259 -0
  411. package/server-managed/storage-payload.ts +121 -0
  412. package/server-managed/storage-stores.ts +91 -0
  413. package/server-managed/storage.ts +82 -0
  414. package/server-managed/team-app-summaries.ts +56 -0
  415. package/server-managed/team-app.ts +156 -0
  416. package/server-managed/team-catalog.ts +7 -0
  417. package/server-managed/team-feed.ts +180 -0
  418. package/server-managed/team-npm-scopes.ts +103 -0
  419. package/server-managed/team-reports.ts +368 -0
  420. package/server-managed/triage-response.ts +16 -0
  421. package/server-managed/type-only-proof.js +161 -0
  422. package/server-managed/type-only-worker.js +31 -0
  423. package/server-managed/type-only.ts +135 -0
  424. package/server-managed/uploads.ts +106 -0
  425. package/server-managed/upstream-cache.ts +256 -0
  426. package/server-managed/view-as.ts +58 -0
  427. package/server-managed/worker-turns.ts +76 -0
  428. package/server-managed/workspace-shares.ts +170 -0
  429. package/server.ts +70 -0
  430. package/strip-types-loader.js +13 -10
  431. package/server/index.ts +0 -480
  432. package/server/lifecycle.ts +0 -208
  433. /package/{LICENSE → LICENSE-MIT} +0 -0
  434. /package/{server → server-e2e}/auth.ts +0 -0
  435. /package/{server → server-e2e}/config.example.json +0 -0
  436. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  437. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  438. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  439. /package/{server → server-e2e}/peer.ts +0 -0
  440. /package/{server → server-e2e}/sse-session.ts +0 -0
  441. /package/{server → server-e2e}/util.ts +0 -0
  442. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,469 @@
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 { NPM_SYMLINKS_ABOVE, npmTarLayout } from '../risk/index.js'
21
+ import type { Role } from '../common/managed/roles.ts'
22
+ import { npmManifest, npmVersionFields, plainObject, stringRecord } from './npm-manifest.ts'
23
+ import { keepJson, readKeptJson, upstreamCachePath } from './upstream-cache.ts'
24
+
25
+ export const NPM_REGISTRY = 'https://registry.npmjs.org'
26
+ const VERSION_DOCUMENT_BYTES = 8 * 1024 * 1024
27
+ // Abbreviated packuments of packages with thousands of versions run to tens of MiB.
28
+ const PACKUMENT_BYTES = 64 * 1024 * 1024
29
+ // What registry documents being read at once may hold, each counted at its
30
+ // limit until it is read and parsed: four packuments, or 32 version documents.
31
+ const MAX_DOCUMENT_BYTES = 4 * PACKUMENT_BYTES
32
+ // What a package may unpack to: the files' bytes and their count; the tar
33
+ // stream holding them is bounded in npm-loads.ts. A repository directory's
34
+ // are its own (repository-code.ts).
35
+ export const MAX_NPM_PACKAGE_BYTES = 64 * 1024 * 1024
36
+ export const MAX_NPM_PACKAGE_FILES = 20_000
37
+ // The entries its tar stream may hold, read before any is counted as a file:
38
+ // a directory's too, though npm packs none.
39
+ export const MAX_NPM_TAR_ENTRIES = 2 * MAX_NPM_PACKAGE_FILES
40
+ // What the files may take as the viewer's JSON. Escaping grows a text up to
41
+ // six times (a control character becomes `\u0001`), so it is counted before
42
+ // anything is serialized.
43
+ export const MAX_NPM_JSON_LENGTH = 96 * 1024 * 1024
44
+ export class NpmPackageError extends Error {
45
+ status: number
46
+ constructor(status: number, code: string) { super(code); this.status = status }
47
+ }
48
+
49
+ // Who reads, as the session has it now: the role, and the scopes of the
50
+ // visible teams they are a member of, where those count (npmScopesCount).
51
+ export interface NpmReader { role: Role; scopes: ReadonlySet<string>; userId: string }
52
+
53
+ // Whether a reader may have a package read with the server's token.
54
+ export function canReadPrivateNpm(reader: NpmReader, name: string): boolean {
55
+ if (reader.role === 'admin' || reader.role === 'manage') return true
56
+ const scope = npmPackageScope(name)
57
+ return scope !== null && reader.scopes.has(scope)
58
+ }
59
+
60
+ // Whether a reader's team scopes count for any of `names`, as
61
+ // canReadPrivateNpm reads them: a scoped one, read by someone below manager.
62
+ export const npmScopesCount = (role: Role, names: readonly string[]): boolean =>
63
+ role !== 'admin' && role !== 'manage' && names.some(name => npmPackageScope(name) !== null)
64
+
65
+ export const npmToken = () => process.env['NPM_TOKEN'] || 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 && npmToken() !== null && npmPackageScope(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: npmToken() })
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
+ // The package's dist-tags and versions, newest published first, from its
309
+ // abbreviated document; with `times`, from its whole one, which alone has
310
+ // when each was published, `times` by version (ISO dates), and `created`,
311
+ // when its first version was, one since unpublished among them: the earliest
312
+ // time it lists, which npm's own `created` can postdate, as a placeholder's
313
+ // does for a package npm took down. With `spare`, as a read no reader waits
314
+ // on (withDocumentBudget). Null where the registry has none for this reader.
315
+ export function readNpmVersions(name: string, privileged: boolean, signal: AbortSignal, { times = false, spare = false } = {}) {
316
+ if (!isNpmPackageName(name)) return Promise.reject(new NpmPackageError(400, 'bad-package'))
317
+ return withDocumentBudget(PACKUMENT_BYTES, async () => {
318
+ const accept = times ? 'application/json' : 'application/vnd.npm.install-v1+json'
319
+ const found = await readDocument(name, registryUrl(name), privileged, { accept, limit: PACKUMENT_BYTES, signal, whole: times })
320
+ if (!found) return null
321
+ const { json } = found
322
+ if (json['name'] !== name || !plainObject(json['versions'])) throw new NpmPackageError(502, 'upstream-invalid')
323
+ const versions = Object.keys(json['versions']).filter(isNpmPackageSpec).toReversed()
324
+ const distTags = Object.fromEntries(Object.entries(stringRecord(json['dist-tags']) ?? {}).filter(([, version]) => versions.includes(version)))
325
+ const listed = { name, private: found.private, distTags, versions }
326
+ if (!times) return listed
327
+ const time = stringRecord(json['time']) ?? {}
328
+ const published = Object.fromEntries(versions.filter(version => isPublishTime(time[version])).map(version => [version, time[version]!]))
329
+ for (const [version, at] of Object.entries(published)) publishTimes.set(`${name}@${version}`, at)
330
+ while (publishTimes.size > PUBLISH_TIMES) publishTimes.delete(publishTimes.keys().next().value!)
331
+ const listedAt = Object.entries(time).filter(([key, at]) => key !== 'modified' && isPublishTime(at)).map(([, at]) => at)
332
+ const created = listedAt.reduce<string | null>((first, at) => first === null || Date.parse(at) < Date.parse(first) ? at : first, null)
333
+ return { ...listed, times: published, created }
334
+ }, spare)
335
+ }
336
+
337
+ // A package's whole document as npm has it for this reader, for risk
338
+ // (npm-risk.ts), within the bounds and budget every document read here is
339
+ // held to; null where npm has none for this reader, or the name is none npm
340
+ // takes. With `anonymous` false, where npm is known to have none for anyone,
341
+ // it is asked only with the token (readDocument).
342
+ export function readNpmPackument(name: string, privileged: boolean, signal: AbortSignal, { anonymous = true } = {}): Promise<Record<string, unknown> | null> {
343
+ if (!isNpmPackageName(name)) return Promise.resolve(null)
344
+ return withDocumentBudget(PACKUMENT_BYTES, async () => (await readDocument(name, registryUrl(name), privileged,
345
+ { accept: 'application/json', limit: PACKUMENT_BYTES, signal, whole: true, anonymous }))?.json ?? null)
346
+ }
347
+
348
+ const isPublishTime = (value: string | undefined) => typeof value === 'string' && value.length <= 40 && !Number.isNaN(Date.parse(value))
349
+
350
+ // When each version was published, by `name@version`, as whole documents read
351
+ // with `times` have said: a version keeps its time once published, so it is
352
+ // kept for as long as the server runs, the first noted going first past a
353
+ // bound, and answered only with the version, once its reader's access is.
354
+ const PUBLISH_TIMES = 100_000
355
+ const publishTimes = new Map<string, string>()
356
+
357
+ // Where public versions' publish times are kept beyond the instance, as the
358
+ // database keeps them (npm-kept.ts npmPublishTimeStore).
359
+ export interface NpmPublishTimeStore {
360
+ read(name: string, version: string): Promise<string | null>
361
+ write(name: string, version: string, at: string): Promise<void>
362
+ }
363
+
364
+ // When `doc` was published: as noted here, else as `store` keeps a public
365
+ // version's, so that another instance, or this one restarted, has it before
366
+ // it reads the whole document again. The store is read once, at once, beside
367
+ // whatever its caller reads meanwhile, a failure read as none; `read` looks
368
+ // here again as it is asked, as the whole document read meanwhile may have
369
+ // noted it by then, and `keep` keeps there the time noted here where it read
370
+ // none.
371
+ export function npmPublishTime(doc: Pick<NpmVersionDocument, 'name' | 'version' | 'private'>, store?: NpmPublishTimeStore) {
372
+ const noted = () => publishTimes.get(`${doc.name}@${doc.version}`) ?? null
373
+ const kept = store && !doc.private ? store.read(doc.name, doc.version).catch(() => null) : Promise.resolve(null)
374
+ return {
375
+ read: async (): Promise<string | null> => noted() ?? await kept ?? noted(),
376
+ async keep() {
377
+ const at = noted()
378
+ if (at !== null && store && !doc.private && await kept === null) await store.write(doc.name, doc.version, at)
379
+ },
380
+ }
381
+ }
382
+
383
+ // A symlink's `link` is its target as stored, its bytes that target's: no text, whatever they spell.
384
+ // One with an execute bit is `executable`.
385
+ export interface NpmPackageFile { path: string; bytes: Uint8Array; link?: string; executable?: true }
386
+
387
+ // The paths of `files` that are executable, as the viewer gets them beside their rows.
388
+ export const npmExecutablePaths = (files: NpmPackageFile[]) => files.flatMap(file => file.executable ? [file.path] : [])
389
+
390
+ // Paths in the order a package's files are read in (readNpmTar), and
391
+ // Compare's: by their UTF-16 code units, as a plain sort orders them.
392
+ export const pathOrder = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
393
+
394
+ // How a tar stream is read (readNpmTar): how far its symlinks may climb above
395
+ // it, and the entries, files and bytes it may hold, a package's unless given;
396
+ // and whether two paths one on macOS or Windows conflict (`foldPaths`), as they do unless given.
397
+ export interface TarReading { symlinksAbove?: number; maxEntries?: number; maxFiles?: number; maxBytes?: number; foldPaths?: boolean }
398
+
399
+ // The regular files of a tar stream, by package path, as npm and pnpm install
400
+ // them (risk's npmTarLayout): each name as stored past its first component,
401
+ // whatever the archive used (`package/`, a release's own directory, `.`), and
402
+ // a file under no directory at its name, as pnpm installs it. The stream is
403
+ // read by @preventive/archive, which refuses one malformed, a name that would
404
+ // climb out of it, an absolute symlink or one past `symlinksAbove` levels
405
+ // above it, any unless given, and a name repeated as another entry, and
406
+ // gives up past `maxEntries` before reading on. Every file is read, whether
407
+ // or not an installer installs it, a hard link as its target's bytes, a
408
+ // symlink for where it points. Where
409
+ // the files conflict (two that differ at one path, as under two top
410
+ // directories, or at two paths one on macOS or Windows unless `foldPaths` is
411
+ // false, a file within another), it is refused as `tarball-conflict`,
412
+ // never read as one installer does. Directories and devices hold no file
413
+ // content and are skipped.
414
+ export function readNpmTar(tar: Uint8Array, { symlinksAbove = NPM_SYMLINKS_ABOVE, maxEntries = MAX_NPM_TAR_ENTRIES, maxFiles = MAX_NPM_PACKAGE_FILES,
415
+ maxBytes = MAX_NPM_PACKAGE_BYTES, foldPaths = true }: TarReading = {}): NpmPackageFile[] {
416
+ let entries: Entry[]
417
+ try { entries = unpack(tar, { maxEntries, symlinksAbove }) }
418
+ catch (err) {
419
+ if (err instanceof ArchiveError) throw err.limited ? new NpmPackageError(413, 'package-too-large') : new NpmPackageError(422, 'bad-tarball')
420
+ throw err
421
+ }
422
+ const files = npmTarLayout(entries, { maxFiles, maxBytes, foldPaths }, (code) => { throw new NpmPackageError(code === 'package-too-large' ? 413 : 422, code) })
423
+ return [...files].map(([path, file]) => ({ path, ...file })).toSorted((a, b) => pathOrder(a.path, b.path))
424
+ }
425
+
426
+ const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
427
+
428
+ // A file's text, or null for bytes that are not UTF-8 text.
429
+ export function npmFileText(bytes: Uint8Array): string | null {
430
+ if (bytes.includes(0)) return null
431
+ try { return utf8.decode(bytes) } catch { return null }
432
+ }
433
+
434
+ // A string's length in JSON: quotes, backslashes and the control characters
435
+ // with a short escape take two characters, the other control characters six.
436
+ function jsonLength(text: string): number {
437
+ let length = text.length + 2
438
+ for (let i = 0; i < text.length; i++) {
439
+ const code = text.codePointAt(i)!
440
+ if (code === 0x22 || code === 0x5c) length += 1
441
+ else if (code < 0x20) length += code >= 0x08 && code <= 0x0d && code !== 0x0b ? 1 : 5
442
+ }
443
+ return length
444
+ }
445
+
446
+ // A row's brackets, size, null and digest, past its strings.
447
+ const ROW_LENGTH = 80
448
+
449
+ // The files as the viewer gets them: `[path, bytes, text]`, text null for a
450
+ // file that is not UTF-8, which instead carries its bytes' sha256, so a
451
+ // comparison of two versions tells a changed one from an unchanged one; a
452
+ // symlink so too, its target last. They may take `maxLength` characters of
453
+ // JSON, a package's unless given.
454
+ export function npmFileRows(files: NpmPackageFile[], maxLength = MAX_NPM_JSON_LENGTH): ([string, number, string] | [string, number, null, string, string?])[] {
455
+ let length = 0
456
+ return files.map(({ path, bytes, link }) => {
457
+ const text = link === undefined ? npmFileText(bytes) : null
458
+ length += ROW_LENGTH + jsonLength(path) + jsonLength(text ?? link ?? '')
459
+ if (length > maxLength) throw new NpmPackageError(413, 'package-too-large')
460
+ const digest = () => `sha256-${createHash('sha256').update(bytes).digest('base64')}`
461
+ if (text !== null) return [path, bytes.byteLength, text]
462
+ return link === undefined ? [path, bytes.byteLength, null, digest()] : [path, bytes.byteLength, null, digest(), link]
463
+ })
464
+ }
465
+
466
+ // The tarball's filename as `npm pack` writes it.
467
+ export function npmTarballFilename(name: string, version: string): string {
468
+ return `${name.replace(/^@/u, '').replace('/', '-')}-${version}.tgz`
469
+ }
@@ -0,0 +1,86 @@
1
+ // Paths as git writes them in a diff's headers (npm-patch.ts parsePatch):
2
+ // quoted as C writes a string where they need it, prefixed `a/` and `b/`.
3
+ import { Buffer } from 'node:buffer'
4
+ import { NPM_PATH_FOLDS } from '../risk/index.js'
5
+ import { NpmPackageError } from './npm-packages.ts'
6
+
7
+ const unreadable = () => new NpmPackageError(422, 'patch-unreadable')
8
+
9
+ // A path as git writes it, unquoted where quoted (as C writes a string, its
10
+ // bytes past ASCII in octal); null where it is quoted otherwise.
11
+ const ESCAPES: Record<string, number> = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 }
12
+ export function unquoted(path: string): string | null {
13
+ if (!path.startsWith('"')) return path
14
+ const bytes: number[] = []
15
+ for (let at = 1; at < path.length; at++) {
16
+ const char = path[at]!
17
+ if (char === '"') return at === path.length - 1 ? new TextDecoder().decode(Uint8Array.from(bytes)) : null
18
+ if (char !== '\\') { bytes.push(...Buffer.from(char)); continue }
19
+ const next = path[++at] ?? ''
20
+ const octal = /^[0-3][0-7]{2}/u.exec(path.slice(at))?.[0]
21
+ if (octal) { bytes.push(Number.parseInt(octal, 8)); at += 2 }
22
+ else if (next in ESCAPES) bytes.push(ESCAPES[next]!)
23
+ else return null
24
+ }
25
+ return null
26
+ }
27
+
28
+ // A side's path in the package, as a `---` or `+++` line names it after its
29
+ // prefix (`a/` or `b/`), git's tab after one with a space in it left out;
30
+ // null for none (`/dev/null`).
31
+ export function sidePath(named: string, prefix: string): string | null {
32
+ const path = unquoted(named.endsWith('\t') ? named.slice(0, -1) : named)
33
+ if (path === '/dev/null') return null
34
+ if (path === null || !path.startsWith(prefix)) throw unreadable()
35
+ return path.slice(prefix.length)
36
+ }
37
+
38
+ // The paths a `diff --git` line names, where they are the same, as git
39
+ // writes them for a file neither renamed nor copied: `a/<path> b/<path>`.
40
+ export function gitPath(named: string): string | null {
41
+ if (named.startsWith('"')) {
42
+ const quoted = /^("(?:[^"\\]|\\.)*") ("(?:[^"\\]|\\.)*")$/u.exec(named)
43
+ const [a, b] = quoted ? [unquoted(quoted[1]!), unquoted(quoted[2]!)] : []
44
+ return a?.startsWith('a/') && b?.startsWith('b/') && a.slice(2) === b.slice(2) ? a.slice(2) : null
45
+ }
46
+ const length = (named.length - 5) / 2
47
+ const path = named.slice(2, 2 + length)
48
+ return Number.isInteger(length) && named.startsWith('a/') && named.slice(2 + length) === ` b/${path}` ? path : null
49
+ }
50
+
51
+ // Whether a `diff --git` line's paths (`rest`, past `diff --git `) are
52
+ // `before` and `after`, as git writes them, either quoted or not.
53
+ export function namesBoth(rest: string, before: string, after: string): boolean {
54
+ const first = rest.startsWith('"') ? /^"(?:[^"\\]|\\.)*"/u.exec(rest)?.[0] : `a/${before}`
55
+ if (first === undefined || !rest.startsWith(`${first} `)) return false
56
+ const second = rest.slice(first.length + 1)
57
+ return unquoted(first) === `a/${before}` && unquoted(second) === `b/${after}`
58
+ }
59
+
60
+ // A path every pnpm takes as written: none of its names starts or ends in
61
+ // whitespace, which pnpm 10 and 11 trim off a path, or is `node_modules`, in
62
+ // which pnpm 12 may leave out a file a patch creates.
63
+ export const isPlainPath = (path: string) => path.split('/').every(name => name === name.trim() && name.toLowerCase() !== 'node_modules')
64
+
65
+ // Takes each path a patch creates or renames a file to, refusing one macOS or
66
+ // Windows may take for another spelled otherwise (NPM_PATH_FOLDS): one of the
67
+ // package's `paths`, a directory of one, or one taken before. So `License`
68
+ // beside `LICENSE`, or `Lib/a.js` beside `lib/`, which pnpm versions may
69
+ // write over the other, or into it.
70
+ export function pathClaims(paths: Iterable<string>): (path: string) => void {
71
+ // By each fold, the spelling of each path and directory; '' for several.
72
+ const spelled = NPM_PATH_FOLDS.map(() => new Map<string, string>())
73
+ const take = (path: string, claim: boolean) => {
74
+ for (let at = path.indexOf('/'); ; at = path.indexOf('/', at + 1)) {
75
+ const name = at === -1 ? path : path.slice(0, at)
76
+ for (const [i, fold] of NPM_PATH_FOLDS.entries()) {
77
+ const key = fold(name), was = spelled[i]!.get(key)
78
+ if (claim && was !== undefined && was !== name) throw unreadable()
79
+ spelled[i]!.set(key, was === undefined || was === name ? name : '')
80
+ }
81
+ if (at === -1) return
82
+ }
83
+ }
84
+ for (const path of paths) take(path, false)
85
+ return path => take(path, true)
86
+ }