@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,287 @@
1
+ // What calls for a look at an npm version, as risk tells it (risk/), for the
2
+ // managed viewer: risk is asked on the server alone, its records kept where
3
+ // each belongs by its type (risk/npm/registry.js, assess.js):
4
+ //
5
+ // - `risk/npm/assessments`, what of an assessment holds whatever the time:
6
+ // a public package's in the public npm cache, as its pretty-printed files
7
+ // are (storage-payload.ts PUBLIC_CACHE), by a hash of its key; a private
8
+ // one's in this instance's memory alone.
9
+ // - `risk/npm/versions`, what a version's document says, which npm never
10
+ // changes once published: a public package's in the database's upstream
11
+ // cache table, shared by every instance; a private one's in memory.
12
+ // - `risk/npm/downloads`, a package's downloads a day, which risk tells as
13
+ // kept for a week: a public package's in the database too, so that another
14
+ // instance, or this one restarted, asks npm's downloads API, which answers
15
+ // some 40 lookups a minute, none of them again that week, each removed a
16
+ // day past it (npm-kept.ts pruneKept); a private one's in memory.
17
+ // - `risk/npm/packages`, `risk/npm/old-versions`, `risk/npm/public` and
18
+ // `risk/npm/advisories`, which risk asks again after an hour: a public
19
+ // package's in memory and in the database too, read from memory first, so
20
+ // that a cold instance, as a serverless one starts, reads no whole document
21
+ // of npm's again that one before it read within the hour; by a hash of
22
+ // their type and key, as a dependency's spec runs to any length, each
23
+ // removed a day on, and one past 256 KiB as JSON (a package's deprecated
24
+ // versions, its messages and all, run long) in memory alone. A private
25
+ // one's in memory.
26
+ // - `npm/tarballs`: none asked, as tarballs are read as the viewer's loads
27
+ // read them, kept where they keep them (npm-loads.ts loadNpmTarball), and
28
+ // an assessment kept needs none.
29
+ //
30
+ // What memory keeps is held to 2,000 records and 64 MiB as JSON, the first
31
+ // kept going first.
32
+ //
33
+ // A cache failure is a miss, never a failed assessment. Packages' documents
34
+ // are read as every other npm document here is, within their bounds and
35
+ // shared budget (npm-packages.ts readNpmPackument), and tarballs as the
36
+ // viewer's loads read them, bounded as they arrive and among the loads made
37
+ // at once. Assessments made at once are bounded as those loads are, each
38
+ // unpacking up to two tarballs: one past them is refused as busy.
39
+ import { Buffer } from 'node:buffer'
40
+ import { createHash } from 'node:crypto'
41
+ import type { CacheStore } from '@preventive/upstream/npm.js'
42
+ import { DEFAULT_MINIMUM_RELEASE_AGE, type NpmAssessment, assessNpm, npmReadyDownload, npmReadyDownloads } from '../risk/index.js'
43
+ import { readBytes } from './blob-store.ts'
44
+ import { CacheMissError, type CacheStorage } from './cache-storage.ts'
45
+ import { npmVersionStore, pruneKept } from './npm-kept.ts'
46
+ import { loadNpmTarball } from './npm-loads.ts'
47
+ import { NpmPackageError, type NpmVersionDocument, npmTokenReads, readNpmPackument, readNpmVersion } from './npm-packages.ts'
48
+ import { npmPackageScope } from '../common/managed/npm-packages.js'
49
+ import type { UpstreamCacheStore } from './upstream-cache.ts'
50
+
51
+ const MEMORY_ENTRIES = 2000
52
+ // As npm-loads.ts MAX_ACTIVE_LOADS.
53
+ const MAX_ACTIVE_ASSESSMENTS = 4
54
+ // Of them, those no reader waits on (`spare`), such as a scan's: the rest are
55
+ // left for readers.
56
+ export const MAX_SPARE_ASSESSMENTS = 2
57
+ let assessing = 0
58
+ // What memory holds at most, by its records' length as JSON: the first kept
59
+ // go first past it, and a record past an eighth of it isn't kept at all.
60
+ const MEMORY_LENGTH = 64 * 1024 * 1024
61
+ let memoryLength = 0
62
+ const memory = new Map<string, { value: unknown; length: number }>()
63
+ function forget(key: string) {
64
+ const kept = memory.get(key)
65
+ if (!kept) return
66
+ memory.delete(key)
67
+ memoryLength -= kept.length
68
+ }
69
+ function remember(key: string, value: unknown) {
70
+ forget(key)
71
+ const length = JSON.stringify(value)?.length ?? 0
72
+ if (length > MEMORY_LENGTH / 8) return
73
+ memory.set(key, { value, length })
74
+ memoryLength += length
75
+ while (memory.size > MEMORY_ENTRIES || memoryLength > MEMORY_LENGTH) forget(memory.keys().next().value!)
76
+ }
77
+
78
+ const digest = (type: string, key: string) => createHash('sha256').update(`${type}\0${key}`).digest('hex')
79
+ const hashed = (type: string, key: string) => `risk/${digest(type, key)}`
80
+ // What of a public package is kept in the database by its key, and for how
81
+ // long its downloads are: risk's week, and a day more.
82
+ const IN_DATABASE = new Set(['risk/npm/versions', 'risk/npm/downloads'])
83
+ const DOWNLOADS_KEPT_MS = 8 * 24 * 60 * 60_000
84
+ // What of a public package risk asks again after an hour, kept in memory and
85
+ // in the database (HOURLY_PREFIX), each a day, none past HOURLY_LENGTH as
86
+ // JSON there.
87
+ const HOURLY = new Set(['risk/npm/packages', 'risk/npm/old-versions', 'risk/npm/public', 'risk/npm/advisories'])
88
+ const HOURLY_PREFIX = 'risk/hourly/'
89
+ const HOURLY_KEPT_MS = 24 * 60 * 60_000
90
+ const HOURLY_LENGTH = 256 * 1024
91
+ const databaseKey = (type: string, key: string) => HOURLY.has(type) ? `${HOURLY_PREFIX}${digest(type, key)}` : `${type}/${key}`
92
+
93
+ export interface NpmRiskStores {
94
+ db: UpstreamCacheStore
95
+ npmCache?: CacheStorage | undefined
96
+ debug?: boolean | undefined
97
+ }
98
+
99
+ // A cache that reads and writes many of a type at once too, as risk's
100
+ // readying of downloads asks (npmReadyDownloads), and reads records of any
101
+ // types at once, as risk reads a package's record and its versions'
102
+ // (registry.js npmPackageFacts): one read and one write of the database each,
103
+ // not one a key, as a request's queries take turns on its connection
104
+ // (db-neon.ts).
105
+ export interface NpmRiskCache extends CacheStore {
106
+ readEach(entries: [type: string, key: string][]): Promise<unknown[]>
107
+ readMany(type: string, keys: string[]): Promise<Map<string, unknown>>
108
+ writeMany(type: string, entries: [key: string, value: unknown][]): Promise<void>
109
+ }
110
+
111
+ // Risk's cache for one package: `isPublic` whether anyone can read it, so
112
+ // that what is kept of it can be shared.
113
+ export function npmRiskCache({ db, npmCache, debug }: NpmRiskStores, isPublic: boolean): NpmRiskCache {
114
+ const warn = (what: string, error: unknown) => { if (debug) console.warn(`managed: risk cache ${what} failed:`, error) }
115
+ // The rows under `prefix` kept `keptMs` before `at` removed, as rows under
116
+ // it are written (pruneKept).
117
+ const prune = (prefix: string, keptMs: number, at: number) => pruneKept(db, prefix, keptMs, at, error => { warn('prune', error) })
118
+ const memoryKey = (type: string, key: string) => `${isPublic ? '' : 'private\0'}${type}\0${key}`
119
+ // Whether a record of `type` is read of the database: unless it is one
120
+ // kept in memory too (HOURLY) and there.
121
+ const ofDatabase = (type: string, key: string) => isPublic && (IN_DATABASE.has(type) || HOURLY.has(type) && !memory.has(memoryKey(type, key)))
122
+ // A record as the database keeps it, read: an hourly one kept in memory
123
+ // too, for the next to ask.
124
+ const readOf = (type: string, key: string, row: string | null | undefined) => {
125
+ const value: unknown = row == null ? null : JSON.parse(row)
126
+ if (value !== null && HOURLY.has(type)) remember(memoryKey(type, key), value)
127
+ return value
128
+ }
129
+ const cache: NpmRiskCache = {
130
+ async readEach(entries) {
131
+ const asked = new Set(entries.flatMap(([type, key], i) => ofDatabase(type, key) ? [i] : []))
132
+ let rows = new Map<string, string>()
133
+ if (asked.size > 0) {
134
+ try { rows = await db.getUpstreamCacheEntries([...asked].map(i => databaseKey(...entries[i]!))) } catch (error) { warn('read', error) }
135
+ }
136
+ return Promise.all(entries.map(([type, key], i) => {
137
+ if (!asked.has(i)) return cache.read(type, key)
138
+ try { return readOf(type, key, rows.get(databaseKey(type, key))) } catch (error) { warn('read', error); return null }
139
+ }))
140
+ },
141
+ async readMany(type, keys) {
142
+ const values = await cache.readEach(keys.map(key => [type, key]))
143
+ return new Map(keys.map((key, i) => [key, values[i]]))
144
+ },
145
+ async writeMany(type, entries) {
146
+ if (!isPublic || !IN_DATABASE.has(type)) { for (const [key, value] of entries) await cache.write(type, key, value); return }
147
+ const at = Date.now()
148
+ try { await db.setUpstreamCacheEntries(entries.map(([key, value]) => [`${type}/${key}`, JSON.stringify(value)]), at) } catch (error) { warn('write', error); return }
149
+ if (type === 'risk/npm/downloads') await prune(`${type}/`, DOWNLOADS_KEPT_MS, at)
150
+ },
151
+ async read(type, key) {
152
+ if (type === 'npm/tarballs') return null
153
+ try {
154
+ if (isPublic && type === 'risk/npm/assessments' && npmCache) return JSON.parse((await readBytes(await npmCache.open(hashed(type, key)))).toString('utf8'))
155
+ if (ofDatabase(type, key)) return readOf(type, key, await db.getUpstreamCacheEntry(databaseKey(type, key)))
156
+ } catch (error) { if (!(error instanceof CacheMissError)) warn('read', error); return null }
157
+ return memory.get(memoryKey(type, key))?.value ?? null
158
+ },
159
+ async write(type, key, value) {
160
+ if (type === 'npm/tarballs') return
161
+ if (isPublic && HOURLY.has(type)) remember(memoryKey(type, key), value)
162
+ try {
163
+ if (isPublic && type === 'risk/npm/assessments' && npmCache) { await npmCache.put(hashed(type, key), Buffer.from(JSON.stringify(value))); return }
164
+ if (isPublic && IN_DATABASE.has(type)) {
165
+ const at = Date.now()
166
+ await db.setUpstreamCacheEntry(databaseKey(type, key), JSON.stringify(value), at)
167
+ if (type === 'risk/npm/downloads') await prune(`${type}/`, DOWNLOADS_KEPT_MS, at)
168
+ return
169
+ }
170
+ if (isPublic && HOURLY.has(type)) {
171
+ const json = JSON.stringify(value)
172
+ if (json.length > HOURLY_LENGTH) return
173
+ const at = Date.now()
174
+ await db.setUpstreamCacheEntry(databaseKey(type, key), json, at)
175
+ await prune(HOURLY_PREFIX, HOURLY_KEPT_MS, at)
176
+ return
177
+ }
178
+ } catch (error) { warn('write', error); return }
179
+ remember(memoryKey(type, key), value)
180
+ },
181
+ }
182
+ return cache
183
+ }
184
+
185
+ // A version's tarball as the viewer's loads read it (npm-loads.ts), its bytes
186
+ // held to the integrity its reader's document names: given up on, and the
187
+ // load released, once `signal` aborts, the load going on for its other
188
+ // readers, so that a reader gone holds no assessment's place.
189
+ async function tarballOf(doc: NpmVersionDocument | undefined, signal: AbortSignal): Promise<Uint8Array> {
190
+ if (!doc) throw new NpmPackageError(502, 'upstream-invalid')
191
+ signal.throwIfAborted()
192
+ const load = loadNpmTarball(doc)
193
+ let onAbort = () => {}
194
+ const aborted = new Promise<never>((_, reject) => { onAbort = () => reject(signal.reason); signal.addEventListener('abort', onAbort, { once: true }) })
195
+ try { return await Promise.race([load.result, aborted]) } finally {
196
+ signal.removeEventListener('abort', onAbort)
197
+ load.release()
198
+ }
199
+ }
200
+
201
+ // The version `doc` names assessed against `old`'s, where given, each as the
202
+ // reader's readNpmVersion read it, or against the one risk picks of its
203
+ // versions (`'pick'`, assessNpm `oldVersion: true`), its document read as the
204
+ // open version's is where its tarball is wanted: trusted however new and however few
205
+ // download it where a team lists its scope (`teamScoped`), its own packages;
206
+ // else held to risk's minimum release age and flagged as unpopular. A new
207
+ // dependency on a package of a scope a team lists (`ownScope`, asked once a
208
+ // scope) is told no tier nor age, as an own package. Its
209
+ // documents are read with npm's token where the reader may have it
210
+ // (`privileged`, as readNpmVersion), its dependencies' without; what is kept
211
+ // of it is shared only where neither version is private, and OSV is asked of
212
+ // its advisories only where it isn't, a private package's name never sent to
213
+ // OSV, as it never is to Socket (http.ts). A `spare` one, no
214
+ // reader waiting on it, is made only within MAX_SPARE_ASSESSMENTS, and tells
215
+ // its dependencies without asking npm of their packages (assessNpm
216
+ // `dependencies`), nor its advisories, which a scan asks of a lockfile's
217
+ // packages at once (repository-risk.ts).
218
+ export function npmRisk(doc: NpmVersionDocument, old: NpmVersionDocument | 'pick' | null,
219
+ { teamScoped, ownScope = () => Promise.resolve(false), fromEmpty = false, privileged, signal, spare = false, ...stores }: NpmRiskStores & { teamScoped: boolean;
220
+ ownScope?: (scope: string) => Promise<boolean>; fromEmpty?: boolean; privileged: boolean; signal: AbortSignal; spare?: boolean }): Promise<NpmAssessment> {
221
+ const scopes = new Map<string, Promise<boolean>>()
222
+ const owned = (name: string) => {
223
+ const scope = npmPackageScope(name)
224
+ if (scope === null) return false
225
+ if (!scopes.has(scope)) scopes.set(scope, ownScope(scope))
226
+ return scopes.get(scope)!
227
+ }
228
+ const given = old === 'pick' ? null : old
229
+ // The one picked, read as the viewer reads a version, kept a day where public.
230
+ const documentOf = async (version: string) => [doc, given].find(read => read?.version === version)
231
+ ?? await readNpmVersion(doc.name, version, privileged, signal, npmVersionStore(stores.db, stores.debug)) ?? undefined
232
+ return bounded(spare, () => assessNpm(doc.name, doc.version, { oldVersion: old === 'pick' ? true : old?.version ?? null, fromEmpty,
233
+ minimumReleaseAge: teamScoped ? 0 : DEFAULT_MINIMUM_RELEASE_AGE,
234
+ popularity: !teamScoped, cache: npmRiskCache(stores, !doc.private && !given?.private), signal, dependencies: !spare, advisories: !spare, osv: !doc.private, owned,
235
+ packument: (name, { authorized }) => readNpmPackument(name, privileged && authorized, signal),
236
+ tarball: async (_name, version) => tarballOf(await documentOf(version), signal) }))
237
+ }
238
+
239
+ // An assessment made within MAX_ACTIVE_ASSESSMENTS, a `spare` one within
240
+ // MAX_SPARE_ASSESSMENTS, all across the server; one past them refused as
241
+ // busy (`npm-busy`).
242
+ async function bounded(spare: boolean, assess: () => Promise<NpmAssessment>): Promise<NpmAssessment> {
243
+ if (assessing >= (spare ? MAX_SPARE_ASSESSMENTS : MAX_ACTIVE_ASSESSMENTS)) throw new NpmPackageError(429, 'npm-busy')
244
+ assessing++
245
+ try { return await assess() } finally { assessing-- }
246
+ }
247
+
248
+ // A version npm has no document of, as risk tells one npm removed, as it
249
+ // removes every one it finds malware in (assessNpm): its package taken down
250
+ // by npm, as a scan's (`spare`), and its advisories of malware, npm's and,
251
+ // where anyone can read its package, OSV's, which alone has some of those
252
+ // npm removed (nx's), a private package's name never sent to OSV. Its
253
+ // package's document read anonymously, else with npm's token alone where
254
+ // that reads more for this reader (`privileged`, npmTokenReads), and kept as
255
+ // a private package's is; no
256
+ // tarball read, nothing of the version being left. Spare, within
257
+ // MAX_SPARE_ASSESSMENTS as a scan's others are. An NpmRiskError where
258
+ // nothing tells of it.
259
+ export function npmRiskRemoved(name: string, version: string,
260
+ { teamScoped, privileged, signal, ...stores }: NpmRiskStores & { teamScoped: boolean; privileged: boolean; signal: AbortSignal }): Promise<NpmAssessment> {
261
+ return bounded(true, async () => {
262
+ const open = await readNpmPackument(name, false, signal)
263
+ return assessNpm(name, version, { minimumReleaseAge: teamScoped ? 0 : DEFAULT_MINIMUM_RELEASE_AGE, popularity: false, downloads: false, dependencies: false,
264
+ osv: open !== null, cache: npmRiskCache(stores, false), signal,
265
+ packument: (read, { authorized }) => read === name
266
+ ? open || !npmTokenReads(name, privileged && authorized) ? Promise.resolve(open) : readNpmPackument(name, true, signal, { anonymous: false })
267
+ : readNpmPackument(read, privileged && authorized, signal),
268
+ tarball: () => Promise.reject(new NpmPackageError(502, 'upstream-invalid')) })
269
+ })
270
+ }
271
+
272
+ // What a scan readies before assessing its packages (repository-risk.ts):
273
+ // their downloads, as risk asks them, kept where a public package's are
274
+ // (npmRiskCache), so that their assessments wait on npm's downloads API for
275
+ // none. At once, those kept and unscoped ones, in bulk, all public, as only a
276
+ // scoped package can be private; each other one on its own
277
+ // (npmReadyScanDownload), kept only where npm counts some, which it does of
278
+ // public packages alone: a private one's none, as of one it has no such
279
+ // package of, isn't kept where public ones are, for its assessment to ask
280
+ // its own where private ones are.
281
+ export const npmReadyScanDownloads = (names: string[], ready: (name: string) => void, stores: NpmRiskStores, signal: AbortSignal) =>
282
+ npmReadyDownloads(names, ready, { cache: npmRiskCache(stores, true), signal })
283
+ export function npmReadyScanDownload(name: string, stores: NpmRiskStores, signal: AbortSignal) {
284
+ const cache = npmRiskCache(stores, true)
285
+ const counted = (value: unknown) => !(value && typeof value === 'object' && 'none' in value)
286
+ return npmReadyDownload(name, { cache: { read: cache.read, write: (type, key, value) => counted(value) ? cache.write(type, key, value) : Promise.resolve() }, signal })
287
+ }
@@ -0,0 +1,147 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { link, lstat, mkdir, open, readdir, rename, rm, rmdir, stat } from 'node:fs/promises'
3
+ import { dirname, join } from 'node:path'
4
+ import { type ObjectPage, type RawObjectStorage, objectPath, validateStoragePage } from './object-storage.ts'
5
+
6
+ function missing(err: unknown): boolean { return (err as NodeJS.ErrnoException).code === 'ENOENT' }
7
+ function version(info: { dev: number; ino: number; size: number; mtimeMs: number; ctimeMs: number }): string {
8
+ return JSON.stringify([info.dev, info.ino, info.size, info.mtimeMs, info.ctimeMs])
9
+ }
10
+
11
+ async function syncDirectory(dir: string): Promise<void> {
12
+ try {
13
+ const directory = await open(dir, 'r')
14
+ try { await directory.sync() } finally { await directory.close() }
15
+ } catch (err) {
16
+ // Windows and some mounted filesystems cannot open/fsync directories.
17
+ // Preserve real I/O failures; file fsync remains mandatory on every write.
18
+ if (!['EINVAL', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EISDIR', 'EBADF', 'EPERM'].includes((err as NodeJS.ErrnoException).code ?? '')) throw err
19
+ }
20
+ }
21
+
22
+ // Keyset pagination survives concurrent file creation/deletion. A final sweep
23
+ // catches objects inserted before the cursor during migration.
24
+ async function listFiles(dir: string, prefix: string, cursor: string | null, limit: number, signal?: AbortSignal): Promise<ObjectPage> {
25
+ const objects: ObjectPage['objects'] = []
26
+ async function visit(key: string): Promise<void> {
27
+ signal?.throwIfAborted()
28
+ let entries
29
+ try {
30
+ if (!(await lstat(join(dir, key))).isDirectory()) {
31
+ console.warn('managed-storage: skipping unsupported directory', JSON.stringify(key))
32
+ return
33
+ }
34
+ entries = await readdir(join(dir, key), { withFileTypes: true })
35
+ }
36
+ catch (err) { if (missing(err)) return; throw err }
37
+ const order = (entry: typeof entries[number]) => `${entry.name}${entry.isDirectory() ? '/' : ''}`
38
+ entries.sort((a, b) => order(a) < order(b) ? -1 : order(a) > order(b) ? 1 : 0)
39
+ for (const entry of entries) {
40
+ signal?.throwIfAborted()
41
+ const child = `${key}${entry.name}`
42
+ if (entry.isSymbolicLink() || (!entry.isDirectory() && !entry.isFile())) {
43
+ console.warn('managed-storage: skipping unsupported entry', JSON.stringify(child))
44
+ continue
45
+ }
46
+ try { objectPath(child) }
47
+ catch { console.warn('managed-storage: skipping invalid entry', JSON.stringify(child)); continue }
48
+ if (entry.isDirectory()) {
49
+ const folder = `${child}/`
50
+ if (cursor && folder < cursor && !cursor.startsWith(folder)) continue
51
+ await visit(folder)
52
+ if (objects.length > limit) return
53
+ }
54
+ else if (entry.isFile() && (!cursor || child > cursor)) {
55
+ try { objects.push({ key: objectPath(child), modifiedAt: (await stat(join(dir, child))).mtimeMs }) }
56
+ catch (err) { if (!missing(err)) throw err }
57
+ if (objects.length > limit) return
58
+ }
59
+ }
60
+ // Another migration worker can observe an unlink before its writer has
61
+ // synced the directory. Persist those observed removals before an empty
62
+ // inventory can mark the shared migration complete.
63
+ try { await syncDirectory(join(dir, key)) } catch (err) { if (!missing(err)) throw err }
64
+ }
65
+ validateStoragePage(prefix, limit)
66
+ await visit(prefix)
67
+ return { objects: objects.slice(0, limit), cursor: objects.length > limit ? objects[limit - 1]!.key : null }
68
+ }
69
+
70
+ export function createDiskObjectStorage(dir: string): RawObjectStorage {
71
+ const path = (key: string) => join(dir, objectPath(key))
72
+ return {
73
+ async head(key, signal) {
74
+ signal?.throwIfAborted()
75
+ try {
76
+ const info = await stat(path(key))
77
+ return { size: info.size, version: version(info), modifiedAt: info.mtimeMs }
78
+ } catch (err) { if (missing(err)) return null; throw err }
79
+ },
80
+ async open(key, signal) {
81
+ signal?.throwIfAborted()
82
+ let file
83
+ try { file = await open(path(key), 'r') }
84
+ catch (err) { if (missing(err)) return null; throw err }
85
+ try {
86
+ const info = await file.stat()
87
+ return { size: info.size, version: version(info), modifiedAt: info.mtimeMs,
88
+ stream: file.createReadStream(signal ? { signal } : {}) }
89
+ } catch (err) { await file.close(); throw err }
90
+ },
91
+ async put(key, bytes, signal, expected) {
92
+ const target = path(key)
93
+ // Temp-file + rename makes replacement atomic to readers. Concurrent
94
+ // migrations use the same persisted data key and immutable plaintext.
95
+ const temp = `${target}.${randomUUID()}.tmp`
96
+ await mkdir(dirname(target), { recursive: true })
97
+ const file = await open(temp, 'wx', 0o600)
98
+ try {
99
+ await file.writeFile(bytes, signal ? { signal } : {})
100
+ await file.sync(); await file.close()
101
+ signal?.throwIfAborted()
102
+ if (expected === null) {
103
+ try { await link(temp, target) }
104
+ catch (err) { if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false; throw err }
105
+ } else if (expected === undefined) await rename(temp, target)
106
+ else {
107
+ try { if (version(await stat(target)) !== expected) return false }
108
+ catch (err) { if (missing(err)) return false; throw err }
109
+ await rename(temp, target)
110
+ }
111
+ await syncDirectory(dirname(target))
112
+ return true
113
+ } finally { await file.close(); await rm(temp, { force: true }) }
114
+ },
115
+ async delete(key, expected, signal) {
116
+ signal?.throwIfAborted()
117
+ try {
118
+ if (expected !== undefined && version(await stat(path(key))) !== expected) return false
119
+ await rm(path(key), { force: true })
120
+ // Persist plaintext removal before migration checkpoints completion.
121
+ // Otherwise a crash could restore the directory entry after SQL has
122
+ // durably disabled further plaintext inventory sweeps.
123
+ await syncDirectory(dirname(path(key)))
124
+ return true
125
+ } catch (err) { if (missing(err)) return true; throw err }
126
+ },
127
+ async sync(key, signal) { signal?.throwIfAborted(); await syncDirectory(dirname(path(key))) },
128
+ async prune(prefix, signal) {
129
+ if (!prefix.endsWith('/')) throw new Error('Invalid storage prefix')
130
+ objectPath(`${prefix}validate`)
131
+ async function visit(folder: string): Promise<void> {
132
+ signal?.throwIfAborted()
133
+ let entries
134
+ try {
135
+ if (!(await lstat(folder)).isDirectory()) return
136
+ entries = await readdir(folder, { withFileTypes: true })
137
+ }
138
+ catch (err) { if (missing(err)) return; throw err }
139
+ for (const entry of entries) if (entry.isDirectory()) await visit(join(folder, entry.name))
140
+ try { await rmdir(folder); await syncDirectory(dirname(folder)) }
141
+ catch (err) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes((err as NodeJS.ErrnoException).code ?? '')) throw err }
142
+ }
143
+ await visit(join(dir, prefix))
144
+ },
145
+ list: (prefix, cursor, limit, signal) => listFiles(dir, prefix, cursor, limit, signal),
146
+ }
147
+ }
@@ -0,0 +1,71 @@
1
+ import { Readable } from 'node:stream'
2
+ import { Buffer } from 'node:buffer'
3
+ import { type VercelBlobSdk, isNotFound, loadVercelBlobSdk } from '../server-common/vercel-blob.ts'
4
+ import { type RawObjectStorage, objectPath, validateStoragePage } from './object-storage.ts'
5
+
6
+ // The SDK's abort option, where there is a signal to give it; and when a blob
7
+ // was last written, now where the SDK does not say.
8
+ const abortable = (signal?: AbortSignal) => signal ? { abortSignal: signal } : {}
9
+ const modifiedAt = (uploadedAt?: Date | string | number) => new Date(uploadedAt ?? Date.now()).getTime()
10
+
11
+ export async function openVercelObjectStorage(token: string, sdk?: VercelBlobSdk): Promise<RawObjectStorage> {
12
+ const blobs = sdk ?? await loadVercelBlobSdk()
13
+ const path = (key: string) => `.managed/${objectPath(key)}`
14
+ const storage: RawObjectStorage = {
15
+ async head(key, signal) {
16
+ try {
17
+ const meta = await blobs.head(path(key), { token, ...abortable(signal) })
18
+ if (!meta.etag) throw new Error('Missing object version')
19
+ return { size: meta.size, version: meta.etag, modifiedAt: modifiedAt(meta.uploadedAt) }
20
+ } catch (err) { if (isNotFound(err, blobs)) return null; throw err }
21
+ },
22
+ async open(key, signal) {
23
+ try {
24
+ // Read the stored representation: transport compression can weaken its
25
+ // ETag, which cannot satisfy ifMatch, and changes the advertised size.
26
+ const result = await blobs.get(path(key), { token, access: 'private', useCache: false,
27
+ headers: { 'accept-encoding': 'identity' }, ...abortable(signal) })
28
+ if (!result) return null
29
+ if (result.statusCode !== 200 || !result.stream || !result.blob.etag) {
30
+ await result.stream?.cancel()
31
+ throw new Error('Unexpected blob response or missing object version')
32
+ }
33
+ return { size: result.blob.size === 0 ? null : result.blob.size, version: result.blob.etag,
34
+ modifiedAt: modifiedAt(result.blob.uploadedAt),
35
+ stream: Readable.fromWeb(result.stream as Parameters<typeof Readable.fromWeb>[0], signal ? { signal } : {}) }
36
+ } catch (err) { if (isNotFound(err, blobs)) return null; throw err }
37
+ },
38
+ async put(key, bytes, signal, expected, sizeHint) {
39
+ const multipart = (sizeHint ?? (Buffer.isBuffer(bytes) ? bytes.length : Infinity)) >= 5 * 1024 * 1024
40
+ try { await blobs.put(path(key), bytes, { token, access: 'private', addRandomSuffix: false, allowOverwrite: expected !== null,
41
+ ...(expected ? { ifMatch: expected } : {}), multipart, contentType: 'application/octet-stream', cacheControlMaxAge: 60, ...abortable(signal) })
42
+ return true
43
+ } catch (err) {
44
+ if (blobs.BlobPreconditionFailedError && err instanceof blobs.BlobPreconditionFailedError) return false
45
+ // The SDK uses a generic error for an occupied pathname. Reconcile a
46
+ // create-only failure against storage; the caller verifies the winner.
47
+ if (expected === null && await storage.head(key, signal)) return false
48
+ throw err
49
+ }
50
+ },
51
+ async delete(key, version, signal) {
52
+ signal?.throwIfAborted()
53
+ try { await blobs.del(path(key), { token, ...(version ? { ifMatch: version } : {}), ...abortable(signal) }); return true }
54
+ catch (err) {
55
+ if (isNotFound(err, blobs)) return true
56
+ if (blobs.BlobPreconditionFailedError && err instanceof blobs.BlobPreconditionFailedError) return false
57
+ throw err
58
+ }
59
+ },
60
+ async list(prefix, cursor, limit, signal) {
61
+ signal?.throwIfAborted()
62
+ validateStoragePage(prefix, limit)
63
+ const page = await blobs.list({ prefix: `.managed/${prefix}`, token, limit, ...(cursor ? { cursor } : {}), ...abortable(signal) })
64
+ if (page.hasMore && (!page.cursor || page.cursor === cursor)) throw new Error('Invalid blob pagination')
65
+ return { objects: page.blobs.filter(blob => blob.pathname.startsWith(`.managed/${prefix}`)).map(blob => ({ key: blob.pathname.slice('.managed/'.length),
66
+ modifiedAt: modifiedAt(blob.uploadedAt) })),
67
+ cursor: page.hasMore ? page.cursor! : null }
68
+ },
69
+ }
70
+ return storage
71
+ }
@@ -0,0 +1,82 @@
1
+ import type { Buffer } from 'node:buffer'
2
+ import type { Readable } from 'node:stream'
3
+ import type { OpenedBlob } from './blob-store.ts'
4
+ import { validateCacheKey } from './cache-storage.ts'
5
+
6
+ export const ENCRYPTED_CACHE_PREFIX = 'cache-encrypted-v1/'
7
+ const STORAGE_PREFIXES = ['reports/', 'bundles/', 'avatars/', 'uploads/', 'cache/', ENCRYPTED_CACHE_PREFIX]
8
+ export interface RawObject extends OpenedBlob { version: string; modifiedAt: number }
9
+ type ObjectMetadata = Omit<RawObject, 'stream'>
10
+ interface ListedObject { key: string; modifiedAt: number }
11
+ export interface ObjectPage { objects: ListedObject[]; cursor: string | null }
12
+ export interface RawObjectStorage {
13
+ open(key: string, signal?: AbortSignal): Promise<RawObject | null>
14
+ head(key: string, signal?: AbortSignal): Promise<ObjectMetadata | null>
15
+ prune?(prefix: string, signal?: AbortSignal): Promise<void>
16
+ // Persist an observed disk replacement before its SQL migration checkpoint.
17
+ sync?(key: string, signal?: AbortSignal): Promise<void>
18
+ // A plaintext size hint selects multipart uploads without buffering streams.
19
+ // Publish atomically only after consuming the body through clean EOF; a body
20
+ // error must preserve the existing object (migration verifies while streaming).
21
+ // A null expected version creates only if absent, without replacing a winner.
22
+ put(key: string, bytes: Buffer | Readable, signal?: AbortSignal, expected?: string | null, sizeHint?: number): Promise<boolean>
23
+ // Return false if the original version changed; do not delete its replacement.
24
+ delete(key: string, version?: string, signal?: AbortSignal): Promise<boolean>
25
+ list(prefix: string, cursor: string | null, limit: number, signal?: AbortSignal): Promise<ObjectPage>
26
+ }
27
+ export interface ObjectStorage {
28
+ open(key: string): Promise<OpenedBlob | null>
29
+ get(key: string): Promise<Buffer | null>
30
+ exists(key: string): Promise<boolean>
31
+ put(key: string, bytes: Buffer, options?: { replaceReport?: boolean }): Promise<string | null>
32
+ delete(key: string): Promise<void>
33
+ // Every object under `prefix`, but those under `keep`, a prefix within it.
34
+ deletePrefix(prefix: string, keep?: string): Promise<void>
35
+ }
36
+
37
+ export function isBlobId(value: string): boolean {
38
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u.test(value)
39
+ }
40
+
41
+ export function objectPath(key: string): string {
42
+ validateCacheKey(key)
43
+ if (!STORAGE_PREFIXES.some(prefix => key.startsWith(prefix))) throw new Error('Invalid managed storage namespace')
44
+ return key
45
+ }
46
+
47
+ // A listing's page: `prefix` a directory of the managed namespace, `limit` a
48
+ // count of at least one.
49
+ export function validateStoragePage(prefix: string, limit: number): void {
50
+ if (!prefix.endsWith('/') || !Number.isInteger(limit) || limit < 1) throw new Error('Invalid storage page')
51
+ objectPath(`${prefix}validate`)
52
+ }
53
+
54
+ // Hash verification and migration may consume a stream before it can be used.
55
+ // Reopen only the same object version, closing any concurrent replacement.
56
+ export async function openObjectVersion(raw: RawObjectStorage, key: string, version: string, signal?: AbortSignal): Promise<RawObject | null> {
57
+ const current = await raw.open(key, signal)
58
+ if (current?.version === version) return current
59
+ current?.stream.destroy()
60
+ return null
61
+ }
62
+
63
+ export async function deleteObjects(raw: RawObjectStorage, prefix: string, signal: AbortSignal, before?: number, keep?: string): Promise<number> {
64
+ const eligible = (modifiedAt: number) => before === undefined || modifiedAt < before
65
+ // Finish listing before deleting: provider cursors may be offset-based.
66
+ const cursors = new Set<string>(), keys = new Set<string>()
67
+ let cursor: string | null = null
68
+ do {
69
+ const page = await raw.list(prefix, cursor, 100, signal)
70
+ for (const object of page.objects) if (eligible(object.modifiedAt) && (keep === undefined || !object.key.startsWith(keep))) keys.add(object.key)
71
+ cursor = page.cursor
72
+ if (cursor !== null && cursors.has(cursor)) throw new Error('Invalid blob pagination')
73
+ if (cursor !== null) cursors.add(cursor)
74
+ } while (cursor !== null)
75
+ let removed = 0
76
+ for (const key of keys) {
77
+ const stored = await raw.head(key, signal)
78
+ // Ignore stale listings and preserve concurrent replacements.
79
+ if (stored && eligible(stored.modifiedAt) && await raw.delete(key, stored.version, signal)) removed++
80
+ }
81
+ return removed
82
+ }