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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (442) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +16 -78
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +6 -0
  13. package/common/bundle-compare-diff.js +377 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-imports.js +20 -0
  20. package/common/bundle-metadata.d.ts +15 -0
  21. package/common/bundle-metadata.js +226 -0
  22. package/common/bundle-pkg-of.d.ts +1 -0
  23. package/common/bundle-pkg-of.js +90 -0
  24. package/common/bundle-reasons.d.ts +6 -0
  25. package/common/bundle-reasons.js +58 -0
  26. package/common/bundle-source-links.d.ts +6 -0
  27. package/common/bundle-source-links.js +216 -0
  28. package/common/bundle-sourcemap.d.ts +10 -0
  29. package/common/bundle-sourcemap.js +100 -0
  30. package/common/bundle-sources.d.ts +10 -0
  31. package/common/bundle-sources.js +374 -0
  32. package/common/bundle-stats.js +41 -0
  33. package/common/bundle-tabs.js +1 -0
  34. package/common/code-language.js +66 -0
  35. package/common/default-scan-models.ts +36 -0
  36. package/common/dependency-reviews.d.ts +18 -0
  37. package/common/dependency-reviews.js +64 -0
  38. package/common/finding-duplicates.js +63 -0
  39. package/common/finding-filters.js +313 -0
  40. package/common/finding-id.js +47 -0
  41. package/common/finding-repo.d.ts +5 -0
  42. package/common/finding-repo.js +67 -0
  43. package/common/github-issue-labels.d.ts +1 -0
  44. package/common/github-issue-labels.js +11 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +14 -0
  48. package/common/line-diff.js +181 -0
  49. package/common/linked-workspace-groups.js +63 -0
  50. package/common/managed/agent-tasks.ts +292 -0
  51. package/common/managed/comments.ts +43 -0
  52. package/common/managed/dependency-routes.js +25 -0
  53. package/common/managed/directory-packages.ts +28 -0
  54. package/common/managed/finding-detail.d.ts +5 -0
  55. package/common/managed/finding-detail.js +75 -0
  56. package/common/managed/finding-values.d.ts +2 -0
  57. package/common/managed/finding-values.js +138 -0
  58. package/common/managed/github-agents.ts +114 -0
  59. package/common/managed/github-logins.ts +49 -0
  60. package/common/managed/lite-name.d.ts +2 -0
  61. package/common/managed/lite-name.js +20 -0
  62. package/common/managed/npm-packages.d.ts +9 -0
  63. package/common/managed/npm-packages.js +63 -0
  64. package/common/managed/permissions.ts +31 -0
  65. package/common/managed/report-content.ts +72 -0
  66. package/common/managed/report-filter.ts +120 -0
  67. package/common/managed/repository-alias.ts +65 -0
  68. package/common/managed/review-view-routes.js +23 -0
  69. package/common/managed/risk-routes.js +30 -0
  70. package/common/managed/roles.ts +41 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +385 -0
  73. package/common/managed/scan-models.ts +6 -0
  74. package/common/managed/stasis-config.ts +7 -0
  75. package/common/managed/team-app.d.ts +19 -0
  76. package/common/managed/team-app.js +129 -0
  77. package/common/managed/team-filters.js +26 -0
  78. package/common/managed/triage.ts +83 -0
  79. package/common/managed/upload-seal.ts +126 -0
  80. package/common/pretty-json.js +98 -0
  81. package/common/pretty-kinds.js +20 -0
  82. package/common/pretty-print.d.ts +6 -0
  83. package/common/pretty-print.js +36 -0
  84. package/common/pretty-sourcemap.js +70 -0
  85. package/common/repo-commit.d.ts +4 -0
  86. package/common/repo-commit.js +30 -0
  87. package/common/revalidation-conflicts.js +48 -0
  88. package/common/revalidation-input-groups.js +56 -0
  89. package/common/save-error-reason.ts +20 -7
  90. package/common/scan-server.ts +13 -0
  91. package/common/security-links.d.ts +5 -0
  92. package/common/security-links.js +33 -0
  93. package/common/server-info.ts +46 -0
  94. package/common/sourcemap-listing.js +78 -0
  95. package/common/sourcemap-mappings.js +136 -0
  96. package/common/sourcemap-unlist.js +85 -0
  97. package/common/stasis-files.d.ts +5 -0
  98. package/common/stasis-files.js +20 -0
  99. package/common/stasis-tgz.d.ts +6 -0
  100. package/common/stasis-tgz.js +27 -0
  101. package/common/utf8.d.ts +3 -0
  102. package/common/utf8.js +45 -0
  103. package/common/whitespace-insensitive.js +19 -0
  104. package/common/workspace-app.js +91 -0
  105. package/common/workspace-groups.js +176 -0
  106. package/out/activity.js +2 -0
  107. package/out/brotli-fallback.js +3 -3
  108. package/out/chunk-2XUEZHIP.js +28 -0
  109. package/out/chunk-55YIWY3H.js +5 -0
  110. package/out/chunk-563V5VVT.js +266 -0
  111. package/out/chunk-5AVGKFMR.js +1 -0
  112. package/out/chunk-5EAVJAD2.js +3 -0
  113. package/out/chunk-5M2X3QPK.js +6 -0
  114. package/out/chunk-5QWPKTCE.js +40 -0
  115. package/out/chunk-5UJHJWFU.js +4 -0
  116. package/out/chunk-6CCSTJWB.js +1 -0
  117. package/out/chunk-6VOB5WXX.js +2 -0
  118. package/out/chunk-6WMQVUT2.js +3 -0
  119. package/out/chunk-6Y6PZ2BU.js +9 -0
  120. package/out/chunk-74JZTGTO.js +11 -0
  121. package/out/chunk-7BKKYVWR.js +7 -0
  122. package/out/chunk-7C7DWL7I.js +1 -0
  123. package/out/chunk-7HP2VYIC.js +2 -0
  124. package/out/chunk-7YFJUT2P.js +1 -0
  125. package/out/chunk-7YO4QV5P.js +1 -0
  126. package/out/chunk-A4BBBHQU.js +1 -0
  127. package/out/chunk-B64CTMVU.js +4 -0
  128. package/out/chunk-BEKYZCPX.js +14 -0
  129. package/out/chunk-C4Z6ZBXV.js +10 -0
  130. package/out/chunk-CU3FPB3P.js +1 -0
  131. package/out/chunk-DEVAORP2.js +1 -0
  132. package/out/chunk-DOYTKRIR.js +53 -0
  133. package/out/chunk-DUASGS2O.js +8 -0
  134. package/out/chunk-EEJA7JBI.js +13 -0
  135. package/out/chunk-FSU2PLJL.js +1 -0
  136. package/out/chunk-GO7FT4OD.js +1 -0
  137. package/out/chunk-GX5UXWT4.js +1 -0
  138. package/out/chunk-H4FEC57K.js +1 -0
  139. package/out/chunk-ITUKKCCK.js +10 -0
  140. package/out/chunk-IYPY47MC.js +1 -0
  141. package/out/chunk-K4XJHM2T.js +1 -0
  142. package/out/chunk-LBD3M3J6.js +1 -0
  143. package/out/chunk-LVSLM7HB.js +1 -0
  144. package/out/chunk-LVW7WWV4.js +1 -0
  145. package/out/chunk-N57OWFKY.js +15 -0
  146. package/out/chunk-NRPC74AM.js +1 -0
  147. package/out/chunk-OAWQNDAO.js +3 -0
  148. package/out/chunk-OOJM4CTU.js +1 -0
  149. package/out/chunk-PEE47ANR.js +1 -0
  150. package/out/chunk-PKLVXUEI.js +11 -0
  151. package/out/chunk-PLGH63UC.js +2 -0
  152. package/out/chunk-PNHBZGDD.js +1 -0
  153. package/out/chunk-PTFYDJUP.js +1 -0
  154. package/out/chunk-PWFUOLZK.js +17 -0
  155. package/out/chunk-PXK7EU4V.js +1 -0
  156. package/out/chunk-QD3IBSF4.js +7 -0
  157. package/out/chunk-QI66YA4F.js +1 -0
  158. package/out/chunk-QRKFPLA4.js +80 -0
  159. package/out/chunk-R3NZFXVR.js +1 -0
  160. package/out/chunk-R5O6FAW4.js +2 -0
  161. package/out/chunk-RPNO56H2.js +1 -0
  162. package/out/chunk-SSPDMA6D.js +1 -0
  163. package/out/chunk-SZWPYLPC.js +1 -0
  164. package/out/chunk-TUII34K2.js +1 -0
  165. package/out/chunk-UJP4PQJA.js +1 -0
  166. package/out/chunk-UJSJMXEG.js +1 -0
  167. package/out/chunk-UR4WYMIP.js +1 -0
  168. package/out/chunk-VHEXSGGP.js +1 -0
  169. package/out/chunk-VYYUMYVW.js +9 -0
  170. package/out/chunk-WCDYSIKG.js +1 -0
  171. package/out/chunk-WFBVS4QI.js +1 -0
  172. package/out/chunk-XM4RLC4A.js +2 -0
  173. package/out/chunk-ZQHLECTI.js +1 -0
  174. package/out/client-managed-import.js +4 -0
  175. package/out/client-managed.js +37 -0
  176. package/out/client-sync.js +11 -17
  177. package/out/compare.js +26 -0
  178. package/out/dialogs.js +40 -0
  179. package/out/github-issue-authorized.html +3 -0
  180. package/out/github-issue-authorized.js +1 -0
  181. package/out/graph.js +19 -4
  182. package/out/index.html +104 -24
  183. package/out/prism.js +14 -10
  184. package/out/scan.js +2 -0
  185. package/out/stasis.svg +20 -0
  186. package/out/terminal.js +367 -39
  187. package/out/view.css +1 -1
  188. package/out/view.js +19 -147
  189. package/package.json +409 -64
  190. package/risk/actions/findings.js +161 -0
  191. package/risk/actions/resolve.js +287 -0
  192. package/risk/actions/scripts/commands.js +182 -0
  193. package/risk/actions/scripts/grade.js +113 -0
  194. package/risk/actions/scripts/packages.js +123 -0
  195. package/risk/actions/scripts/shell.js +169 -0
  196. package/risk/actions/uses.js +94 -0
  197. package/risk/actions/workflow.js +183 -0
  198. package/risk/files/characters.js +354 -0
  199. package/risk/files/hosts.js +206 -0
  200. package/risk/files/readability.js +185 -0
  201. package/risk/files/runs-code.js +568 -0
  202. package/risk/files/script.js +410 -0
  203. package/risk/files/source-map-link.js +43 -0
  204. package/risk/files/stamps.js +47 -0
  205. package/risk/index.d.ts +294 -0
  206. package/risk/index.js +12 -0
  207. package/risk/npm/assess.js +285 -0
  208. package/risk/npm/combined.js +68 -0
  209. package/risk/npm/compare.js +236 -0
  210. package/risk/npm/dependencies.js +172 -0
  211. package/risk/npm/diff.js +79 -0
  212. package/risk/npm/downloads.js +84 -0
  213. package/risk/npm/files.js +445 -0
  214. package/risk/npm/held.js +67 -0
  215. package/risk/npm/install-scripts.js +34 -0
  216. package/risk/npm/malware.js +38 -0
  217. package/risk/npm/manifest.js +65 -0
  218. package/risk/npm/new-dependency.js +60 -0
  219. package/risk/npm/old-version.js +108 -0
  220. package/risk/npm/registry.js +393 -0
  221. package/risk/npm/release.js +85 -0
  222. package/risk/npm/score.js +59 -0
  223. package/risk/npm/specs.js +124 -0
  224. package/risk/npm/tarball.js +169 -0
  225. package/server-common/database-config.ts +16 -0
  226. package/server-common/initialize.ts +18 -0
  227. package/server-common/npm-advisories.ts +101 -0
  228. package/{server → server-common}/origin.ts +5 -5
  229. package/server-common/reap.ts +48 -0
  230. package/server-common/scan-config.ts +19 -0
  231. package/server-common/standalone.ts +29 -0
  232. package/server-common/storage-crypto.ts +182 -0
  233. package/server-common/storage-log.ts +38 -0
  234. package/server-common/vercel-blob.ts +103 -0
  235. package/server-e2e/app.ts +487 -0
  236. package/{server → server-e2e}/bus-receiver.ts +2 -1
  237. package/{server → server-e2e}/cli.js +9 -4
  238. package/{server → server-e2e}/config.ts +50 -42
  239. package/{server → server-e2e}/db-neon.ts +2 -2
  240. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  241. package/{server → server-e2e}/db-stmt.ts +2 -2
  242. package/{server → server-e2e}/db.ts +7 -7
  243. package/{server → server-e2e}/http.ts +44 -13
  244. package/{server → server-e2e}/hub.ts +40 -9
  245. package/server-e2e/index.ts +17 -0
  246. package/server-e2e/lifecycle.ts +95 -0
  247. package/{server → server-e2e}/neon-driver.ts +2 -2
  248. package/{server → server-e2e}/npm-proxy.ts +12 -145
  249. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  250. package/{server → server-e2e}/objstore/blob.ts +1 -1
  251. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  252. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  253. package/{server → server-e2e}/objstore/init.ts +19 -27
  254. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  255. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  257. package/{server → server-e2e}/objstore/rest.ts +3 -3
  258. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  259. package/{server → server-e2e}/objstore/store.ts +7 -7
  260. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  261. package/{server → server-e2e}/pubsub.ts +12 -9
  262. package/{server → server-e2e}/sign.ts +4 -4
  263. package/{server → server-e2e}/sse-server.ts +60 -33
  264. package/{server → server-e2e}/static.ts +18 -17
  265. package/{server → server-e2e}/sync-handlers.ts +64 -30
  266. package/{server → server-e2e}/ws-server.ts +20 -9
  267. package/server-managed/activity.ts +269 -0
  268. package/server-managed/agent-merges.ts +109 -0
  269. package/server-managed/app-agents.ts +23 -0
  270. package/server-managed/avatar-store.ts +13 -0
  271. package/server-managed/blob-store.ts +26 -0
  272. package/server-managed/brotli.ts +10 -0
  273. package/server-managed/bundle-advisories.ts +79 -0
  274. package/server-managed/bundle-advisory-inventory.ts +85 -0
  275. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  276. package/server-managed/bundle-build-diagnostics.js +23 -0
  277. package/server-managed/bundle-build-leases.ts +41 -0
  278. package/server-managed/bundle-build-worker.js +380 -0
  279. package/server-managed/bundle-build.ts +326 -0
  280. package/server-managed/bundle-cache.ts +261 -0
  281. package/server-managed/bundle-catalog.ts +29 -0
  282. package/server-managed/bundle-commits.ts +133 -0
  283. package/server-managed/bundle-dependency-reviews.ts +91 -0
  284. package/server-managed/bundle-store.ts +24 -0
  285. package/server-managed/bundle-summary-cache.ts +139 -0
  286. package/server-managed/bundle-validation.ts +33 -0
  287. package/server-managed/bundle.ts +151 -0
  288. package/server-managed/cache-storage.ts +20 -0
  289. package/server-managed/cli.js +21 -0
  290. package/server-managed/combined.ts +43 -0
  291. package/server-managed/comments.ts +138 -0
  292. package/server-managed/commit-coauthors.ts +105 -0
  293. package/server-managed/commit-lockfiles.ts +78 -0
  294. package/server-managed/comparison.ts +51 -0
  295. package/server-managed/config.ts +163 -0
  296. package/server-managed/content-access.ts +15 -0
  297. package/server-managed/crypto.ts +25 -0
  298. package/server-managed/db-methods.ts +1915 -0
  299. package/server-managed/db-neon.ts +398 -0
  300. package/server-managed/db-schema.ts +263 -0
  301. package/server-managed/db-table-names.ts +22 -0
  302. package/server-managed/db.ts +149 -0
  303. package/server-managed/dependabot-access.ts +61 -0
  304. package/server-managed/dependabot-alerts.ts +180 -0
  305. package/server-managed/dependency-review-comments.ts +158 -0
  306. package/server-managed/dependency-reviews.ts +369 -0
  307. package/server-managed/github-accounts.ts +59 -0
  308. package/server-managed/github-actions.ts +71 -0
  309. package/server-managed/github-app.ts +347 -0
  310. package/server-managed/github-errors.ts +92 -0
  311. package/server-managed/github-graphql.ts +42 -0
  312. package/server-managed/github-issue-links.ts +264 -0
  313. package/server-managed/github-issue-oauth.ts +30 -0
  314. package/server-managed/github-issues.ts +157 -0
  315. package/server-managed/github-link-oauth.ts +56 -0
  316. package/server-managed/github-links.ts +204 -0
  317. package/server-managed/github-metadata.ts +213 -0
  318. package/server-managed/github-oauth.ts +264 -0
  319. package/server-managed/github-pulls.ts +257 -0
  320. package/server-managed/github-requests.ts +181 -0
  321. package/server-managed/github-users.ts +30 -0
  322. package/server-managed/github-values.ts +26 -0
  323. package/server-managed/history-windows.ts +172 -0
  324. package/server-managed/http-response.ts +76 -0
  325. package/server-managed/http.ts +6327 -0
  326. package/server-managed/import-triage.ts +51 -0
  327. package/server-managed/index.ts +204 -0
  328. package/server-managed/kept-briefly.ts +37 -0
  329. package/server-managed/kept.ts +28 -0
  330. package/server-managed/link-reports.ts +149 -0
  331. package/server-managed/listed-activity.ts +39 -0
  332. package/server-managed/locked-packages.ts +234 -0
  333. package/server-managed/lockfile-scope.ts +58 -0
  334. package/server-managed/lru.ts +30 -0
  335. package/server-managed/managed-issues.ts +92 -0
  336. package/server-managed/management-catalog.ts +45 -0
  337. package/server-managed/management.ts +116 -0
  338. package/server-managed/npm-delta-worker.js +142 -0
  339. package/server-managed/npm-delta.ts +277 -0
  340. package/server-managed/npm-insights.ts +455 -0
  341. package/server-managed/npm-kept.ts +265 -0
  342. package/server-managed/npm-loads.ts +259 -0
  343. package/server-managed/npm-manifest.ts +117 -0
  344. package/server-managed/npm-packages.ts +469 -0
  345. package/server-managed/npm-patch-paths.ts +86 -0
  346. package/server-managed/npm-patch.ts +455 -0
  347. package/server-managed/npm-provenance.ts +127 -0
  348. package/server-managed/npm-risk.ts +287 -0
  349. package/server-managed/object-storage-disk.ts +147 -0
  350. package/server-managed/object-storage-vercel.ts +71 -0
  351. package/server-managed/object-storage.ts +82 -0
  352. package/server-managed/package-entry-points.ts +127 -0
  353. package/server-managed/pretty-copies.ts +22 -0
  354. package/server-managed/pretty-format.d.ts +3 -0
  355. package/server-managed/pretty-format.js +13 -0
  356. package/server-managed/pretty-print.ts +442 -0
  357. package/server-managed/public-workspace.ts +243 -0
  358. package/server-managed/pull-comment-reviews.ts +161 -0
  359. package/server-managed/pull-dependencies.ts +370 -0
  360. package/server-managed/pull-dependency-reviews.ts +407 -0
  361. package/server-managed/pull-reviews.ts +202 -0
  362. package/server-managed/queue.ts +54 -0
  363. package/server-managed/release-commits.ts +85 -0
  364. package/server-managed/rename-diff-worker.js +30 -0
  365. package/server-managed/rename-diff.ts +237 -0
  366. package/server-managed/repo-path.ts +21 -0
  367. package/server-managed/report-migration.ts +32 -0
  368. package/server-managed/report-opening.ts +77 -0
  369. package/server-managed/report-query.ts +10 -0
  370. package/server-managed/report-response.ts +16 -0
  371. package/server-managed/report-sources.ts +185 -0
  372. package/server-managed/report-store.ts +77 -0
  373. package/server-managed/repository-actions.ts +220 -0
  374. package/server-managed/repository-agents.ts +422 -0
  375. package/server-managed/repository-aliases.ts +119 -0
  376. package/server-managed/repository-browser.ts +361 -0
  377. package/server-managed/repository-changes.ts +280 -0
  378. package/server-managed/repository-code.ts +222 -0
  379. package/server-managed/repository-dependency-reviews.ts +182 -0
  380. package/server-managed/repository-discovery.ts +83 -0
  381. package/server-managed/repository-history.ts +428 -0
  382. package/server-managed/repository-issues.ts +293 -0
  383. package/server-managed/repository-policy.ts +27 -0
  384. package/server-managed/repository-pulls.ts +207 -0
  385. package/server-managed/repository-pulse.ts +477 -0
  386. package/server-managed/repository-risk-assess.ts +108 -0
  387. package/server-managed/repository-risk-audit.ts +78 -0
  388. package/server-managed/repository-risk-caches.ts +37 -0
  389. package/server-managed/repository-risk-read.ts +260 -0
  390. package/server-managed/repository-risk-stasis.ts +61 -0
  391. package/server-managed/repository-risk-turn.ts +97 -0
  392. package/server-managed/repository-risk.ts +516 -0
  393. package/server-managed/repository-squashes.ts +160 -0
  394. package/server-managed/repository-stamp.ts +41 -0
  395. package/server-managed/request-timing.ts +63 -0
  396. package/server-managed/reviewed-dependencies.ts +170 -0
  397. package/server-managed/revisions.ts +35 -0
  398. package/server-managed/scan-downloads.ts +121 -0
  399. package/server-managed/session.ts +132 -0
  400. package/server-managed/slugs.ts +38 -0
  401. package/server-managed/solidity-entry-points.ts +71 -0
  402. package/server-managed/sql-postgres.ts +34 -0
  403. package/server-managed/sql.ts +107 -0
  404. package/server-managed/stasis-config.ts +147 -0
  405. package/server-managed/stasis-dependencies.ts +221 -0
  406. package/server-managed/static.ts +28 -0
  407. package/server-managed/storage-command.ts +16 -0
  408. package/server-managed/storage-db.ts +183 -0
  409. package/server-managed/storage-encryption.ts +288 -0
  410. package/server-managed/storage-maintenance.ts +259 -0
  411. package/server-managed/storage-payload.ts +121 -0
  412. package/server-managed/storage-stores.ts +91 -0
  413. package/server-managed/storage.ts +82 -0
  414. package/server-managed/team-app-summaries.ts +56 -0
  415. package/server-managed/team-app.ts +156 -0
  416. package/server-managed/team-catalog.ts +7 -0
  417. package/server-managed/team-feed.ts +180 -0
  418. package/server-managed/team-npm-scopes.ts +103 -0
  419. package/server-managed/team-reports.ts +368 -0
  420. package/server-managed/triage-response.ts +16 -0
  421. package/server-managed/type-only-proof.js +161 -0
  422. package/server-managed/type-only-worker.js +31 -0
  423. package/server-managed/type-only.ts +135 -0
  424. package/server-managed/uploads.ts +106 -0
  425. package/server-managed/upstream-cache.ts +256 -0
  426. package/server-managed/view-as.ts +58 -0
  427. package/server-managed/worker-turns.ts +76 -0
  428. package/server-managed/workspace-shares.ts +170 -0
  429. package/server.ts +70 -0
  430. package/strip-types-loader.js +13 -10
  431. package/server/index.ts +0 -480
  432. package/server/lifecycle.ts +0 -208
  433. /package/{LICENSE → LICENSE-MIT} +0 -0
  434. /package/{server → server-e2e}/auth.ts +0 -0
  435. /package/{server → server-e2e}/config.example.json +0 -0
  436. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  437. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  438. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  439. /package/{server → server-e2e}/peer.ts +0 -0
  440. /package/{server → server-e2e}/sse-session.ts +0 -0
  441. /package/{server → server-e2e}/util.ts +0 -0
  442. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,256 @@
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`: where the server has an upstream disk cache (off Vercel,
93
+ // set at startup), that keeps everything; else this store keeps listings and
94
+ // public names, those of `keys` (auditedKeys) read at once.
95
+ export function auditCache(cacheDir: string | null | undefined, db: UpstreamCacheStore, signal: AbortSignal, debug = false, keys: Iterable<string> = []): CacheStore | undefined {
96
+ return cacheDir ? undefined : upstreamCache(db, signal, debug, keys)
97
+ }
98
+
99
+ // Only listings and public names are kept: upstream's other records (npm
100
+ // version documents, registries' repository lookups) read as misses and are
101
+ // not written.
102
+ const LISTINGS = 'github/advisories'
103
+ const PUBLIC_NAMES = 'npm/public'
104
+ const PUBLIC_REPOS = 'github/public'
105
+ const CACHED_TYPES = new Set([LISTINGS, PUBLIC_NAMES, PUBLIC_REPOS])
106
+
107
+ // What an audit of `packages` reads first, where it is already known: the
108
+ // listings of the repositories it knows, each `github` package, each `soldeer`
109
+ // package's given repository, and with `repoAdvisories`, every other
110
+ // package's, upstream looking up the rest itself; and whether each npm package,
111
+ // and each `github` package's repository but one said `internal`, is public, as
112
+ // upstream asks before it asks OSV of it. Each as upstream asks for it, a
113
+ // listing and a repository by its lowercased name.
114
+ export function auditedKeys(packages: Iterable<Package>, repoAdvisories: boolean): string[] {
115
+ return [...new Set([...packages].flatMap(pkg => {
116
+ const repo = pkg.ecosystem === 'github' ? pkg.name : pkg.ecosystem === 'soldeer' || repoAdvisories ? pkg.github : undefined
117
+ const asked = pkg.ecosystem === 'npm' ? [`${PUBLIC_NAMES}/${pkg.name}`]
118
+ : pkg.ecosystem === 'github' && pkg.internal !== true ? [`${PUBLIC_REPOS}/${pkg.name.toLowerCase()}`] : []
119
+ return [...asked, ...repo === undefined ? [] : [`${LISTINGS}/${repo.toLowerCase()}`]]
120
+ }))]
121
+ }
122
+
123
+ // The cache is an optimization: a database failure is a miss, never a failed
124
+ // audit. Upstream keeps listing after an abandoned audit; once `signal` aborts,
125
+ // the request's database work is over and the store is left alone.
126
+ // Upstream reads one listing at a time per repository, and whether a name is
127
+ // public eight at a time, and a request's queries share one connection (Neon),
128
+ // so a recheck of hundreds of packages would wait on as many round trips: the
129
+ // first read asks for every one of `keys` at once. Any other key, or all of
130
+ // them if that read fails, is read alone.
131
+ export function upstreamCache(db: UpstreamCacheStore, signal: AbortSignal, debug = false, keys: Iterable<string> = []): CacheStore {
132
+ const batched = new Set(keys)
133
+ let batch: Promise<Map<string, string> | null> | undefined
134
+ const readBatch = () => batch ??= db.getUpstreamCacheEntries([...batched]).catch((error: unknown) => {
135
+ if (debug) console.warn('managed: upstream cache read failed:', error)
136
+ return null
137
+ })
138
+ return {
139
+ async read(type, key) {
140
+ if (!CACHED_TYPES.has(type) || signal.aborted) return null
141
+ const cacheKey = `${type}/${key}`
142
+ try {
143
+ const found = batched.has(cacheKey) ? await readBatch() : null
144
+ const value = found ? found.get(cacheKey) ?? null : await db.getUpstreamCacheEntry(cacheKey)
145
+ return value === null ? null : JSON.parse(value) as unknown
146
+ } catch (error) {
147
+ if (debug) console.warn('managed: upstream cache read failed:', error)
148
+ return null
149
+ }
150
+ },
151
+ async write(type, key, value) {
152
+ if (!CACHED_TYPES.has(type) || signal.aborted) return
153
+ try { await db.setUpstreamCacheEntry(`${type}/${key}`, JSON.stringify(value), Date.now()) } catch (error) {
154
+ if (debug) console.warn('managed: upstream cache write failed:', error)
155
+ }
156
+ },
157
+ }
158
+ }
159
+
160
+ // The file upstream keeps `file` in, under `dir` of its disk cache
161
+ // (setCacheDir), as its cachePath names it: `@babel+core@7.29.7.tgz`, a
162
+ // capital written `!` and the letter, and a Windows device name's first
163
+ // letter escaped.
164
+ export function upstreamCachePath(root: string, dir: string, file: string): string {
165
+ const name = encodeURIComponent(file.replaceAll(/[!A-Z]/gu, char => `!${char.toLowerCase()}`))
166
+ .replaceAll('%40', '@').replaceAll('%2F', '+')
167
+ .replace(/^(?=(?:con|prn|aux|nul|com\d|lpt\d)(?:\.|$))./u, char => `%${char.codePointAt(0)!.toString(16).toUpperCase()}`)
168
+ return join(root, dir, name)
169
+ }
170
+
171
+ // A kept file, where it is a regular file of at most `max` bytes, checked on
172
+ // the file as opened (a FIFO or device would block or never end), and read
173
+ // to the size it had then.
174
+ export async function readKeptFile(path: string, max: number): Promise<Uint8Array | null> {
175
+ const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK).catch(() => null)
176
+ if (!handle) return null
177
+ try {
178
+ const stats = await handle.stat()
179
+ if (!stats.isFile() || stats.size > max) return null
180
+ const bytes = Buffer.allocUnsafe(stats.size)
181
+ for (let at = 0; at < bytes.length;) {
182
+ const { bytesRead } = await handle.read(bytes, at, bytes.length - at, at)
183
+ if (bytesRead === 0) return null
184
+ at += bytesRead
185
+ }
186
+ return bytes
187
+ } catch { return null }
188
+ finally { await handle.close() }
189
+ }
190
+
191
+ // `bytes` kept at `path`, written whole beside it first and then moved in, so a
192
+ // reader finds the old file or the new one, never part of one; a failure
193
+ // keeps nothing.
194
+ let tmpSeq = 0
195
+ export async function keepFile(path: string, bytes: Uint8Array) {
196
+ const tmp = `${path}.${process.pid}.${++tmpSeq}.tmp`
197
+ try {
198
+ await mkdir(dirname(path), { recursive: true })
199
+ await writeFile(tmp, bytes)
200
+ await rename(tmp, path)
201
+ } catch { await rm(tmp, { force: true }).catch(() => {}) }
202
+ }
203
+
204
+ const gunzipAsync = promisify(gunzip)
205
+ const gzipAsync = promisify(gzip)
206
+
207
+ // An upstream's JSON object kept with its ETag, gzipped, as keepJson keeps it:
208
+ // `{ etag, json }`, or null where none is kept, or what is can't be read
209
+ // within `limit` bytes.
210
+ export async function readKeptJson(path: string, limit: number): Promise<{ etag: string; json: Record<string, unknown> } | null> {
211
+ const bytes = await readKeptFile(path, limit)
212
+ if (!bytes) return null
213
+ const object = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
214
+ try {
215
+ const kept: unknown = JSON.parse((await gunzipAsync(bytes, { maxOutputLength: limit + 1024 })).toString('utf8'))
216
+ return object(kept) && typeof kept['etag'] === 'string' && object(kept['json']) ? { etag: kept['etag'], json: kept['json'] } : null
217
+ } catch { return null }
218
+ }
219
+
220
+ // `body`, an upstream's JSON object as it wrote it, kept with its `etag`.
221
+ export async function keepJson(path: string, etag: string, body: Buffer) {
222
+ await keepFile(path, await gzipAsync(Buffer.concat([Buffer.from(`{"etag":${JSON.stringify(etag)},"json":`), body, Buffer.from('}')])))
223
+ }
224
+
225
+ // A kept listing is read to no more than this, gzipped or not: one runs to
226
+ // some hundreds of KiB.
227
+ const LISTING_BYTES = 64 * 1024 * 1024
228
+
229
+ // A repository's listing as last kept where audits keep them (auditCache),
230
+ // however old, for when GitHub can't be reached to refresh it: `at`, when it
231
+ // was kept, and `cache`, a store answering it to upstream as kept just now,
232
+ // so that upstream takes it rather than ask GitHub, and keeping nothing.
233
+ // Upstream checks it as it checks its own. Null where none is kept, or it
234
+ // can't be read.
235
+ export async function lastListing(cacheDir: string | null | undefined, db: UpstreamCacheStore, repo: string, debug = false): Promise<{ at: number; cache: CacheStore } | null> {
236
+ const key = repo.toLowerCase()
237
+ let kept: { at?: unknown } | null
238
+ try {
239
+ if (cacheDir) {
240
+ const bytes = await readKeptFile(upstreamCachePath(cacheDir, LISTINGS, `${key}.json.gz`), LISTING_BYTES)
241
+ kept = bytes && JSON.parse((await gunzipAsync(bytes, { maxOutputLength: LISTING_BYTES })).toString('utf8'))
242
+ } else {
243
+ const value = await db.getUpstreamCacheEntry(`${LISTINGS}/${key}`)
244
+ kept = value === null ? null : JSON.parse(value)
245
+ }
246
+ } catch (error) {
247
+ if (debug) console.warn('managed: kept listing read failed:', error)
248
+ return null
249
+ }
250
+ const at = kept?.at
251
+ if (typeof at !== 'number') return null
252
+ return { at, cache: {
253
+ read: (type, name) => Promise.resolve(type === LISTINGS && name === key ? { ...kept, at: Date.now() } : null),
254
+ write: () => Promise.resolve(),
255
+ } }
256
+ }
@@ -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
+ }
@@ -0,0 +1,170 @@
1
+ import { linkRevision } from './link-reports.ts'
2
+ import type { ManagedSql } from './sql.ts'
3
+ import type { BundleBuildConditions, ManagedBundle, TeamReportAccessSnapshot, UserTeam } from './db.ts'
4
+ import { type TeamUserPermissions, parseTeamUserPermissions } from '../common/managed/permissions.ts'
5
+
6
+ export const WORKSPACE_SHARE_SCHEMA = `
7
+ CREATE TABLE IF NOT EXISTS managed_workspace_share (
8
+ token_hash TEXT PRIMARY KEY,
9
+ team_id TEXT NOT NULL REFERENCES managed_team(id) ON DELETE CASCADE,
10
+ created_by TEXT NOT NULL REFERENCES managed_user(id) ON DELETE CASCADE,
11
+ created_at INTEGER NOT NULL,
12
+ dependencies INTEGER NOT NULL DEFAULT 0,
13
+ security INTEGER NOT NULL DEFAULT 0
14
+ ) STRICT;
15
+ CREATE INDEX IF NOT EXISTS managed_workspace_share_team_idx ON managed_workspace_share(team_id);
16
+ `
17
+
18
+ export interface WorkspaceShareSnapshot extends TeamReportAccessSnapshot {
19
+ team: UserTeam
20
+ permissions: TeamUserPermissions
21
+ repositories: { repoId: number; github: string; path: string }[]
22
+ bundles: ManagedBundle[]
23
+ }
24
+ export interface WorkspaceShareInfo {
25
+ id: string
26
+ createdAt: number
27
+ createdBy: string
28
+ permissions: TeamUserPermissions
29
+ }
30
+ export interface ManagedWorkspaceShare extends WorkspaceShareInfo {
31
+ teamId: string
32
+ teamName: string
33
+ teamSlug: string
34
+ }
35
+ export type WorkspaceShareFeedState = { grant: string; catalog: number; annotations: number }
36
+ export interface WorkspaceShareStore {
37
+ createWorkspaceShare(sessionId: string, now: number, teamId: string, tokenHash: string, permissions?: TeamUserPermissions): Promise<boolean>
38
+ listWorkspaceShares(sessionId: string, now: number, teamId: string): Promise<WorkspaceShareInfo[] | null>
39
+ listManagedWorkspaceShares(sessionId: string, now: number): Promise<ManagedWorkspaceShare[] | null>
40
+ updateWorkspaceShare(sessionId: string, now: number, teamId: string, id: string, permissions: TeamUserPermissions): Promise<boolean>
41
+ revokeWorkspaceShares(sessionId: string, now: number, teamId: string, id?: string): Promise<boolean>
42
+ getWorkspaceShare(tokenHash: string): Promise<WorkspaceShareSnapshot | null>
43
+ getWorkspaceShareFeedState(tokenHash: string): Promise<WorkspaceShareFeedState | null>
44
+ }
45
+
46
+ // A share is a capability, never a user session. Its issuer must still manage
47
+ // this team on every read. No union of the issuer's other memberships applies.
48
+ function shareQueries(db: ManagedSql) {
49
+ const manager = db.prepare(`SELECT 1 FROM managed_session s
50
+ JOIN managed_user u ON u.id = s.user_id
51
+ JOIN managed_team t ON t.id = ? AND t.hidden = 0
52
+ WHERE s.id = ? AND s.expires_at > ? AND (u.role = 'admin' OR (u.role = 'manage'
53
+ AND EXISTS (SELECT 1 FROM managed_team_user tu WHERE tu.user_id = u.id AND tu.team_id = t.id)))`)
54
+ const insert = db.prepare(`INSERT INTO managed_workspace_share (token_hash, team_id, created_by, created_at, dependencies, security)
55
+ SELECT ?, ?, user_id, ?, ?, ? FROM managed_session WHERE id = ?`)
56
+ const remove = db.prepare('DELETE FROM managed_workspace_share WHERE team_id = ? AND (CAST(? AS TEXT) IS NULL OR token_hash = ?)')
57
+ const update = db.prepare('UPDATE managed_workspace_share SET dependencies = ?, security = ? WHERE team_id = ? AND token_hash = ?')
58
+ // The management ID is a hash, never a bearer token. Existing URLs remain
59
+ // unchanged when their permissions are edited; plaintext tokens aren't kept.
60
+ const list = db.prepare(`SELECT s.token_hash AS id, s.created_at AS createdAt, u.login AS createdBy, s.dependencies, s.security
61
+ FROM managed_workspace_share s JOIN managed_user u ON u.id = s.created_by WHERE s.team_id = ? ORDER BY s.created_at DESC, s.token_hash`)
62
+ const session = db.prepare(`SELECT u.id, u.role FROM managed_session s JOIN managed_user u ON u.id = s.user_id
63
+ WHERE s.id = ? AND s.expires_at > ? AND u.role IN ('manage', 'admin')`)
64
+ const all = db.prepare(`SELECT s.token_hash AS id, s.created_at AS createdAt, u.login AS createdBy, s.dependencies, s.security,
65
+ t.id AS teamId, t.slug AS teamSlug, t.name AS teamName FROM managed_workspace_share s
66
+ JOIN managed_user u ON u.id = s.created_by JOIN managed_team t ON t.id = s.team_id AND t.hidden = 0
67
+ WHERE ? = 'admin' OR EXISTS (SELECT 1 FROM managed_team_user tu WHERE tu.user_id = ? AND tu.team_id = s.team_id)
68
+ ORDER BY t.name, t.id, s.created_at DESC, s.token_hash`)
69
+ const shareGrant = `FROM managed_workspace_share s
70
+ JOIN managed_user u ON u.id = s.created_by
71
+ JOIN managed_team t ON t.id = s.team_id AND t.hidden = 0
72
+ WHERE s.token_hash = ? AND (u.role = 'admin' OR (u.role = 'manage'
73
+ AND EXISTS (SELECT 1 FROM managed_team_user tu WHERE tu.user_id = u.id AND tu.team_id = s.team_id)))`
74
+ const share = db.prepare(`SELECT t.id, t.slug, t.name, s.dependencies, s.security ${shareGrant}`)
75
+ // Validate the capability and its issuer every poll; global counters are
76
+ // internal hints that let unchanged feeds skip rebuilding the full catalog.
77
+ const feed = db.prepare(`SELECT t.id, s.dependencies, s.security,
78
+ (SELECT catalog FROM managed_change_revision WHERE id = 1) AS catalog,
79
+ (SELECT annotations FROM managed_change_revision WHERE id = 1) AS annotations ${shareGrant}`)
80
+ const repositories = db.prepare(`SELECT tr.repo_id AS repoId, sr.full_name AS github, tr.path
81
+ FROM managed_team_repo tr JOIN managed_selected_repo sr ON sr.repo_id = tr.repo_id
82
+ WHERE tr.team_id = ? ORDER BY tr.repo_id, tr.path`)
83
+ const reports = db.prepare(`SELECT DISTINCT r.id, r.slug, r.filename, r.analyzer, r.byte_size AS byteSize,
84
+ r.sha256, r.repo_directory AS directory, sr.full_name AS github, r.confirmed_default AS confirmedDefault
85
+ FROM managed_team_repo tr JOIN managed_report r ON r.repo_id = tr.repo_id
86
+ JOIN managed_selected_repo sr ON sr.repo_id = r.repo_id
87
+ WHERE tr.team_id = ? AND r.visible = 1 AND (tr.path = '' OR r.repo_directory = tr.path
88
+ OR substr(r.repo_directory, 1, length(tr.path) + 1) = tr.path || '/') ORDER BY r.id`)
89
+ // A raw bundle is visible only when its declared root is inside the team scope.
90
+ // Root bundles remain hidden from directory-only grants.
91
+ const bundles = db.prepare(`SELECT DISTINCT b.id, b.slug, b.integrity, b.filename, b.kind, b.byte_size AS byteSize,
92
+ b.uploaded_by AS uploadedBy, b.repo_id AS repoId, b.repo_directory AS repoDirectory, b.uploaded_at AS uploadedAt, b.provenance, b.build_conditions AS buildConditions, sr.full_name AS repoFullName
93
+ FROM managed_team_repo tr JOIN managed_bundle b ON b.repo_id = tr.repo_id
94
+ JOIN managed_selected_repo sr ON sr.repo_id = b.repo_id
95
+ WHERE tr.team_id = ? AND b.visible = 1 AND (tr.path = '' OR b.repo_directory = tr.path
96
+ OR substr(b.repo_directory, 1, length(tr.path) + 1) = tr.path || '/') ORDER BY b.id`)
97
+ return { manager, insert, remove, update, list, session, all, share, feed, repositories, reports, bundles }
98
+ }
99
+
100
+ function shareInfo<T extends { dependencies: number; security: number }>(row: T) {
101
+ const { dependencies, security, ...rest } = row
102
+ return { ...rest, permissions: { dependencies: dependencies === 1, security: security === 1 } }
103
+ }
104
+
105
+ export function workspaceShareMethods(db: ManagedSql): WorkspaceShareStore {
106
+ const q = shareQueries(db)
107
+ return {
108
+ async createWorkspaceShare(sessionId, now, teamId, tokenHash, permissions) {
109
+ if (!await q.manager.get(teamId, sessionId, now)) return false
110
+ const p = parseTeamUserPermissions(permissions)
111
+ await q.insert.run(tokenHash, teamId, now, +p.dependencies, +p.security, sessionId)
112
+ return true
113
+ },
114
+ async listWorkspaceShares(sessionId, now, teamId) {
115
+ if (!await q.manager.get(teamId, sessionId, now)) return null
116
+ const rows = await q.list.all(teamId) as { id: string; createdAt: number; createdBy: string; dependencies: number; security: number }[]
117
+ return rows.map(shareInfo)
118
+ },
119
+ async listManagedWorkspaceShares(sessionId, now) {
120
+ const viewer = await q.session.get(sessionId, now) as { id: string; role: string } | undefined
121
+ if (!viewer) return null
122
+ const rows = await q.all.all(viewer.role, viewer.id) as (Omit<ManagedWorkspaceShare, 'permissions'> & { dependencies: number; security: number })[]
123
+ return rows.map(shareInfo)
124
+ },
125
+ async updateWorkspaceShare(sessionId, now, teamId, id, permissions) {
126
+ if (!await q.manager.get(teamId, sessionId, now)) return false
127
+ const p = parseTeamUserPermissions(permissions)
128
+ return (await q.update.run(+p.dependencies, +p.security, teamId, id)).changes > 0
129
+ },
130
+ async revokeWorkspaceShares(sessionId, now, teamId, id) {
131
+ if (!await q.manager.get(teamId, sessionId, now)) return false
132
+ const result = await q.remove.run(teamId, id ?? null, id ?? null)
133
+ return id === undefined || result.changes > 0
134
+ },
135
+ async getWorkspaceShareFeedState(tokenHash) {
136
+ const row = await q.feed.get(tokenHash) as { id: string; dependencies: number; security: number; catalog: number; annotations: number } | undefined
137
+ return row ? { grant: JSON.stringify([row.id, row.dependencies, row.security]), catalog: row.catalog, annotations: row.annotations } : null
138
+ },
139
+ async getWorkspaceShare(tokenHash) {
140
+ const grant = await q.share.get(tokenHash) as { id: string; slug: string; name: string; dependencies: number; security: number } | undefined
141
+ if (!grant) return null
142
+ const { permissions, ...team } = shareInfo(grant)
143
+ const rows = await q.reports.all(team.id) as { id: string; slug: string; filename: string; analyzer: string | null; byteSize: number; sha256: string; directory: string; github: string; confirmedDefault: number }[]
144
+ const links = await linkRevision(db)
145
+ const bundleRows = (await q.bundles.all(team.id) as (Omit<ManagedBundle, 'buildConditions'> & { buildConditions: string | null; repoFullName: string })[])
146
+ .map(row => ({ ...row, buildConditions: row.buildConditions == null ? null : JSON.parse(row.buildConditions) as BundleBuildConditions }))
147
+ const repositories = await q.repositories.all(team.id) as WorkspaceShareSnapshot['repositories']
148
+ const keyOf = (row: typeof rows[number]) => JSON.stringify([row.sha256, row.github, row.directory, row.filename, permissions, links, ...row.confirmedDefault === 1 ? ['confirmed'] : []])
149
+ return {
150
+ user: { id: `share:${tokenHash}`, login: 'public', name: 'Public workspace', avatarUrl: null, role: 'view' },
151
+ teamId: team.id,
152
+ linkRevision: links,
153
+ permissions,
154
+ repositories,
155
+ reports: rows.map(row => ({ id: row.id, filename: row.filename, byteSize: row.byteSize, sha256: row.sha256,
156
+ repo: { github: row.github, directory: row.directory }, permissions, ...row.confirmedDefault === 1 ? { confirmedDefault: true as const } : {} })),
157
+ catalogKeys: Object.fromEntries(rows.map(row => [row.id, keyOf(row)])),
158
+ team: { ...team, permissions, cacheKey: links,
159
+ repos: repositories.map(repo => ({ repoId: repo.repoId, fullName: repo.github, path: repo.path || null }))
160
+ .toSorted((a, b) => a.fullName.localeCompare(b.fullName) || (a.path ?? '').localeCompare(b.path ?? '')),
161
+ reports: rows.map(row => ({ id: row.id, slug: row.slug, filename: row.filename, visible: true, analyzer: row.analyzer, repoFullName: row.github, repoDirectory: row.directory,
162
+ cacheKey: keyOf(row) })),
163
+ bundles: bundleRows.map(row => ({ id: row.id, slug: row.slug, integrity: row.integrity,
164
+ filename: row.filename, visible: true, kind: row.kind, byteSize: row.byteSize, repoId: row.repoId!, repoDirectory: row.repoDirectory, repoFullName: row.repoFullName, provenance: row.provenance })),
165
+ },
166
+ bundles: bundleRows.map(row => ({ ...row, visible: true })),
167
+ }
168
+ },
169
+ }
170
+ }
package/server.ts ADDED
@@ -0,0 +1,70 @@
1
+ import { parseArgs } from 'node:util'
2
+ import type { Server } from 'node:http'
3
+ import { startServer } from './server-common/standalone.ts'
4
+
5
+ // The reviewed dependencies a host keeps beyond the app, registered before
6
+ // init() (server-managed/reviewed-dependencies.ts): an async method telling
7
+ // whether a dependency, as a lockfile locks it, is reviewed there
8
+ // (`lookup`), and optionally one reading the reviews an open pull request's
9
+ // comments make (`parseComments`), and one formatting one's own dependency
10
+ // reviews as a comment to copy (`formatDependencyReviews`). They replace a
11
+ // repository's commit its dependencies are reviewed since.
12
+ export { registerReviewedDependencies } from './server-managed/reviewed-dependencies.ts'
13
+ export type { CommentReview, DependencyReviewEntry, FormatDependencyReviewsInput, ParseCommentsInput, ReviewComment, ReviewedBase, ReviewedDependencies, ReviewedDependency,
14
+ ReviewedLockfile, ReviewedVersion, ReviewVerdict } from './server-managed/reviewed-dependencies.ts'
15
+
16
+ const modes = ['e2e', 'managed', 'managed-e2e', 'e2e-managed'] as const
17
+ export type ServerMode = typeof modes[number]
18
+
19
+ function parseMode(mode: string): ServerMode {
20
+ for (const candidate of modes) if (mode === candidate) return candidate
21
+ throw new Error(`Unknown mode: ${mode}. Expected ${modes.join(', ')}.`)
22
+ }
23
+
24
+ export type InitOptions = {
25
+ mode?: ServerMode
26
+ // False serves only the API: `out/` is never read, nor its UI served, for
27
+ // hosts that serve the UI themselves.
28
+ ui?: boolean
29
+ }
30
+
31
+ // Assemble the selected server without binding a port. Hosts can reuse its
32
+ // request/upgrade listeners or call listen() themselves. `init(mode)` is
33
+ // `init({ mode })`.
34
+ export async function init(options: ServerMode | InitOptions = {}): Promise<Server> {
35
+ const { mode = 'e2e', ui = true }: InitOptions = typeof options === 'string' ? { mode: options } : options
36
+ const selected = parseMode(mode)
37
+ if (selected === 'e2e') {
38
+ const { createE2eApp } = await import('./server-e2e/app.ts')
39
+ return (await createE2eApp(undefined, { ui })).httpServer
40
+ }
41
+ if (selected === 'managed') {
42
+ const managed = await import('./server-managed/index.ts')
43
+ return managed.init(undefined, { ui })
44
+ }
45
+ const combined = await import('./server-managed/combined.ts')
46
+ return combined.init(selected === 'managed-e2e' ? 'managed+e2e' : 'e2e+managed', { ui })
47
+ }
48
+
49
+ export async function start(): Promise<void> {
50
+ const { values } = parseArgs({ options: {
51
+ mode: { type: 'string', default: 'e2e' },
52
+ help: { type: 'boolean', short: 'h' },
53
+ } })
54
+ const mode = parseMode(values.mode)
55
+ if (values.help) {
56
+ console.log(`Usage: node cli.js --mode <${modes.join('|')}>
57
+ Defaults to e2e. Combined modes share HOST/PORT; the first mode is the client default.
58
+ Managed modes require GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET and OAUTH_CALLBACK_URL.
59
+ Combined storage: DATABASE_URL for a shared Neon DB, or E2E_DATABASE_URL and
60
+ MANAGED_DATABASE_URL for separate Neon DBs. Do not mix shared and per-mode URLs.
61
+ Without URLs: SQLite at DB_PATH for e2e and MANAGED_DB_PATH for managed.
62
+ Combined mode does not support mixing Neon and SQLite.`)
63
+ } else {
64
+ const config = mode === 'managed'
65
+ ? (await import('./server-managed/config.ts')).loadManagedConfig()
66
+ : (await import('./server-e2e/config.ts')).loadConfig()
67
+ const server = await init(mode)
68
+ startServer(server, config)
69
+ }
70
+ }