@preventive/triage 1.0.0-alpha.9 → 1.0.0-alpha.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (448) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +16 -78
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +6 -0
  13. package/common/bundle-compare-diff.js +378 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-imports.js +20 -0
  20. package/common/bundle-metadata.d.ts +15 -0
  21. package/common/bundle-metadata.js +226 -0
  22. package/common/bundle-pkg-of.d.ts +1 -0
  23. package/common/bundle-pkg-of.js +90 -0
  24. package/common/bundle-reasons.d.ts +6 -0
  25. package/common/bundle-reasons.js +58 -0
  26. package/common/bundle-source-links.d.ts +6 -0
  27. package/common/bundle-source-links.js +216 -0
  28. package/common/bundle-sourcemap.d.ts +10 -0
  29. package/common/bundle-sourcemap.js +100 -0
  30. package/common/bundle-sources.d.ts +10 -0
  31. package/common/bundle-sources.js +374 -0
  32. package/common/bundle-stats.js +41 -0
  33. package/common/bundle-tabs.js +1 -0
  34. package/common/code-language.js +80 -0
  35. package/common/default-scan-models.ts +37 -0
  36. package/common/dependency-reviews.d.ts +19 -0
  37. package/common/dependency-reviews.js +67 -0
  38. package/common/finding-duplicates.js +63 -0
  39. package/common/finding-filters.js +313 -0
  40. package/common/finding-id.js +47 -0
  41. package/common/finding-repo.d.ts +5 -0
  42. package/common/finding-repo.js +67 -0
  43. package/common/github-issue-labels.d.ts +3 -0
  44. package/common/github-issue-labels.js +42 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +15 -0
  48. package/common/line-diff.js +188 -0
  49. package/common/linked-workspace-groups.js +63 -0
  50. package/common/managed/agent-tasks.ts +292 -0
  51. package/common/managed/comments.ts +43 -0
  52. package/common/managed/dependency-routes.js +25 -0
  53. package/common/managed/directory-packages.ts +28 -0
  54. package/common/managed/finding-detail.d.ts +5 -0
  55. package/common/managed/finding-detail.js +75 -0
  56. package/common/managed/finding-values.d.ts +2 -0
  57. package/common/managed/finding-values.js +138 -0
  58. package/common/managed/github-agents.ts +114 -0
  59. package/common/managed/github-logins.ts +49 -0
  60. package/common/managed/lite-name.d.ts +2 -0
  61. package/common/managed/lite-name.js +20 -0
  62. package/common/managed/npm-packages.d.ts +9 -0
  63. package/common/managed/npm-packages.js +63 -0
  64. package/common/managed/permissions.ts +31 -0
  65. package/common/managed/report-content.ts +72 -0
  66. package/common/managed/report-filter.ts +120 -0
  67. package/common/managed/repository-alias.ts +65 -0
  68. package/common/managed/review-view-routes.js +23 -0
  69. package/common/managed/risk-routes.js +30 -0
  70. package/common/managed/roles.ts +48 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +386 -0
  73. package/common/managed/scan-models.ts +6 -0
  74. package/common/managed/stasis-config.ts +7 -0
  75. package/common/managed/team-app.d.ts +19 -0
  76. package/common/managed/team-app.js +129 -0
  77. package/common/managed/team-filters.js +26 -0
  78. package/common/managed/triage.ts +83 -0
  79. package/common/managed/upload-seal.ts +126 -0
  80. package/common/npm-token.d.ts +2 -0
  81. package/common/npm-token.js +14 -0
  82. package/common/pretty-json.js +123 -0
  83. package/common/pretty-kinds.js +20 -0
  84. package/common/pretty-print.d.ts +7 -0
  85. package/common/pretty-print.js +41 -0
  86. package/common/pretty-sourcemap.js +70 -0
  87. package/common/repo-commit.d.ts +4 -0
  88. package/common/repo-commit.js +30 -0
  89. package/common/revalidation-conflicts.js +48 -0
  90. package/common/revalidation-input-groups.js +56 -0
  91. package/common/scan-server.ts +13 -0
  92. package/common/security-links.d.ts +5 -0
  93. package/common/security-links.js +33 -0
  94. package/common/server-info.ts +46 -0
  95. package/common/sourcemap-listing.js +78 -0
  96. package/common/sourcemap-mappings.js +136 -0
  97. package/common/sourcemap-unlist.js +85 -0
  98. package/common/stasis-files.d.ts +5 -0
  99. package/common/stasis-files.js +20 -0
  100. package/common/stasis-tgz.d.ts +6 -0
  101. package/common/stasis-tgz.js +27 -0
  102. package/common/utf8.d.ts +3 -0
  103. package/common/utf8.js +45 -0
  104. package/common/whitespace-insensitive.js +19 -0
  105. package/common/workspace-app.js +91 -0
  106. package/common/workspace-groups.js +176 -0
  107. package/out/activity.js +2 -0
  108. package/out/brotli-fallback.js +3 -3
  109. package/out/chunk-2XUEZHIP.js +28 -0
  110. package/out/chunk-3DOSBILK.js +4 -0
  111. package/out/chunk-55YIWY3H.js +5 -0
  112. package/out/chunk-5AVGKFMR.js +1 -0
  113. package/out/chunk-5PWEAEA5.js +1 -0
  114. package/out/chunk-6VOB5WXX.js +2 -0
  115. package/out/chunk-6Y6PZ2BU.js +9 -0
  116. package/out/chunk-74JZTGTO.js +11 -0
  117. package/out/chunk-7BKKYVWR.js +7 -0
  118. package/out/chunk-7C7DWL7I.js +1 -0
  119. package/out/chunk-7HP2VYIC.js +2 -0
  120. package/out/chunk-7YFJUT2P.js +1 -0
  121. package/out/chunk-A4BBBHQU.js +1 -0
  122. package/out/chunk-B64CTMVU.js +4 -0
  123. package/out/chunk-BEKYZCPX.js +14 -0
  124. package/out/chunk-BZJU5EEV.js +1 -0
  125. package/out/chunk-C4Z6ZBXV.js +10 -0
  126. package/out/chunk-CJVMNJDZ.js +3 -0
  127. package/out/chunk-CU3FPB3P.js +1 -0
  128. package/out/chunk-DEVAORP2.js +1 -0
  129. package/out/chunk-DUASGS2O.js +8 -0
  130. package/out/chunk-EEJA7JBI.js +13 -0
  131. package/out/chunk-ESXA7KID.js +1 -0
  132. package/out/chunk-FSU2PLJL.js +1 -0
  133. package/out/chunk-GO7FT4OD.js +1 -0
  134. package/out/chunk-GX5UXWT4.js +1 -0
  135. package/out/chunk-HGWFRZNC.js +267 -0
  136. package/out/chunk-IYPY47MC.js +1 -0
  137. package/out/chunk-JZAROLQT.js +40 -0
  138. package/out/chunk-K4XJHM2T.js +1 -0
  139. package/out/chunk-KP2XM324.js +6 -0
  140. package/out/chunk-LRWB6QVO.js +1 -0
  141. package/out/chunk-LVSLM7HB.js +1 -0
  142. package/out/chunk-LVW7WWV4.js +1 -0
  143. package/out/chunk-N57OWFKY.js +15 -0
  144. package/out/chunk-NRPC74AM.js +1 -0
  145. package/out/chunk-OOJM4CTU.js +1 -0
  146. package/out/chunk-PKLVXUEI.js +11 -0
  147. package/out/chunk-PLGH63UC.js +2 -0
  148. package/out/chunk-PNHBZGDD.js +1 -0
  149. package/out/chunk-PWFUOLZK.js +17 -0
  150. package/out/chunk-PXK7EU4V.js +1 -0
  151. package/out/chunk-QD3IBSF4.js +7 -0
  152. package/out/chunk-QI66YA4F.js +1 -0
  153. package/out/chunk-QRKFPLA4.js +80 -0
  154. package/out/chunk-R3NZFXVR.js +1 -0
  155. package/out/chunk-R5O6FAW4.js +2 -0
  156. package/out/chunk-RAM3GDAD.js +1 -0
  157. package/out/chunk-RPNO56H2.js +1 -0
  158. package/out/chunk-SMNFBOLO.js +10 -0
  159. package/out/chunk-SSPDMA6D.js +1 -0
  160. package/out/chunk-SZTCJVZJ.js +55 -0
  161. package/out/chunk-SZWPYLPC.js +1 -0
  162. package/out/chunk-TKPNRQNN.js +3 -0
  163. package/out/chunk-TUII34K2.js +1 -0
  164. package/out/chunk-UJP4PQJA.js +1 -0
  165. package/out/chunk-UJSJMXEG.js +1 -0
  166. package/out/chunk-UR4WYMIP.js +1 -0
  167. package/out/chunk-UTYWTUTC.js +1 -0
  168. package/out/chunk-VHEXSGGP.js +1 -0
  169. package/out/chunk-VYYUMYVW.js +9 -0
  170. package/out/chunk-WBK5ZN4K.js +3 -0
  171. package/out/chunk-WCDYSIKG.js +1 -0
  172. package/out/chunk-XM4RLC4A.js +2 -0
  173. package/out/chunk-XRAAYXPR.js +1 -0
  174. package/out/chunk-ZQHLECTI.js +1 -0
  175. package/out/client-managed-import.js +4 -0
  176. package/out/client-managed.js +35 -0
  177. package/out/client-sync.js +11 -17
  178. package/out/compare.js +26 -0
  179. package/out/dialogs.js +40 -0
  180. package/out/github-issue-authorized.html +3 -0
  181. package/out/github-issue-authorized.js +1 -0
  182. package/out/graph.js +19 -5
  183. package/out/index.html +105 -25
  184. package/out/prism.js +14 -10
  185. package/out/scan.js +2 -0
  186. package/out/stasis.svg +20 -0
  187. package/out/terminal.js +367 -39
  188. package/out/view.css +1 -1
  189. package/out/view.js +19 -148
  190. package/package.json +416 -64
  191. package/risk/actions/findings.js +161 -0
  192. package/risk/actions/resolve.js +287 -0
  193. package/risk/actions/scripts/commands.js +182 -0
  194. package/risk/actions/scripts/grade.js +113 -0
  195. package/risk/actions/scripts/packages.js +123 -0
  196. package/risk/actions/scripts/shell.js +169 -0
  197. package/risk/actions/uses.js +94 -0
  198. package/risk/actions/workflow.js +183 -0
  199. package/risk/files/characters.js +354 -0
  200. package/risk/files/hosts.js +206 -0
  201. package/risk/files/readability.js +185 -0
  202. package/risk/files/runs-code.js +568 -0
  203. package/risk/files/script.js +420 -0
  204. package/risk/files/source-map-link.js +43 -0
  205. package/risk/files/stamps.js +47 -0
  206. package/risk/index.d.ts +309 -0
  207. package/risk/index.js +12 -0
  208. package/risk/npm/assess.js +303 -0
  209. package/risk/npm/combined.js +68 -0
  210. package/risk/npm/compare.js +236 -0
  211. package/risk/npm/dependencies.js +172 -0
  212. package/risk/npm/diff.js +79 -0
  213. package/risk/npm/downloads.js +84 -0
  214. package/risk/npm/files.js +445 -0
  215. package/risk/npm/held.js +67 -0
  216. package/risk/npm/install-scripts.js +34 -0
  217. package/risk/npm/malware.js +38 -0
  218. package/risk/npm/manifest.js +65 -0
  219. package/risk/npm/new-dependency.js +60 -0
  220. package/risk/npm/old-version.js +108 -0
  221. package/risk/npm/registry.js +401 -0
  222. package/risk/npm/release.js +85 -0
  223. package/risk/npm/score.js +59 -0
  224. package/risk/npm/specs.js +124 -0
  225. package/risk/npm/tarball.js +169 -0
  226. package/server-common/database-config.ts +16 -0
  227. package/server-common/initialize.ts +18 -0
  228. package/server-common/npm-advisories.ts +101 -0
  229. package/{server → server-common}/origin.ts +5 -5
  230. package/server-common/reap.ts +48 -0
  231. package/server-common/scan-config.ts +19 -0
  232. package/server-common/standalone.ts +29 -0
  233. package/server-common/storage-crypto.ts +182 -0
  234. package/server-common/storage-log.ts +38 -0
  235. package/server-common/vercel-blob.ts +103 -0
  236. package/server-e2e/app.ts +487 -0
  237. package/{server → server-e2e}/bus-receiver.ts +2 -1
  238. package/{server → server-e2e}/cli.js +9 -4
  239. package/{server → server-e2e}/config.ts +52 -42
  240. package/{server → server-e2e}/db-neon.ts +2 -2
  241. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  242. package/{server → server-e2e}/db-stmt.ts +2 -2
  243. package/{server → server-e2e}/db.ts +7 -7
  244. package/{server → server-e2e}/http.ts +44 -13
  245. package/{server → server-e2e}/hub.ts +40 -9
  246. package/server-e2e/index.ts +17 -0
  247. package/server-e2e/lifecycle.ts +95 -0
  248. package/{server → server-e2e}/neon-driver.ts +2 -2
  249. package/{server → server-e2e}/npm-proxy.ts +12 -145
  250. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  251. package/{server → server-e2e}/objstore/blob.ts +1 -1
  252. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  253. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  254. package/{server → server-e2e}/objstore/init.ts +19 -27
  255. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  257. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  258. package/{server → server-e2e}/objstore/rest.ts +3 -3
  259. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  260. package/{server → server-e2e}/objstore/store.ts +7 -7
  261. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  262. package/{server → server-e2e}/pubsub.ts +12 -9
  263. package/{server → server-e2e}/sign.ts +4 -4
  264. package/{server → server-e2e}/sse-server.ts +3 -3
  265. package/{server → server-e2e}/static.ts +18 -17
  266. package/{server → server-e2e}/sync-handlers.ts +56 -30
  267. package/{server → server-e2e}/ws-server.ts +20 -9
  268. package/server-managed/activity.ts +269 -0
  269. package/server-managed/agent-merges.ts +109 -0
  270. package/server-managed/app-agents.ts +23 -0
  271. package/server-managed/avatar-store.ts +21 -0
  272. package/server-managed/blob-store.ts +26 -0
  273. package/server-managed/brotli.ts +10 -0
  274. package/server-managed/bundle-advisories.ts +176 -0
  275. package/server-managed/bundle-advisory-inventory.ts +85 -0
  276. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  277. package/server-managed/bundle-build-diagnostics.js +23 -0
  278. package/server-managed/bundle-build-leases.ts +41 -0
  279. package/server-managed/bundle-build-worker.js +387 -0
  280. package/server-managed/bundle-build.ts +328 -0
  281. package/server-managed/bundle-cache.ts +261 -0
  282. package/server-managed/bundle-catalog.ts +29 -0
  283. package/server-managed/bundle-commits.ts +133 -0
  284. package/server-managed/bundle-dependency-reviews.ts +91 -0
  285. package/server-managed/bundle-store.ts +24 -0
  286. package/server-managed/bundle-summary-cache.ts +139 -0
  287. package/server-managed/bundle-validation.ts +33 -0
  288. package/server-managed/bundle.ts +151 -0
  289. package/server-managed/cache-storage.ts +20 -0
  290. package/server-managed/cli.js +21 -0
  291. package/server-managed/combined.ts +43 -0
  292. package/server-managed/comments.ts +138 -0
  293. package/server-managed/commit-coauthors.ts +105 -0
  294. package/server-managed/commit-lockfiles.ts +78 -0
  295. package/server-managed/comparison.ts +51 -0
  296. package/server-managed/config.ts +163 -0
  297. package/server-managed/content-access.ts +15 -0
  298. package/server-managed/crypto.ts +25 -0
  299. package/server-managed/db-methods.ts +1950 -0
  300. package/server-managed/db-neon.ts +401 -0
  301. package/server-managed/db-schema.ts +271 -0
  302. package/server-managed/db-table-names.ts +22 -0
  303. package/server-managed/db.ts +150 -0
  304. package/server-managed/dependabot-access.ts +85 -0
  305. package/server-managed/dependabot-alerts.ts +197 -0
  306. package/server-managed/dependency-review-comments.ts +158 -0
  307. package/server-managed/dependency-reviews.ts +369 -0
  308. package/server-managed/github-accounts.ts +59 -0
  309. package/server-managed/github-actions.ts +71 -0
  310. package/server-managed/github-app.ts +347 -0
  311. package/server-managed/github-errors.ts +92 -0
  312. package/server-managed/github-graphql.ts +42 -0
  313. package/server-managed/github-issue-links.ts +264 -0
  314. package/server-managed/github-issue-oauth.ts +30 -0
  315. package/server-managed/github-issues.ts +169 -0
  316. package/server-managed/github-link-oauth.ts +56 -0
  317. package/server-managed/github-links.ts +204 -0
  318. package/server-managed/github-metadata.ts +218 -0
  319. package/server-managed/github-oauth.ts +264 -0
  320. package/server-managed/github-pulls.ts +290 -0
  321. package/server-managed/github-requests.ts +181 -0
  322. package/server-managed/github-users.ts +53 -0
  323. package/server-managed/github-values.ts +26 -0
  324. package/server-managed/history-windows.ts +172 -0
  325. package/server-managed/http-response.ts +76 -0
  326. package/server-managed/http.ts +6722 -0
  327. package/server-managed/import-triage.ts +51 -0
  328. package/server-managed/index.ts +204 -0
  329. package/server-managed/kept-briefly.ts +37 -0
  330. package/server-managed/kept.ts +28 -0
  331. package/server-managed/known-listings.ts +112 -0
  332. package/server-managed/link-reports.ts +149 -0
  333. package/server-managed/listed-activity.ts +39 -0
  334. package/server-managed/locked-packages.ts +234 -0
  335. package/server-managed/lockfile-scope.ts +58 -0
  336. package/server-managed/lru.ts +30 -0
  337. package/server-managed/managed-issues.ts +92 -0
  338. package/server-managed/management-catalog.ts +45 -0
  339. package/server-managed/management.ts +116 -0
  340. package/server-managed/npm-delta-worker.js +203 -0
  341. package/server-managed/npm-delta.ts +277 -0
  342. package/server-managed/npm-insights.ts +455 -0
  343. package/server-managed/npm-kept.ts +274 -0
  344. package/server-managed/npm-loads.ts +259 -0
  345. package/server-managed/npm-manifest.ts +117 -0
  346. package/server-managed/npm-packages.ts +477 -0
  347. package/server-managed/npm-patch-paths.ts +86 -0
  348. package/server-managed/npm-patch.ts +457 -0
  349. package/server-managed/npm-provenance.ts +127 -0
  350. package/server-managed/npm-risk.ts +310 -0
  351. package/server-managed/object-storage-disk.ts +147 -0
  352. package/server-managed/object-storage-vercel.ts +71 -0
  353. package/server-managed/object-storage.ts +82 -0
  354. package/server-managed/package-entry-points.ts +127 -0
  355. package/server-managed/pretty-copies.ts +22 -0
  356. package/server-managed/pretty-format.d.ts +4 -0
  357. package/server-managed/pretty-format.js +27 -0
  358. package/server-managed/pretty-print.ts +444 -0
  359. package/server-managed/public-workspace.ts +242 -0
  360. package/server-managed/pull-comment-reviews.ts +161 -0
  361. package/server-managed/pull-dependencies.ts +370 -0
  362. package/server-managed/pull-dependency-reviews.ts +458 -0
  363. package/server-managed/pull-reviews.ts +202 -0
  364. package/server-managed/pulse-walk.ts +164 -0
  365. package/server-managed/queue.ts +54 -0
  366. package/server-managed/release-commits.ts +85 -0
  367. package/server-managed/rename-diff-worker.js +30 -0
  368. package/server-managed/rename-diff.ts +237 -0
  369. package/server-managed/repo-path.ts +21 -0
  370. package/server-managed/report-migration.ts +32 -0
  371. package/server-managed/report-opening.ts +77 -0
  372. package/server-managed/report-query.ts +10 -0
  373. package/server-managed/report-response.ts +16 -0
  374. package/server-managed/report-sources.ts +185 -0
  375. package/server-managed/report-store.ts +77 -0
  376. package/server-managed/repository-actions.ts +220 -0
  377. package/server-managed/repository-agents.ts +422 -0
  378. package/server-managed/repository-aliases.ts +119 -0
  379. package/server-managed/repository-browser.ts +362 -0
  380. package/server-managed/repository-changes.ts +280 -0
  381. package/server-managed/repository-code.ts +222 -0
  382. package/server-managed/repository-dependency-reviews.ts +220 -0
  383. package/server-managed/repository-discovery.ts +83 -0
  384. package/server-managed/repository-history.ts +444 -0
  385. package/server-managed/repository-issues.ts +293 -0
  386. package/server-managed/repository-policy.ts +27 -0
  387. package/server-managed/repository-pulls.ts +207 -0
  388. package/server-managed/repository-pulse.ts +409 -0
  389. package/server-managed/repository-risk-assess.ts +179 -0
  390. package/server-managed/repository-risk-audit.ts +145 -0
  391. package/server-managed/repository-risk-caches.ts +56 -0
  392. package/server-managed/repository-risk-kept.ts +86 -0
  393. package/server-managed/repository-risk-read.ts +296 -0
  394. package/server-managed/repository-risk-stasis.ts +61 -0
  395. package/server-managed/repository-risk-turn.ts +97 -0
  396. package/server-managed/repository-risk.ts +528 -0
  397. package/server-managed/repository-squashes.ts +160 -0
  398. package/server-managed/repository-stamp.ts +41 -0
  399. package/server-managed/request-timing.ts +63 -0
  400. package/server-managed/reviewed-dependencies.ts +170 -0
  401. package/server-managed/revisions.ts +35 -0
  402. package/server-managed/scan-downloads.ts +121 -0
  403. package/server-managed/session.ts +132 -0
  404. package/server-managed/slugs.ts +38 -0
  405. package/server-managed/solidity-entry-points.ts +71 -0
  406. package/server-managed/sql-postgres.ts +34 -0
  407. package/server-managed/sql.ts +107 -0
  408. package/server-managed/stasis-config.ts +147 -0
  409. package/server-managed/stasis-dependencies.ts +280 -0
  410. package/server-managed/static.ts +28 -0
  411. package/server-managed/storage-command.ts +16 -0
  412. package/server-managed/storage-db.ts +183 -0
  413. package/server-managed/storage-encryption.ts +288 -0
  414. package/server-managed/storage-maintenance.ts +259 -0
  415. package/server-managed/storage-payload.ts +121 -0
  416. package/server-managed/storage-stores.ts +91 -0
  417. package/server-managed/storage.ts +82 -0
  418. package/server-managed/team-app-summaries.ts +57 -0
  419. package/server-managed/team-app.ts +162 -0
  420. package/server-managed/team-catalog.ts +7 -0
  421. package/server-managed/team-feed.ts +180 -0
  422. package/server-managed/team-icons.ts +50 -0
  423. package/server-managed/team-npm-scopes.ts +103 -0
  424. package/server-managed/team-progress.ts +77 -0
  425. package/server-managed/team-reports.ts +369 -0
  426. package/server-managed/triage-response.ts +16 -0
  427. package/server-managed/type-only-proof.js +181 -0
  428. package/server-managed/type-only-worker.js +31 -0
  429. package/server-managed/type-only.ts +135 -0
  430. package/server-managed/uploads.ts +106 -0
  431. package/server-managed/upstream-cache.ts +275 -0
  432. package/server-managed/view-as.ts +58 -0
  433. package/server-managed/worker-turns.ts +76 -0
  434. package/server-managed/workspace-shares.ts +170 -0
  435. package/server.ts +70 -0
  436. package/strip-types-loader.js +13 -10
  437. package/server/index.ts +0 -480
  438. package/server/lifecycle.ts +0 -208
  439. /package/{LICENSE → LICENSE-MIT} +0 -0
  440. /package/{server → server-e2e}/auth.ts +0 -0
  441. /package/{server → server-e2e}/config.example.json +0 -0
  442. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  443. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  444. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  445. /package/{server → server-e2e}/peer.ts +0 -0
  446. /package/{server → server-e2e}/sse-session.ts +0 -0
  447. /package/{server → server-e2e}/util.ts +0 -0
  448. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,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
+ }
@@ -0,0 +1,275 @@
1
+ import { Buffer } from 'node:buffer'
2
+ import { constants } from 'node:fs'
3
+ import { mkdir, open, rename, rm, writeFile } from 'node:fs/promises'
4
+ import { dirname, join } from 'node:path'
5
+ import { promisify } from 'node:util'
6
+ import { gunzip, gzip } from 'node:zlib'
7
+ import type { CacheStore, Package } from '@preventive/upstream/advisories.js'
8
+ import type { ManagedSql } from './sql.ts'
9
+
10
+ // Records @preventive/upstream would otherwise keep in its disk cache, shared
11
+ // by every instance: each repository's published advisory listing, written by
12
+ // dependency audits that ask repositories, keyed `github/advisories/owner/name`;
13
+ // and, written by audits that ask OSV, each npm package npm's registry serves
14
+ // anyone, keyed `npm/public/name`, and each GitHub repository github.com
15
+ // serves anyone, a `github` package's, keyed `github/public/owner/name`.
16
+ // Upstream stamps, validates and expires each value (90 minutes for a listing,
17
+ // a month for a public name); a refresh replaces the row, and there is one row
18
+ // per repository or name, so rows are not evicted. Only public repositories
19
+ // publish advisories, and only names anyone may read are kept: rows are shared
20
+ // across viewers.
21
+ export const UPSTREAM_CACHE_SCHEMA = `
22
+ CREATE TABLE IF NOT EXISTS managed_upstream_cache (
23
+ cache_key TEXT PRIMARY KEY,
24
+ value TEXT NOT NULL,
25
+ cached_at INTEGER NOT NULL
26
+ ) STRICT;
27
+ `
28
+
29
+ export interface UpstreamCacheStore {
30
+ getUpstreamCacheEntry(key: string): Promise<string | null>
31
+ // Key → value for those of `keys` that are kept.
32
+ getUpstreamCacheEntries(keys: string[]): Promise<Map<string, string>>
33
+ // Those of `first` that are kept; where none is, those of `then`, in the
34
+ // same statement (`first` whether they are `first`'s).
35
+ getFirstUpstreamCacheEntries(first: string[], then: string[]): Promise<{ first: boolean; entries: Map<string, string> }>
36
+ setUpstreamCacheEntry(key: string, value: string, cachedAt: number): Promise<void>
37
+ // Each of `entries` (key, value), as setUpstreamCacheEntry keeps one, in one
38
+ // statement: the last of a key given twice.
39
+ setUpstreamCacheEntries(entries: [key: string, value: string][], cachedAt: number): Promise<void>
40
+ // Removes those under `prefix` (no LIKE wildcard in it) kept before `before`;
41
+ // how many.
42
+ deleteUpstreamCacheEntries(prefix: string, before: number): Promise<number>
43
+ }
44
+
45
+ export function upstreamCacheMethods(db: ManagedSql): UpstreamCacheStore {
46
+ const get = db.prepare('SELECT value FROM managed_upstream_cache WHERE cache_key = ?')
47
+ const getMany = db.prepare('SELECT cache_key, value FROM managed_upstream_cache WHERE cache_key IN (SELECT value FROM json_each(?))')
48
+ const getFirst = db.prepare(`WITH found AS (SELECT cache_key, value FROM managed_upstream_cache WHERE cache_key IN (SELECT value FROM json_each(?)))
49
+ SELECT cache_key, value, 1 AS in_first FROM found
50
+ UNION ALL SELECT cache_key, value, 0 AS in_first FROM managed_upstream_cache
51
+ WHERE cache_key IN (SELECT value FROM json_each(?)) AND NOT EXISTS (SELECT 1 FROM found)`)
52
+ // The statement keeping as many as `rows` at once. A slower concurrent audit
53
+ // cannot replace a newer listing with an older one.
54
+ const insert = (rows: number) => db.prepare(`INSERT INTO managed_upstream_cache (cache_key, value, cached_at) VALUES ${Array.from({ length: rows }, () => '(?, ?, ?)').join(', ')}
55
+ ON CONFLICT (cache_key) DO UPDATE SET value = excluded.value, cached_at = excluded.cached_at
56
+ WHERE managed_upstream_cache.cached_at <= excluded.cached_at`)
57
+ const set = insert(1)
58
+ const remove = db.prepare('DELETE FROM managed_upstream_cache WHERE cache_key LIKE ? AND cached_at < ?')
59
+ // setUpstreamCacheEntries's, by how many it keeps at once.
60
+ const setMany = new Map<number, ReturnType<ManagedSql['prepare']>>()
61
+ return {
62
+ async getUpstreamCacheEntry(key) {
63
+ const row = await get.get(key) as { value: string } | undefined
64
+ return row?.value ?? null
65
+ },
66
+ async getUpstreamCacheEntries(keys) {
67
+ if (keys.length === 0) return new Map()
68
+ const rows = await getMany.all(JSON.stringify(keys)) as { cache_key: string; value: string }[]
69
+ return new Map(rows.map(row => [row.cache_key, row.value]))
70
+ },
71
+ async getFirstUpstreamCacheEntries(first, then) {
72
+ if (first.length === 0 && then.length === 0) return { first: false, entries: new Map() }
73
+ const rows = await getFirst.all(JSON.stringify(first), JSON.stringify(then)) as { cache_key: string; value: string; in_first: number }[]
74
+ return { first: rows.some(row => Number(row.in_first) === 1), entries: new Map(rows.map(row => [row.cache_key, row.value])) }
75
+ },
76
+ async setUpstreamCacheEntry(key, value, cachedAt) {
77
+ await set.run(key, value, cachedAt)
78
+ },
79
+ async setUpstreamCacheEntries(entries, cachedAt) {
80
+ const rows = [...new Map(entries)]
81
+ if (rows.length === 0) return
82
+ let many = setMany.get(rows.length)
83
+ if (!many) setMany.set(rows.length, many = insert(rows.length))
84
+ await many.run(...rows.flatMap(([key, value]) => [key, value, cachedAt]))
85
+ },
86
+ async deleteUpstreamCacheEntries(prefix, before) {
87
+ return Number((await remove.run(`${prefix}%`, before)).changes)
88
+ },
89
+ }
90
+ }
91
+
92
+ // An audit's `cache`: this store keeps listings and public names
93
+ // (upstreamCache), those of `keys` (auditedKeys) read at once, shared by every
94
+ // instance and with every other place that asks for listings
95
+ // (known-listings.ts); where the server has an upstream disk cache (off
96
+ // Vercel, set at startup), that keeps the rest (diskCache), else nothing does.
97
+ export function auditCache(cacheDir: string | null | undefined, db: UpstreamCacheStore, signal: AbortSignal, debug = false, keys: Iterable<string> = []): CacheStore {
98
+ const kept = upstreamCache(db, signal, debug, keys)
99
+ if (!cacheDir) return kept
100
+ const disk = diskCache(cacheDir)
101
+ return { read: (type, key) => (CACHED_TYPES.has(type) ? kept : disk).read(type, key),
102
+ write: (type, key, value) => (CACHED_TYPES.has(type) ? kept : disk).write(type, key, value) }
103
+ }
104
+
105
+ // Only listings and public names are kept: upstream's other records (npm
106
+ // version documents, registries' repository lookups) read as misses and are
107
+ // not written.
108
+ export const LISTINGS = 'github/advisories'
109
+ const PUBLIC_NAMES = 'npm/public'
110
+ const PUBLIC_REPOS = 'github/public'
111
+ const CACHED_TYPES = new Set([LISTINGS, PUBLIC_NAMES, PUBLIC_REPOS])
112
+
113
+ // What an audit of `packages` reads first, where it is already known: the
114
+ // listings of the repositories it knows, each `github` package, each `soldeer`
115
+ // package's given repository, and with `repoAdvisories`, every other
116
+ // package's, upstream looking up the rest itself; and whether each npm package,
117
+ // and each `github` package's repository but one said `internal`, is public, as
118
+ // upstream asks before it asks OSV of it. Each as upstream asks for it, a
119
+ // listing and a repository by its lowercased name.
120
+ export function auditedKeys(packages: Iterable<Package>, repoAdvisories: boolean): string[] {
121
+ return [...new Set([...packages].flatMap(pkg => {
122
+ const repo = pkg.ecosystem === 'github' ? pkg.name : pkg.ecosystem === 'soldeer' || repoAdvisories ? pkg.github : undefined
123
+ const asked = pkg.ecosystem === 'npm' ? [`${PUBLIC_NAMES}/${pkg.name}`]
124
+ : pkg.ecosystem === 'github' && pkg.internal !== true ? [`${PUBLIC_REPOS}/${pkg.name.toLowerCase()}`] : []
125
+ return [...asked, ...repo === undefined ? [] : [`${LISTINGS}/${repo.toLowerCase()}`]]
126
+ }))]
127
+ }
128
+
129
+ // The cache is an optimization: a database failure is a miss, never a failed
130
+ // audit. Upstream keeps listing after an abandoned audit; once `signal` aborts,
131
+ // the request's database work is over and the store is left alone.
132
+ // Upstream reads one listing at a time per repository, and whether a name is
133
+ // public eight at a time, and a request's queries share one connection (Neon),
134
+ // so a recheck of hundreds of packages would wait on as many round trips: the
135
+ // first read asks for every one of `keys` at once. Any other key, or all of
136
+ // them if that read fails, is read alone.
137
+ export function upstreamCache(db: UpstreamCacheStore, signal: AbortSignal, debug = false, keys: Iterable<string> = []): CacheStore {
138
+ const batched = new Set(keys)
139
+ let batch: Promise<Map<string, string> | null> | undefined
140
+ const readBatch = () => batch ??= db.getUpstreamCacheEntries([...batched]).catch((error: unknown) => {
141
+ if (debug) console.warn('managed: upstream cache read failed:', error)
142
+ return null
143
+ })
144
+ return {
145
+ async read(type, key) {
146
+ if (!CACHED_TYPES.has(type) || signal.aborted) return null
147
+ const cacheKey = `${type}/${key}`
148
+ try {
149
+ const found = batched.has(cacheKey) ? await readBatch() : null
150
+ const value = found ? found.get(cacheKey) ?? null : await db.getUpstreamCacheEntry(cacheKey)
151
+ return value === null ? null : JSON.parse(value) as unknown
152
+ } catch (error) {
153
+ if (debug) console.warn('managed: upstream cache read failed:', error)
154
+ return null
155
+ }
156
+ },
157
+ async write(type, key, value) {
158
+ if (!CACHED_TYPES.has(type) || signal.aborted) return
159
+ try { await db.setUpstreamCacheEntry(`${type}/${key}`, JSON.stringify(value), Date.now()) } catch (error) {
160
+ if (debug) console.warn('managed: upstream cache write failed:', error)
161
+ }
162
+ },
163
+ }
164
+ }
165
+
166
+ // The file upstream keeps `file` in, under `dir` of its disk cache
167
+ // (setCacheDir), as its cachePath names it: `@babel+core@7.29.7.tgz`, a
168
+ // capital written `!` and the letter, and a Windows device name's first
169
+ // letter escaped.
170
+ export function upstreamCachePath(root: string, dir: string, file: string): string {
171
+ const name = encodeURIComponent(file.replaceAll(/[!A-Z]/gu, char => `!${char.toLowerCase()}`))
172
+ .replaceAll('%40', '@').replaceAll('%2F', '+')
173
+ .replace(/^(?=(?:con|prn|aux|nul|com\d|lpt\d)(?:\.|$))./u, char => `%${char.codePointAt(0)!.toString(16).toUpperCase()}`)
174
+ return join(root, dir, name)
175
+ }
176
+
177
+ // A kept file, where it is a regular file of at most `max` bytes, checked on
178
+ // the file as opened (a FIFO or device would block or never end), and read
179
+ // to the size it had then.
180
+ export async function readKeptFile(path: string, max: number): Promise<Uint8Array | null> {
181
+ const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK).catch(() => null)
182
+ if (!handle) return null
183
+ try {
184
+ const stats = await handle.stat()
185
+ if (!stats.isFile() || stats.size > max) return null
186
+ const bytes = Buffer.allocUnsafe(stats.size)
187
+ for (let at = 0; at < bytes.length;) {
188
+ const { bytesRead } = await handle.read(bytes, at, bytes.length - at, at)
189
+ if (bytesRead === 0) return null
190
+ at += bytesRead
191
+ }
192
+ return bytes
193
+ } catch { return null }
194
+ finally { await handle.close() }
195
+ }
196
+
197
+ // `bytes` kept at `path`, written whole beside it first and then moved in, so a
198
+ // reader finds the old file or the new one, never part of one; a failure
199
+ // keeps nothing.
200
+ let tmpSeq = 0
201
+ export async function keepFile(path: string, bytes: Uint8Array) {
202
+ const tmp = `${path}.${process.pid}.${++tmpSeq}.tmp`
203
+ try {
204
+ await mkdir(dirname(path), { recursive: true })
205
+ await writeFile(tmp, bytes)
206
+ await rename(tmp, path)
207
+ } catch { await rm(tmp, { force: true }).catch(() => {}) }
208
+ }
209
+
210
+ const gunzipAsync = promisify(gunzip)
211
+ const gzipAsync = promisify(gzip)
212
+
213
+ // An upstream's JSON object kept with its ETag, gzipped, as keepJson keeps it:
214
+ // `{ etag, json }`, or null where none is kept, or what is can't be read
215
+ // within `limit` bytes.
216
+ export async function readKeptJson(path: string, limit: number): Promise<{ etag: string; json: Record<string, unknown> } | null> {
217
+ const bytes = await readKeptFile(path, limit)
218
+ if (!bytes) return null
219
+ const object = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
220
+ try {
221
+ const kept: unknown = JSON.parse((await gunzipAsync(bytes, { maxOutputLength: limit + 1024 })).toString('utf8'))
222
+ return object(kept) && typeof kept['etag'] === 'string' && object(kept['json']) ? { etag: kept['etag'], json: kept['json'] } : null
223
+ } catch { return null }
224
+ }
225
+
226
+ // `body`, an upstream's JSON object as it wrote it, kept with its `etag`.
227
+ export async function keepJson(path: string, etag: string, body: Buffer) {
228
+ await keepFile(path, await gzipAsync(Buffer.concat([Buffer.from(`{"etag":${JSON.stringify(etag)},"json":`), body, Buffer.from('}')])))
229
+ }
230
+
231
+ // Upstream's disk cache at `root` (setCacheDir) as a store of what audits
232
+ // keep there, all JSON, each in the file upstream's own reads and writes use:
233
+ // `key.json`, gzipped as `key.json.gz` in the directories upstream gzips, and
234
+ // read to no more than upstream reads (its MAX_BYTES). Bytes, which audits
235
+ // don't keep, aren't kept.
236
+ const GZIPPED = new Set([LISTINGS, 'npm/versions', 'rubysec/index', 'rubysec/advisories'])
237
+ const KEPT_BYTES = 512 * 1024 * 1024
238
+ const utf8 = new TextDecoder('utf-8', { fatal: true })
239
+ function diskCache(root: string): CacheStore {
240
+ const pathOf = (type: string, key: string) => upstreamCachePath(root, type, GZIPPED.has(type) ? `${key}.json.gz` : `${key}.json`)
241
+ return {
242
+ async read(type, key) {
243
+ const bytes = await readKeptFile(pathOf(type, key), KEPT_BYTES)
244
+ try { return bytes && JSON.parse(utf8.decode(GZIPPED.has(type) ? await gunzipAsync(bytes, { maxOutputLength: KEPT_BYTES }) : bytes)) as unknown } catch { return null }
245
+ },
246
+ async write(type, key, value) {
247
+ if (value instanceof Uint8Array) return
248
+ const json = Buffer.from(JSON.stringify(value))
249
+ await keepFile(pathOf(type, key), GZIPPED.has(type) ? await gzipAsync(json) : json)
250
+ },
251
+ }
252
+ }
253
+
254
+ // A repository's listing as last kept (upstreamCache), however old, for when
255
+ // GitHub can't be reached to refresh it: `at`, when it was kept, and `cache`,
256
+ // a store answering it to upstream as kept just now, so that upstream takes
257
+ // it rather than ask GitHub, and keeping nothing. Upstream checks it as it
258
+ // checks its own. Null where none is kept, or it can't be read.
259
+ export async function lastListing(db: UpstreamCacheStore, repo: string, debug = false): Promise<{ at: number; cache: CacheStore } | null> {
260
+ const key = repo.toLowerCase()
261
+ let kept: { at?: unknown } | null
262
+ try {
263
+ const value = await db.getUpstreamCacheEntry(`${LISTINGS}/${key}`)
264
+ kept = value === null ? null : JSON.parse(value)
265
+ } catch (error) {
266
+ if (debug) console.warn('managed: kept listing read failed:', error)
267
+ return null
268
+ }
269
+ const at = kept?.at
270
+ if (typeof at !== 'number') return null
271
+ return { at, cache: {
272
+ read: (type, name) => Promise.resolve(type === LISTINGS && name === key ? { ...kept, at: Date.now() } : null),
273
+ write: () => Promise.resolve(),
274
+ } }
275
+ }
@@ -0,0 +1,58 @@
1
+ // An administrator's read-only view as another user, for checking what that
2
+ // account can access. The view is a session row for the viewed user (so every
3
+ // access check applies that user's role, teams and permissions unchanged) tied
4
+ // to the admin's own session, carried in its own cookie beside the session
5
+ // cookie. Ending the admin session, or the admin role, ends the view.
6
+ //
7
+ // The router refuses writes for any request that carries the view cookie, and
8
+ // such requests never act with the viewed user's GitHub credentials: GitHub
9
+ // data that needs them is left out instead.
10
+ import { AsyncLocalStorage } from 'node:async_hooks'
11
+ import type { ManagedConfig } from './config.ts'
12
+ import type { ManagedDb, ManagedSession } from './db.ts'
13
+ import { hashToken, randomToken } from './crypto.ts'
14
+ import { VIEW_COOKIE, buildCookie, clearCookie, cookieName, parseCookies } from './session.ts'
15
+
16
+ export const VIEW_AS_PATH = '/api/auth/view-as'
17
+ export const VIEW_ONLY_ERROR = 'view-only'
18
+
19
+ function viewCookieName(config: ManagedConfig): string {
20
+ return cookieName(config, VIEW_COOKIE)
21
+ }
22
+
23
+ // The raw view token, or null when the request carries no view.
24
+ export function viewToken(config: ManagedConfig, cookieHeader: string | undefined): string | null {
25
+ const token = parseCookies(cookieHeader).get(viewCookieName(config))
26
+ return token == null || token === '' ? null : token
27
+ }
28
+
29
+ export function clearViewCookie(config: ManagedConfig): string {
30
+ return clearCookie(viewCookieName(config), config.cookieSecure)
31
+ }
32
+
33
+ // Open a view as `userId` from the admin's `session`, replacing any earlier
34
+ // view of that session. Null when the database refuses it (see createViewSession).
35
+ export async function startViewSession(config: ManagedConfig, db: ManagedDb, session: ManagedSession, userId: string, now: number): Promise<string | null> {
36
+ const token = randomToken()
37
+ const ok = await db.createViewSession({ id: hashToken(token), viewerSessionId: session.id, userId, csrfToken: randomToken() }, now)
38
+ if (!ok) return null
39
+ return buildCookie(viewCookieName(config), token, {
40
+ maxAgeS: Math.max(0, Math.floor((session.expiresAt - now) / 1000)), secure: config.cookieSecure, sameSite: 'Lax',
41
+ })
42
+ }
43
+
44
+ export async function endViewSession(config: ManagedConfig, db: ManagedDb, cookieHeader: string | undefined): Promise<void> {
45
+ const token = viewToken(config, cookieHeader)
46
+ if (token != null) await db.deleteSession(hashToken(token))
47
+ }
48
+
49
+ const viewing = new AsyncLocalStorage<boolean>()
50
+
51
+ export function runViewing<T>(active: boolean, work: () => T): T {
52
+ return active ? viewing.run(true, work) : work()
53
+ }
54
+
55
+ // Whether the current request is an admin's view as another user.
56
+ export function isViewing(): boolean {
57
+ return viewing.getStore() === true
58
+ }
@@ -0,0 +1,76 @@
1
+ // Jobs worked out each in a worker of its own, off the event loop
2
+ // (npm-delta.ts, rename-diff.ts, type-only.ts): as many at once per process
3
+ // as `active`, those waiting their turn past them as many as `waiting`, any
4
+ // more refused (429 `busy`), each waiting until its deadline at most (504
5
+ // `timeout`); a worker given until its deadline too, then terminated (504
6
+ // `timeout`). One that can't start is refused (503 `unavailable`), and one
7
+ // gone without an answer `accept` takes fails (422 `failed`), each as `error`
8
+ // tells it; `what` names them in the log. A worker that told, before its
9
+ // answer, one to settle for (`early`) fails in neither way: gone without its
10
+ // own, its deadline come or its memory run out, it answers that.
11
+ import { Worker, type WorkerOptions } from 'node:worker_threads'
12
+
13
+ export function workerTurns({ what, active, waiting, error: Failure, busy, timeout, failed }: {
14
+ what: string; active: number; waiting: number; error: new (status: number, code: string) => Error; busy: string; timeout: string; failed: string
15
+ }) {
16
+ let running = 0
17
+ const queued: Array<() => void> = []
18
+ // A worker's turn, waited for behind those running until `deadline`; given
19
+ // up, it goes to the next one waiting.
20
+ async function turn(deadline: number): Promise<void> {
21
+ if (running < active) { running++; return }
22
+ if (queued.length >= waiting) throw new Failure(429, busy)
23
+ await new Promise<void>((resolve, reject) => {
24
+ const next = () => { clearTimeout(timer); resolve() }
25
+ const timer = setTimeout(() => {
26
+ queued.splice(queued.indexOf(next), 1)
27
+ reject(new Failure(504, timeout))
28
+ }, deadline - Date.now())
29
+ queued.push(next)
30
+ })
31
+ }
32
+ function done() {
33
+ const next = queued.shift()
34
+ if (next) next()
35
+ else running--
36
+ }
37
+ return {
38
+ // `work` done in its turn, held till it settles.
39
+ async inTurn<T>(deadline: number, work: () => Promise<T>): Promise<T> {
40
+ await turn(deadline)
41
+ try { return await work() } finally { done() }
42
+ },
43
+ // The answer of a worker of `url`, as `accept` takes it, or null where
44
+ // it doesn't: settled once the worker is gone, so that its turn is given
45
+ // up only then. `early`, where given, is asked first of each thing the
46
+ // worker tells: the answer to settle for should it be gone before it
47
+ // tells its own, or null for what is its own, or anything else.
48
+ run<T>(url: URL, options: WorkerOptions, accept: (told: unknown) => T | null, deadline: number, early?: (told: unknown) => T | null): Promise<T> {
49
+ let worker: Worker
50
+ try { worker = new Worker(url, options) } catch (err) {
51
+ console.warn(`managed: a ${what} could not start:`, err)
52
+ throw new Failure(503, 'unavailable')
53
+ }
54
+ return new Promise((resolve, reject) => {
55
+ let answer: T | null = null, answered = false, failure = new Failure(422, failed)
56
+ const timer = setTimeout(() => { failure = new Failure(504, timeout); void worker.terminate() }, deadline - Date.now())
57
+ worker.on('message', (told: unknown) => {
58
+ // Nothing it tells past its answer, while it is being terminated, is taken.
59
+ if (answered) return
60
+ const settled = early?.(told) ?? null
61
+ if (settled !== null) { answer = settled; return }
62
+ answered = true
63
+ answer = accept(told) ?? answer
64
+ void worker.terminate()
65
+ })
66
+ worker.once('error', err => { console.warn(`managed: a ${what} failed:`, err) })
67
+ // Gone: answered, run out of memory, or terminated.
68
+ worker.once('exit', () => {
69
+ clearTimeout(timer)
70
+ if (answer === null) reject(failure)
71
+ else resolve(answer)
72
+ })
73
+ })
74
+ },
75
+ }
76
+ }