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

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-5AVGKFMR.js +1 -0
  111. package/out/chunk-5CJKUV53.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-6CCSTJWB.js +1 -0
  116. package/out/chunk-6VOB5WXX.js +2 -0
  117. package/out/chunk-6Y6PZ2BU.js +9 -0
  118. package/out/chunk-74JZTGTO.js +11 -0
  119. package/out/chunk-7BKKYVWR.js +7 -0
  120. package/out/chunk-7C7DWL7I.js +1 -0
  121. package/out/chunk-7HP2VYIC.js +2 -0
  122. package/out/chunk-7YFJUT2P.js +1 -0
  123. package/out/chunk-7YO4QV5P.js +1 -0
  124. package/out/chunk-A4BBBHQU.js +1 -0
  125. package/out/chunk-B64CTMVU.js +4 -0
  126. package/out/chunk-BEKYZCPX.js +14 -0
  127. package/out/chunk-C4Z6ZBXV.js +10 -0
  128. package/out/chunk-CU3FPB3P.js +1 -0
  129. package/out/chunk-DEVAORP2.js +1 -0
  130. package/out/chunk-DUASGS2O.js +8 -0
  131. package/out/chunk-DUS5ARE2.js +53 -0
  132. package/out/chunk-EEJA7JBI.js +13 -0
  133. package/out/chunk-FSU2PLJL.js +1 -0
  134. package/out/chunk-GBMAXAYK.js +3 -0
  135. package/out/chunk-GO7FT4OD.js +1 -0
  136. package/out/chunk-GX5UXWT4.js +1 -0
  137. package/out/chunk-ITUKKCCK.js +10 -0
  138. package/out/chunk-IYPY47MC.js +1 -0
  139. package/out/chunk-JXBRWLMA.js +4 -0
  140. package/out/chunk-K4XJHM2T.js +1 -0
  141. package/out/chunk-LBD3M3J6.js +1 -0
  142. package/out/chunk-LVSLM7HB.js +1 -0
  143. package/out/chunk-LVW7WWV4.js +1 -0
  144. package/out/chunk-MV66NL3G.js +3 -0
  145. package/out/chunk-N57OWFKY.js +15 -0
  146. package/out/chunk-NRPC74AM.js +1 -0
  147. package/out/chunk-OOJM4CTU.js +1 -0
  148. package/out/chunk-OWSEQOL5.js +1 -0
  149. package/out/chunk-PKLVXUEI.js +11 -0
  150. package/out/chunk-PLGH63UC.js +2 -0
  151. package/out/chunk-PNHBZGDD.js +1 -0
  152. package/out/chunk-PTFYDJUP.js +1 -0
  153. package/out/chunk-PWFUOLZK.js +17 -0
  154. package/out/chunk-PXK7EU4V.js +1 -0
  155. package/out/chunk-QD3IBSF4.js +7 -0
  156. package/out/chunk-QI66YA4F.js +1 -0
  157. package/out/chunk-QRKFPLA4.js +80 -0
  158. package/out/chunk-R3NZFXVR.js +1 -0
  159. package/out/chunk-R5O6FAW4.js +2 -0
  160. package/out/chunk-RPNO56H2.js +1 -0
  161. package/out/chunk-SSPDMA6D.js +1 -0
  162. package/out/chunk-SZWPYLPC.js +1 -0
  163. package/out/chunk-TUII34K2.js +1 -0
  164. package/out/chunk-UJP4PQJA.js +1 -0
  165. package/out/chunk-UJSJMXEG.js +1 -0
  166. package/out/chunk-UR4WYMIP.js +1 -0
  167. package/out/chunk-VHEXSGGP.js +1 -0
  168. package/out/chunk-VYYUMYVW.js +9 -0
  169. package/out/chunk-VZPPX6MV.js +1 -0
  170. package/out/chunk-WCDYSIKG.js +1 -0
  171. package/out/chunk-XM4RLC4A.js +2 -0
  172. package/out/chunk-YKCRCNYZ.js +266 -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 +341 -0
  199. package/risk/files/hosts.js +206 -0
  200. package/risk/files/readability.js +185 -0
  201. package/risk/files/runs-code.js +563 -0
  202. package/risk/files/script.js +402 -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 +247 -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 +1914 -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 +143 -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 +6324 -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,16 @@
1
+ import type { TriageRow } from './db.ts'
2
+ import { type TriageEntryPatch, isTriageBucket } from '../common/managed/triage.ts'
3
+
4
+ // A stored triage row (current state or a trail event) → its wire entry: only
5
+ // set fields present, `false` kept for flagged (the explicit un-flag tombstone
6
+ // must round-trip), and null for the row of a cleared entry (every field
7
+ // null) — the reader adopts the clear.
8
+ export function triageWireEntry(row: Pick<TriageRow, 'color' | 'triage' | 'comment' | 'fix' | 'flagged'>, legacyHistory = false): TriageEntryPatch | null {
9
+ const e: TriageEntryPatch = {}
10
+ if (row.color != null) e.color = row.color
11
+ if (isTriageBucket(row.triage)) e.triage = row.triage
12
+ if (legacyHistory && row.comment != null) e.comment = row.comment
13
+ if (row.fix != null) e.fix = row.fix
14
+ if (row.flagged != null) e.flagged = row.flagged
15
+ return Object.keys(e).length > 0 ? e : null
16
+ }
@@ -0,0 +1,161 @@
1
+ // Whether a pair of a comparison's files changed in types alone (type-only.ts),
2
+ // told in a worker (type-only-worker.js): each a file a side, `{ path, text }`,
3
+ // a side not there null, its path as it is, which says what a file is.
4
+ //
5
+ // typeOnlyStamped: as @preventive/compare's compareTrees stamps a change
6
+ // `typeOnly`. Two paths pair as one change wherever compareTrees takes them
7
+ // for a rename at all; where it doesn't, the pair is types only where each of
8
+ // its two changes is: the file gone erasing whole, and the one come erasing
9
+ // whole or leaving a single bare `export {}`, which nothing loaded before.
10
+ //
11
+ // typeOnlyRuns: one it doesn't stamp may still hold types alone but for what
12
+ // runs on each side, each side there a declaration file proveTypeOnly proves,
13
+ // its runtime what changed: a module load added, gone or another, or a file
14
+ // added or removed that loads one, as a zod schema's declarations do. Told
15
+ // then are the lines that hold what runs on each side (`runs` the base's,
16
+ // `otherRuns` the other's, none for a side not there), for the viewer to diff
17
+ // those alone with its types set aside: the hashbang, each statement Node's
18
+ // type stripping leaves to run (a module load, `export {}`, `export default`
19
+ // of a name), each comment it keeps that may be one a tool reads (a
20
+ // triple-slash directive, a source map or source URL pragma), told wide of
21
+ // the proof's own grammar for them, so none it reads is ever set aside, and
22
+ // each enum, whose members compile into what reads them (runLines). A
23
+ // line holding any of it is told whole; a range is `[from, to)` of lines
24
+ // counted from zero, as the viewer splits a text at `\n`. None are told of
25
+ // a pair where a diff of those lines would not show what changed: a
26
+ // triple-slash comment that leads one side, where a directive steers, and
27
+ // stands below a statement on the other, where it is prose, its line the same
28
+ // on both (`moved`). Its diff is drawn whole, as one not proven is.
29
+ //
30
+ // Each sets aside a file's own source map comment, as tsc writes one with a
31
+ // declaration map: its last line exactly `//# sourceMappingURL=` its own name
32
+ // `.map`, a newline after it or none (withoutOwnMap). It names the file's own
33
+ // map, for a debugger alone, and is taken for one of its types: the file is
34
+ // proven, and its lines that run told, without it.
35
+ import { stripTypeScriptTypes } from 'node:module'
36
+ import { compareTrees, proveTypeOnly } from '@preventive/compare'
37
+ import { parseSync } from 'oxc-parser'
38
+
39
+ // A declaration file as compareTrees takes one: `.d.ts`, `.d.mts`, `.d.cts`,
40
+ // and `.d.css.ts` for a `.css` file's.
41
+ const DECLARATION = /\.d\.(?:[^./]+\.)?[cm]?ts$/u
42
+ // A comment that may be a directive (`/// <reference .../>`) or a pragma
43
+ // (`//# sourceMappingURL=`, and its legacy `//@` and block forms).
44
+ const STEERING = /^\/(?:\/\/|[/*][#@])/u
45
+ const BLANK = /^\s*$/u
46
+
47
+ const tree = file => (file ? [{ name: file.path, data: file.text }] : [])
48
+
49
+ // A file without its own source map comment, where its last line is that and
50
+ // nothing else: `//# sourceMappingURL=` and its name, `user.d.ts.map` for
51
+ // `types/user.d.ts`, ending the file with a newline or without. Any other
52
+ // name or spelling, or anything after it, and the file is as it is; so too
53
+ // where its own name is not plain (PLAIN_NAME): one holding a line terminator
54
+ // would end the comment within it, and what follows would run, so no other
55
+ // character than Latin letters, digits, `-`, `_` and `.` is taken in one.
56
+ const PLAIN_NAME = /^[A-Za-z0-9._-]+$/u
57
+ function withoutOwnMap(file) {
58
+ if (file === null) return null
59
+ const name = file.path.slice(file.path.lastIndexOf('/') + 1)
60
+ if (!PLAIN_NAME.test(name)) return file
61
+ const comment = `//# sourceMappingURL=${name}.map`
62
+ for (const last of [comment, `${comment}\n`]) {
63
+ const before = file.text.endsWith(last) ? file.text.slice(0, -last.length) : null
64
+ if (before !== null && (before === '' || before === '\uFEFF' || before.endsWith('\n'))) return { ...file, text: before }
65
+ }
66
+ return file
67
+ }
68
+
69
+ // Two the same but for their own source map comments changed nothing else:
70
+ // in types alone, where each is a declaration file proven to hold types alone.
71
+ export function typeOnlyStamped(from, to) {
72
+ const [base, other] = [from, to].map(withoutOwnMap)
73
+ const changes = compareTrees(tree(base), tree(other), { paths: 'keys', lines: false, renames: Number.MIN_VALUE })
74
+ if (changes.length > 0) return changes.every(change => change.typeOnly === true)
75
+ return [base, other].every(file => file !== null && DECLARATION.test(file.path) && proveTypeOnly(file.text).proven)
76
+ }
77
+
78
+ // Each enum a program declares, wherever it stands: exported, or within a
79
+ // namespace, a module or `declare global`. Stripping erases one whole, yet its
80
+ // members are values: tsc writes a const enum's member into the code that
81
+ // reads it (`E.A` emitted as `1`), and a const enum's member may be computed
82
+ // from any enum's, so a change to one changes what runs elsewhere, and none is
83
+ // folded as types alone. Statements alone hold one, so lists of them alone are
84
+ // walked, a work list as namespaces nest.
85
+ function enumsOf(program) {
86
+ const found = [], lists = [program.body]
87
+ while (lists.length > 0) {
88
+ for (const statement of lists.pop()) {
89
+ let node = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement
90
+ if (node?.type === 'TSEnumDeclaration') found.push(node)
91
+ while (node?.type === 'TSModuleDeclaration') node = node.body
92
+ if (node?.type === 'TSModuleBlock') lists.push(node.body)
93
+ }
94
+ }
95
+ return found
96
+ }
97
+
98
+ // The lines of a text proven to hold types alone but for what runs that hold
99
+ // any of that, as merged ranges (`lines`), and its triple-slash comments, by
100
+ // whether each leads it (`leading`, `below`). Stripping blanks what it erases
101
+ // in place, each character to a blank, so a statement it leaves blank is
102
+ // erased and one it leaves anything of runs, as the proof found, and a comment
103
+ // it leaves is kept; what it reads starts past a byte order mark, and so do
104
+ // the offsets in its tree. An enum, which stripping blanks, is told among them
105
+ // all the same (enumsOf), so that no fold sets one aside as types alone.
106
+ function runLines(text) {
107
+ const shift = text.startsWith('\uFEFF') ? 1 : 0
108
+ const body = text.slice(shift)
109
+ const code = stripTypeScriptTypes(body, { mode: 'strip' })
110
+ const { program, comments } = parseSync('file.ts', body, { lang: 'ts', sourceType: 'module' })
111
+ const kept = ({ start, end }) => code.slice(start, end)
112
+ const steering = comments.filter(comment => STEERING.test(kept(comment)))
113
+ const spans = [...program.hashbang ? [program.hashbang] : [], ...program.body.filter(statement => !BLANK.test(kept(statement))), ...steering, ...enumsOf(program)]
114
+ const starts = [0]
115
+ for (let at = text.indexOf('\n'); at !== -1; at = text.indexOf('\n', at + 1)) starts.push(at + 1)
116
+ // The line an offset of the text is on: the last whose start is at most it.
117
+ const lineAt = offset => {
118
+ let high = starts.length - 1, low = 0
119
+ while (low < high) {
120
+ const mid = Math.ceil((low + high) / 2)
121
+ if (starts[mid] <= offset) low = mid
122
+ else high = mid - 1
123
+ }
124
+ return low
125
+ }
126
+ const ranges = []
127
+ for (const { start, end } of spans.toSorted((a, b) => a.start - b.start)) {
128
+ const from = lineAt(shift + start), to = lineAt(shift + Math.max(start, end - 1)) + 1
129
+ const last = ranges.at(-1)
130
+ if (last && from <= last[1]) last[1] = Math.max(last[1], to)
131
+ else ranges.push([from, to])
132
+ }
133
+ // Its triple-slash comments, by their text: those that lead it, before its
134
+ // first statement, where alone a directive steers, and those below one.
135
+ const first = program.body[0]?.start ?? Infinity
136
+ const slashed = leads => new Set(steering.filter(comment => (comment.start < first) === leads).map(kept).filter(comment => comment.startsWith('///')))
137
+ return { lines: ranges, leading: slashed(true), below: slashed(false) }
138
+ }
139
+
140
+ // Whether a triple-slash comment that leads `one` side stands only below a
141
+ // statement on the `other`: a directive that steers on one alone, though its
142
+ // line reads the same on both.
143
+ const moved = (one, other) => [...one.leading].some(comment => !other.leading.has(comment) && other.below.has(comment))
144
+
145
+ // `{ runs, otherRuns }` where each side there is a declaration file proven to
146
+ // hold types alone but for what runs, and no directive steers on one side
147
+ // alone unseen (`moved`); else false, and where the proof throws, as no
148
+ // check should. Asked of a pair not stamped, which always runs some.
149
+ export function typeOnlyRuns(...pair) {
150
+ const [from, to] = pair.map(withoutOwnMap)
151
+ const sides = [from, to].filter(file => file !== null)
152
+ if (sides.length === 0 || !sides.every(file => DECLARATION.test(file.path))) return false
153
+ try {
154
+ if (!sides.every(file => proveTypeOnly(file.text).proven)) return false
155
+ const [base, other] = [from, to].map(file => (file ? runLines(file.text) : null))
156
+ if (base && other && (moved(base, other) || moved(other, base))) return false
157
+ return { runs: base?.lines ?? [], otherRuns: other?.lines ?? [] }
158
+ } catch {
159
+ return false
160
+ }
161
+ }
@@ -0,0 +1,31 @@
1
+ // Which of a comparison's pairs of files changed in types alone (type-only.ts),
2
+ // off the server's event loop, as type-only-proof.js tells each. Told first,
3
+ // `{ stamped }`, is whether each is stamped, by pair: what runs is worked out
4
+ // after, so that it cannot cost a stamp the worker's deadline, however long
5
+ // one file's takes. Then, where asked for (`runsUntil` a time, not null),
6
+ // what runs of each pair not stamped, `{ at, runs, otherRuns }` as each is
7
+ // found, the smallest files first, so that one that takes long keeps the
8
+ // fewest waiting, and none begun once `runsUntil` has come. Last, its answer,
9
+ // by pair: `true`, `{ runs, otherRuns }` for one that holds types alone but
10
+ // for what runs, or `false`, as for one not asked for or not come to.
11
+ import { parentPort, workerData } from 'node:worker_threads'
12
+ import { typeOnlyRuns, typeOnlyStamped } from './type-only-proof.js'
13
+
14
+ const { pairs, runsUntil } = workerData
15
+ // Node worker messages have no browser target origin.
16
+ // oxlint-disable-next-line unicorn/require-post-message-target-origin
17
+ const tell = told => parentPort.postMessage(told)
18
+ const answer = pairs.map(([from, to]) => typeOnlyStamped(from, to))
19
+ tell({ stamped: answer })
20
+ if (runsUntil !== null) {
21
+ const size = ([from, to]) => (from?.text.length ?? 0) + (to?.text.length ?? 0)
22
+ const rest = [...pairs.keys()].filter(at => !answer[at]).toSorted((a, b) => size(pairs[a]) - size(pairs[b]))
23
+ for (const at of rest) {
24
+ if (Date.now() >= runsUntil) break
25
+ const runs = typeOnlyRuns(...pairs[at])
26
+ if (!runs) continue
27
+ answer[at] = runs
28
+ tell({ at, ...runs })
29
+ }
30
+ }
31
+ tell(answer)
@@ -0,0 +1,135 @@
1
+ // Compare's changes to TypeScript declaration files in types alone (GET
2
+ // /api/bundles/:id/type-only?other=, GET /api/npm/type-only): every file
3
+ // that changed between a comparison's two sides, added and removed ones too,
4
+ // paired as its viewer pairs them (rename-diff.ts comparedFiles), whose
5
+ // change @preventive/compare's compareTrees stamps
6
+ // `typeOnly` -- each side there a file named as a declaration file and
7
+ // proven to hold types alone but for a runtime, the module loads and
8
+ // `export {}` its stripping leaves, that the change leaves as it was, an
9
+ // added one's empty or a single bare `export {}` (proveTypeOnly) -- and
10
+ // nothing else. Asked with `runs=1`, those too that hold types alone but for
11
+ // a runtime the change does not leave as it was, each with the lines holding
12
+ // that runtime on either side (type-only-proof.js), as many as there is time
13
+ // left for once every file is stamped, which none of them costs a stamp: a
14
+ // viewer that does not ask takes every line for a change in types alone.
15
+ // Proven in a worker, off the event loop, a comparison at a time per process,
16
+ // for at most a minute; told a line each, `{ path, hash, otherPath,
17
+ // otherHash }`, a side not there null, and `runs` and `otherRuns` where those
18
+ // are told, which the viewer checks name the files it shows. Access is the
19
+ // caller's to check. Where this Node proves nothing (proofUnsupported), a
20
+ // comparison of any TypeScript file is refused (501 proof-unsupported), not
21
+ // told as one of none changed in types alone.
22
+ import { proveTypeOnly } from '@preventive/compare'
23
+ import { pathOrder } from './npm-packages.ts'
24
+ import { type ComparedSide, PrettyError, type PrettyRequest } from './pretty-print.ts'
25
+ import { comparedFiles } from './rename-diff.ts'
26
+ import { workerTurns } from './worker-turns.ts'
27
+
28
+ // TypeScript files, by extension as the pretty-print cache reads them: none
29
+ // other is asked about.
30
+ const TYPESCRIPT = new Set(['ts', 'mts', 'cts'])
31
+ // Comparisons proven at once per process, and those waiting their turn past
32
+ // them, any more refused; the longest one may take, its wait included.
33
+ const MAX_ACTIVE_PROOFS = 1
34
+ const MAX_WAITING_PROOFS = 16
35
+ const PROOF_TIMEOUT_MS = 60_000
36
+ // What runs is begun of no pair once this little of that is left, so the
37
+ // answer comes that long before the deadline but for the pair being worked
38
+ // out, which may take any time: a file of many module loads takes minutes
39
+ // (@preventive/compare's proof is quadratic in them). One still not done at
40
+ // the deadline costs what runs of it and of those after it, never a stamp.
41
+ const RUNS_MARGIN_MS = 15_000
42
+
43
+ type File = PrettyRequest & { text: string }
44
+ // A range of lines, `[from, to)`, counted from zero.
45
+ type Lines = [number, number]
46
+ export interface TypeOnlyLine { path: string | null; hash: string | null; otherPath: string | null; otherHash: string | null; runs?: Lines[]; otherRuns?: Lines[] }
47
+ type Proof = boolean | { runs: Lines[]; otherRuns: Lines[] }
48
+
49
+ // Whether a request asks for the files that hold types alone but for what runs too.
50
+ export const runsAsked = (params: URLSearchParams) => params.get('runs') === '1'
51
+
52
+ const workers = workerTurns({ what: 'type-only proof', active: MAX_ACTIVE_PROOFS, waiting: MAX_WAITING_PROOFS, error: PrettyError,
53
+ busy: 'proof-busy', timeout: 'proof-timeout', failed: 'unproven' })
54
+
55
+ const ranges = (told: unknown): told is Lines[] => Array.isArray(told)
56
+ && told.every(range => Array.isArray(range) && range.length === 2 && range.every(Number.isSafeInteger) && range[0] >= 0 && range[0] < range[1])
57
+ const runsOf = (told: unknown): told is { runs: Lines[]; otherRuns: Lines[] } => typeof told === 'object' && told !== null
58
+ && 'runs' in told && 'otherRuns' in told && ranges(told.runs) && ranges(told.otherRuns)
59
+ const proof = (told: unknown): told is Proof => typeof told === 'boolean' || runsOf(told)
60
+
61
+ // What a worker of `count` pairs told before its answer, as the answer to
62
+ // settle for should it be gone without one (type-only-worker.js): every stamp
63
+ // first, `{ stamped }`, then what runs of a pair it told as not stamped, `{
64
+ // at, runs, otherRuns }`, one at a time, each pair not come to as not stamped.
65
+ // A function of each thing it tells, as workers.run asks one: that answer so
66
+ // far, or null for what is neither, its own answer among it.
67
+ export function proofsSoFar(count: number): (told: unknown) => Proof[] | null {
68
+ let sofar: Proof[] | null = null
69
+ return told => {
70
+ if (typeof told !== 'object' || told === null) return null
71
+ if ('stamped' in told) {
72
+ const { stamped } = told
73
+ if (sofar !== null || !Array.isArray(stamped) || stamped.length !== count || !stamped.every(one => typeof one === 'boolean')) return null
74
+ sofar = [...stamped]
75
+ return sofar
76
+ }
77
+ if (sofar === null || !('at' in told) || typeof told.at !== 'number' || sofar[told.at] !== false || !runsOf(told)) return null
78
+ sofar[told.at] = { runs: told.runs, otherRuns: told.otherRuns }
79
+ return sofar
80
+ }
81
+ }
82
+
83
+ // Which of `pairs` compareTrees stamps types only, by index, and with `runs`
84
+ // which hold types alone but for what runs, with its lines, as many as there
85
+ // is time for, in a worker settled once it is gone; none where it fails, as
86
+ // no proof should. One gone before its answer, its deadline come on a file
87
+ // that takes long or its memory run out, is answered for as far as it told
88
+ // (proofsSoFar): what runs is worked out after every stamp, and costs none.
89
+ function proven(pairs: Array<[File | null, File | null]>, runs: boolean, deadline: number): Promise<Proof[]> {
90
+ return workers.run(new URL('./type-only-worker.js', import.meta.url), {
91
+ workerData: { pairs: pairs.map(sides => sides.map(file => file && { path: file.path, text: file.text })), runsUntil: runs ? deadline - RUNS_MARGIN_MS : null },
92
+ // Node's type stripping, which the proof holds oxc's tree to, warns it is experimental.
93
+ execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1024 },
94
+ }, (told): Proof[] | null => (Array.isArray(told) && told.length === pairs.length && told.every(proof) ? told : null), deadline, proofsSoFar(pairs.length))
95
+ }
96
+
97
+ // Why this Node proves nothing, or null: proveTypeOnly tells every text
98
+ // `unsupported` alike where the Node has no type stripping of its own, or no
99
+ // parser loads, or its stripping writes otherwise than the proof holds it to
100
+ // (as amaro 1.2, Node's stripping since, writes ASCII spaces where 1.1 wrote
101
+ // blanks of the bytes it erased). Found once, as the worker would find it,
102
+ // and logged then: an empty text is proven wherever proving is.
103
+ let unsupported: string | null | undefined
104
+ export function proofUnsupported(): string | null {
105
+ if (unsupported === undefined) {
106
+ unsupported = proveTypeOnly('').proven ? null : `Node ${process.version}, amaro ${process.versions['amaro'] ?? 'none'}`
107
+ if (unsupported !== null) console.warn(`managed: no file can be proven to change in types alone on ${unsupported}: @preventive/compare's proveTypeOnly finds it unsupported`)
108
+ }
109
+ return unsupported
110
+ }
111
+
112
+ // The files that changed between a comparison's two sides in types alone,
113
+ // as the viewer pairs them, and with `runs` those in types alone but for what
114
+ // runs, a line each once all are proven, in path order.
115
+ export function typeOnlyFiles([base, other]: readonly [ComparedSide, ComparedSide], runs = false): AsyncGenerator<TypeOnlyLine> {
116
+ const typescript = ({ files }: ComparedSide) => new Map(files.filter(file => TYPESCRIPT.has(file.extension)).map(file => [file.path, file]))
117
+ const [olds, news] = [typescript(base), typescript(other)]
118
+ const { changed, onlyBase, onlyOther } = comparedFiles([base, other])
119
+ // A side there not a TypeScript file this reads leaves its pair out; one not there is null.
120
+ const pairs = [...changed.map(({ path, basePath = path }) => [olds.get(basePath), news.get(path)]),
121
+ ...onlyBase.map(({ path, basePath = path }) => [olds.get(basePath), null]), ...onlyOther.map(({ path }) => [null, news.get(path)])]
122
+ .filter((sides): sides is [File | null, File | null] => sides.every(file => file !== undefined) && sides.some(file => file !== null) && sides[0]?.hash !== sides[1]?.hash)
123
+ .toSorted(([a, b], [c, d]) => pathOrder((b ?? a)!.path, (d ?? c)!.path))
124
+ // Thrown before any line is streamed, so that its status is sent.
125
+ if (pairs.length > 0 && proofUnsupported() !== null) throw new PrettyError(501, 'proof-unsupported')
126
+ return (async function* () {
127
+ if (pairs.length === 0) return
128
+ const deadline = Date.now() + PROOF_TIMEOUT_MS
129
+ const stamped = await workers.inTurn(deadline, () => proven(pairs, runs, deadline))
130
+ for (const [i, [from, to]] of pairs.entries()) {
131
+ const told = stamped[i]
132
+ if (told) yield { path: from?.path ?? null, hash: from?.hash ?? null, otherPath: to?.path ?? null, otherHash: to?.hash ?? null, ...told !== true && told }
133
+ }
134
+ })()
135
+ }
@@ -0,0 +1,106 @@
1
+ // Staging is shared storage, never process memory. Each part is bound to the
2
+ // authenticated session, destination and random upload ID. No bearer URL is
3
+ // exposed; all reads/writes still pass the managed role/origin/CSRF gates.
4
+ import { Buffer } from 'node:buffer'
5
+ import { createHash, generateKeyPairSync } from 'node:crypto'
6
+ import type { IncomingMessage } from 'node:http'
7
+ import type { BlobStore } from './blob-store.ts'
8
+ import { isBlobId } from './object-storage.ts'
9
+ import { maxSealedBytes, openUpload } from '../common/managed/upload-seal.ts'
10
+
11
+ export const UPLOAD_CHUNK_BYTES = 3 * 1024 * 1024
12
+ export const MAX_UPLOAD_BYTES = 1024 * 1024 * 1024
13
+ // Staged parts may carry a sealed body, slightly larger than its content.
14
+ const MAX_STAGED_BYTES = maxSealedBytes(MAX_UPLOAD_BYTES)
15
+ const MAX_UPLOAD_PARTS = Math.ceil(MAX_STAGED_BYTES / UPLOAD_CHUNK_BYTES)
16
+ export type UploadKind = 'reports' | 'bundles'
17
+
18
+ function partId(session: string, kind: UploadKind, id: string, index: number): string {
19
+ const hash = createHash('sha256').update(JSON.stringify([session, kind, id, index])).digest('hex').slice(0, 32)
20
+ return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20)}`
21
+ }
22
+
23
+ export function validUploadPart(id: string, index: number, maxBytes: number): boolean {
24
+ return isBlobId(id) && Number.isSafeInteger(index) && index >= 0 && index < Math.ceil(Math.min(maxSealedBytes(maxBytes), MAX_STAGED_BYTES) / UPLOAD_CHUNK_BYTES)
25
+ }
26
+
27
+ export function validUpload(id: string, count: number): boolean {
28
+ return isBlobId(id) && Number.isSafeInteger(count) && count > 0
29
+ }
30
+
31
+ // Limit cleanup to indices that any configured server could have accepted,
32
+ // even if the request advertises an enormous count or the limit was lowered.
33
+ export async function deleteUpload(store: BlobStore, session: string, kind: UploadKind, id: string, count: number): Promise<void> {
34
+ if (!validUpload(id, count)) throw new Error('bad-upload')
35
+ const end = Math.min(count, MAX_UPLOAD_PARTS), errors = []
36
+ for (let start = 0; start < end; start += 8) {
37
+ const results = await Promise.allSettled(Array.from({ length: Math.min(8, end - start) },
38
+ (_, index) => store.delete(partId(session, kind, id, start + index))))
39
+ for (const result of results) if (result.status === 'rejected') errors.push(result.reason)
40
+ }
41
+ if (errors.length > 0) throw new AggregateError(errors, 'Upload cleanup failed')
42
+ }
43
+
44
+ export async function putUploadPart(store: BlobStore, session: string, kind: UploadKind, id: string, index: number, bytes: Buffer): Promise<void> {
45
+ await store.put(partId(session, kind, id, index), bytes)
46
+ }
47
+
48
+ // Parts read at once while an upload is put together.
49
+ const PARTS_READ_AT_ONCE = 6
50
+
51
+ // The staged upload `req` names, its parts read a few at a time into the one
52
+ // buffer it fills, each as long as its place in it. Its parts are deleted
53
+ // once read, or once it fails: awaited, unless `behind` takes that cleanup to
54
+ // go on past the response (http.ts), which staging maintenance backs up.
55
+ export async function readUpload(store: BlobStore, req: IncomingMessage, session: string, kind: UploadKind, maxBytes: number,
56
+ behind?: (cleanup: Promise<void>) => void): Promise<Buffer> {
57
+ const id = req.headers['x-upload-id']
58
+ const count = Number(req.headers['x-upload-parts']), size = Number(req.headers['x-upload-size'])
59
+ if (typeof id !== 'string' || !validUpload(id, count)) throw new Error('bad-upload')
60
+ try {
61
+ if (!Number.isSafeInteger(size) || size <= 0 || count !== Math.ceil(size / UPLOAD_CHUNK_BYTES)) throw new Error('bad-upload')
62
+ if (size > maxBytes || size > MAX_STAGED_BYTES) throw new Error('too-large')
63
+ // Every byte of it is written below before it is returned: each part
64
+ // must fill its place exactly, or the upload fails.
65
+ const body = Buffer.allocUnsafe(size)
66
+ let failed = false, next = 0
67
+ const readParts = async () => {
68
+ while (!failed && next < count) {
69
+ const index = next++
70
+ const bytes = await store.get(partId(session, kind, id, index))
71
+ const expected = Math.min(UPLOAD_CHUNK_BYTES, size - index * UPLOAD_CHUNK_BYTES)
72
+ if (!bytes || bytes.length !== expected) { failed = true; throw new Error('bad-upload') }
73
+ bytes.copy(body, index * UPLOAD_CHUNK_BYTES)
74
+ }
75
+ }
76
+ // Each read settled before its parts are deleted.
77
+ const results = await Promise.allSettled(Array.from({ length: Math.min(PARTS_READ_AT_ONCE, count) }, readParts))
78
+ const rejected = results.find(result => result.status === 'rejected')
79
+ if (rejected) throw rejected.reason
80
+ return body
81
+ } finally {
82
+ // These bytes can no longer be finalized. Failed/abandoned chunk uploads
83
+ // are also covered by automatic staging maintenance.
84
+ const cleanup = deleteUpload(store, session, kind, id, count).catch(err => console.warn('managed: upload cleanup failed:', err))
85
+ if (behind) behind(cleanup)
86
+ else await cleanup
87
+ }
88
+ }
89
+
90
+ // A session's upload key pair, stored as its private JWK.
91
+ export function newUploadKey(): string {
92
+ const { privateKey } = generateKeyPairSync('x25519')
93
+ const { kty, crv, x, d } = privateKey.export({ format: 'jwk' })
94
+ return JSON.stringify({ kty, crv, x, d })
95
+ }
96
+
97
+ // The raw public key (base64url) browsers seal this session's uploads to.
98
+ export function uploadPublicKey(key: string): string {
99
+ return (JSON.parse(key) as { x: string }).x
100
+ }
101
+
102
+ export async function openSessionUpload(key: string | null | undefined, sealed: Buffer, maxBytes: number): Promise<Buffer> {
103
+ if (!key) throw new Error('bad-upload')
104
+ const bytes = await openUpload(new Uint8Array(sealed.buffer as ArrayBuffer, sealed.byteOffset, sealed.byteLength), JSON.parse(key) as JsonWebKey, maxBytes)
105
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
106
+ }