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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (442) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +16 -78
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +6 -0
  13. package/common/bundle-compare-diff.js +377 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-imports.js +20 -0
  20. package/common/bundle-metadata.d.ts +15 -0
  21. package/common/bundle-metadata.js +226 -0
  22. package/common/bundle-pkg-of.d.ts +1 -0
  23. package/common/bundle-pkg-of.js +90 -0
  24. package/common/bundle-reasons.d.ts +6 -0
  25. package/common/bundle-reasons.js +58 -0
  26. package/common/bundle-source-links.d.ts +6 -0
  27. package/common/bundle-source-links.js +216 -0
  28. package/common/bundle-sourcemap.d.ts +10 -0
  29. package/common/bundle-sourcemap.js +100 -0
  30. package/common/bundle-sources.d.ts +10 -0
  31. package/common/bundle-sources.js +374 -0
  32. package/common/bundle-stats.js +41 -0
  33. package/common/bundle-tabs.js +1 -0
  34. package/common/code-language.js +66 -0
  35. package/common/default-scan-models.ts +36 -0
  36. package/common/dependency-reviews.d.ts +18 -0
  37. package/common/dependency-reviews.js +64 -0
  38. package/common/finding-duplicates.js +63 -0
  39. package/common/finding-filters.js +313 -0
  40. package/common/finding-id.js +47 -0
  41. package/common/finding-repo.d.ts +5 -0
  42. package/common/finding-repo.js +67 -0
  43. package/common/github-issue-labels.d.ts +1 -0
  44. package/common/github-issue-labels.js +11 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +14 -0
  48. package/common/line-diff.js +181 -0
  49. package/common/linked-workspace-groups.js +63 -0
  50. package/common/managed/agent-tasks.ts +292 -0
  51. package/common/managed/comments.ts +43 -0
  52. package/common/managed/dependency-routes.js +25 -0
  53. package/common/managed/directory-packages.ts +28 -0
  54. package/common/managed/finding-detail.d.ts +5 -0
  55. package/common/managed/finding-detail.js +75 -0
  56. package/common/managed/finding-values.d.ts +2 -0
  57. package/common/managed/finding-values.js +138 -0
  58. package/common/managed/github-agents.ts +114 -0
  59. package/common/managed/github-logins.ts +49 -0
  60. package/common/managed/lite-name.d.ts +2 -0
  61. package/common/managed/lite-name.js +20 -0
  62. package/common/managed/npm-packages.d.ts +9 -0
  63. package/common/managed/npm-packages.js +63 -0
  64. package/common/managed/permissions.ts +31 -0
  65. package/common/managed/report-content.ts +72 -0
  66. package/common/managed/report-filter.ts +120 -0
  67. package/common/managed/repository-alias.ts +65 -0
  68. package/common/managed/review-view-routes.js +23 -0
  69. package/common/managed/risk-routes.js +30 -0
  70. package/common/managed/roles.ts +41 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +385 -0
  73. package/common/managed/scan-models.ts +6 -0
  74. package/common/managed/stasis-config.ts +7 -0
  75. package/common/managed/team-app.d.ts +19 -0
  76. package/common/managed/team-app.js +129 -0
  77. package/common/managed/team-filters.js +26 -0
  78. package/common/managed/triage.ts +83 -0
  79. package/common/managed/upload-seal.ts +126 -0
  80. package/common/pretty-json.js +98 -0
  81. package/common/pretty-kinds.js +20 -0
  82. package/common/pretty-print.d.ts +6 -0
  83. package/common/pretty-print.js +36 -0
  84. package/common/pretty-sourcemap.js +70 -0
  85. package/common/repo-commit.d.ts +4 -0
  86. package/common/repo-commit.js +30 -0
  87. package/common/revalidation-conflicts.js +48 -0
  88. package/common/revalidation-input-groups.js +56 -0
  89. package/common/save-error-reason.ts +20 -7
  90. package/common/scan-server.ts +13 -0
  91. package/common/security-links.d.ts +5 -0
  92. package/common/security-links.js +33 -0
  93. package/common/server-info.ts +46 -0
  94. package/common/sourcemap-listing.js +78 -0
  95. package/common/sourcemap-mappings.js +136 -0
  96. package/common/sourcemap-unlist.js +85 -0
  97. package/common/stasis-files.d.ts +5 -0
  98. package/common/stasis-files.js +20 -0
  99. package/common/stasis-tgz.d.ts +6 -0
  100. package/common/stasis-tgz.js +27 -0
  101. package/common/utf8.d.ts +3 -0
  102. package/common/utf8.js +45 -0
  103. package/common/whitespace-insensitive.js +19 -0
  104. package/common/workspace-app.js +91 -0
  105. package/common/workspace-groups.js +176 -0
  106. package/out/activity.js +2 -0
  107. package/out/brotli-fallback.js +3 -3
  108. package/out/chunk-2XUEZHIP.js +28 -0
  109. package/out/chunk-55YIWY3H.js +5 -0
  110. package/out/chunk-5AVGKFMR.js +1 -0
  111. package/out/chunk-5CJKUV53.js +1 -0
  112. package/out/chunk-5EAVJAD2.js +3 -0
  113. package/out/chunk-5M2X3QPK.js +6 -0
  114. package/out/chunk-5QWPKTCE.js +40 -0
  115. package/out/chunk-6CCSTJWB.js +1 -0
  116. package/out/chunk-6VOB5WXX.js +2 -0
  117. package/out/chunk-6Y6PZ2BU.js +9 -0
  118. package/out/chunk-74JZTGTO.js +11 -0
  119. package/out/chunk-7BKKYVWR.js +7 -0
  120. package/out/chunk-7C7DWL7I.js +1 -0
  121. package/out/chunk-7HP2VYIC.js +2 -0
  122. package/out/chunk-7YFJUT2P.js +1 -0
  123. package/out/chunk-7YO4QV5P.js +1 -0
  124. package/out/chunk-A4BBBHQU.js +1 -0
  125. package/out/chunk-B64CTMVU.js +4 -0
  126. package/out/chunk-BEKYZCPX.js +14 -0
  127. package/out/chunk-C4Z6ZBXV.js +10 -0
  128. package/out/chunk-CU3FPB3P.js +1 -0
  129. package/out/chunk-DEVAORP2.js +1 -0
  130. package/out/chunk-DUASGS2O.js +8 -0
  131. package/out/chunk-DUS5ARE2.js +53 -0
  132. package/out/chunk-EEJA7JBI.js +13 -0
  133. package/out/chunk-FSU2PLJL.js +1 -0
  134. package/out/chunk-GBMAXAYK.js +3 -0
  135. package/out/chunk-GO7FT4OD.js +1 -0
  136. package/out/chunk-GX5UXWT4.js +1 -0
  137. package/out/chunk-ITUKKCCK.js +10 -0
  138. package/out/chunk-IYPY47MC.js +1 -0
  139. package/out/chunk-JXBRWLMA.js +4 -0
  140. package/out/chunk-K4XJHM2T.js +1 -0
  141. package/out/chunk-LBD3M3J6.js +1 -0
  142. package/out/chunk-LVSLM7HB.js +1 -0
  143. package/out/chunk-LVW7WWV4.js +1 -0
  144. package/out/chunk-MV66NL3G.js +3 -0
  145. package/out/chunk-N57OWFKY.js +15 -0
  146. package/out/chunk-NRPC74AM.js +1 -0
  147. package/out/chunk-OOJM4CTU.js +1 -0
  148. package/out/chunk-OWSEQOL5.js +1 -0
  149. package/out/chunk-PKLVXUEI.js +11 -0
  150. package/out/chunk-PLGH63UC.js +2 -0
  151. package/out/chunk-PNHBZGDD.js +1 -0
  152. package/out/chunk-PTFYDJUP.js +1 -0
  153. package/out/chunk-PWFUOLZK.js +17 -0
  154. package/out/chunk-PXK7EU4V.js +1 -0
  155. package/out/chunk-QD3IBSF4.js +7 -0
  156. package/out/chunk-QI66YA4F.js +1 -0
  157. package/out/chunk-QRKFPLA4.js +80 -0
  158. package/out/chunk-R3NZFXVR.js +1 -0
  159. package/out/chunk-R5O6FAW4.js +2 -0
  160. package/out/chunk-RPNO56H2.js +1 -0
  161. package/out/chunk-SSPDMA6D.js +1 -0
  162. package/out/chunk-SZWPYLPC.js +1 -0
  163. package/out/chunk-TUII34K2.js +1 -0
  164. package/out/chunk-UJP4PQJA.js +1 -0
  165. package/out/chunk-UJSJMXEG.js +1 -0
  166. package/out/chunk-UR4WYMIP.js +1 -0
  167. package/out/chunk-VHEXSGGP.js +1 -0
  168. package/out/chunk-VYYUMYVW.js +9 -0
  169. package/out/chunk-VZPPX6MV.js +1 -0
  170. package/out/chunk-WCDYSIKG.js +1 -0
  171. package/out/chunk-XM4RLC4A.js +2 -0
  172. package/out/chunk-YKCRCNYZ.js +266 -0
  173. package/out/chunk-ZQHLECTI.js +1 -0
  174. package/out/client-managed-import.js +4 -0
  175. package/out/client-managed.js +37 -0
  176. package/out/client-sync.js +11 -17
  177. package/out/compare.js +26 -0
  178. package/out/dialogs.js +40 -0
  179. package/out/github-issue-authorized.html +3 -0
  180. package/out/github-issue-authorized.js +1 -0
  181. package/out/graph.js +19 -4
  182. package/out/index.html +104 -24
  183. package/out/prism.js +14 -10
  184. package/out/scan.js +2 -0
  185. package/out/stasis.svg +20 -0
  186. package/out/terminal.js +367 -39
  187. package/out/view.css +1 -1
  188. package/out/view.js +19 -147
  189. package/package.json +409 -64
  190. package/risk/actions/findings.js +161 -0
  191. package/risk/actions/resolve.js +287 -0
  192. package/risk/actions/scripts/commands.js +182 -0
  193. package/risk/actions/scripts/grade.js +113 -0
  194. package/risk/actions/scripts/packages.js +123 -0
  195. package/risk/actions/scripts/shell.js +169 -0
  196. package/risk/actions/uses.js +94 -0
  197. package/risk/actions/workflow.js +183 -0
  198. package/risk/files/characters.js +341 -0
  199. package/risk/files/hosts.js +206 -0
  200. package/risk/files/readability.js +185 -0
  201. package/risk/files/runs-code.js +563 -0
  202. package/risk/files/script.js +402 -0
  203. package/risk/files/source-map-link.js +43 -0
  204. package/risk/files/stamps.js +47 -0
  205. package/risk/index.d.ts +294 -0
  206. package/risk/index.js +12 -0
  207. package/risk/npm/assess.js +285 -0
  208. package/risk/npm/combined.js +68 -0
  209. package/risk/npm/compare.js +236 -0
  210. package/risk/npm/dependencies.js +172 -0
  211. package/risk/npm/diff.js +79 -0
  212. package/risk/npm/downloads.js +84 -0
  213. package/risk/npm/files.js +445 -0
  214. package/risk/npm/held.js +67 -0
  215. package/risk/npm/install-scripts.js +34 -0
  216. package/risk/npm/malware.js +38 -0
  217. package/risk/npm/manifest.js +65 -0
  218. package/risk/npm/new-dependency.js +60 -0
  219. package/risk/npm/old-version.js +108 -0
  220. package/risk/npm/registry.js +393 -0
  221. package/risk/npm/release.js +85 -0
  222. package/risk/npm/score.js +59 -0
  223. package/risk/npm/specs.js +124 -0
  224. package/risk/npm/tarball.js +169 -0
  225. package/server-common/database-config.ts +16 -0
  226. package/server-common/initialize.ts +18 -0
  227. package/server-common/npm-advisories.ts +101 -0
  228. package/{server → server-common}/origin.ts +5 -5
  229. package/server-common/reap.ts +48 -0
  230. package/server-common/scan-config.ts +19 -0
  231. package/server-common/standalone.ts +29 -0
  232. package/server-common/storage-crypto.ts +182 -0
  233. package/server-common/storage-log.ts +38 -0
  234. package/server-common/vercel-blob.ts +103 -0
  235. package/server-e2e/app.ts +487 -0
  236. package/{server → server-e2e}/bus-receiver.ts +2 -1
  237. package/{server → server-e2e}/cli.js +9 -4
  238. package/{server → server-e2e}/config.ts +50 -42
  239. package/{server → server-e2e}/db-neon.ts +2 -2
  240. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  241. package/{server → server-e2e}/db-stmt.ts +2 -2
  242. package/{server → server-e2e}/db.ts +7 -7
  243. package/{server → server-e2e}/http.ts +44 -13
  244. package/{server → server-e2e}/hub.ts +40 -9
  245. package/server-e2e/index.ts +17 -0
  246. package/server-e2e/lifecycle.ts +95 -0
  247. package/{server → server-e2e}/neon-driver.ts +2 -2
  248. package/{server → server-e2e}/npm-proxy.ts +12 -145
  249. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  250. package/{server → server-e2e}/objstore/blob.ts +1 -1
  251. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  252. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  253. package/{server → server-e2e}/objstore/init.ts +19 -27
  254. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  255. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  257. package/{server → server-e2e}/objstore/rest.ts +3 -3
  258. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  259. package/{server → server-e2e}/objstore/store.ts +7 -7
  260. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  261. package/{server → server-e2e}/pubsub.ts +12 -9
  262. package/{server → server-e2e}/sign.ts +4 -4
  263. package/{server → server-e2e}/sse-server.ts +60 -33
  264. package/{server → server-e2e}/static.ts +18 -17
  265. package/{server → server-e2e}/sync-handlers.ts +64 -30
  266. package/{server → server-e2e}/ws-server.ts +20 -9
  267. package/server-managed/activity.ts +247 -0
  268. package/server-managed/agent-merges.ts +109 -0
  269. package/server-managed/app-agents.ts +23 -0
  270. package/server-managed/avatar-store.ts +13 -0
  271. package/server-managed/blob-store.ts +26 -0
  272. package/server-managed/brotli.ts +10 -0
  273. package/server-managed/bundle-advisories.ts +79 -0
  274. package/server-managed/bundle-advisory-inventory.ts +85 -0
  275. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  276. package/server-managed/bundle-build-diagnostics.js +23 -0
  277. package/server-managed/bundle-build-leases.ts +41 -0
  278. package/server-managed/bundle-build-worker.js +380 -0
  279. package/server-managed/bundle-build.ts +326 -0
  280. package/server-managed/bundle-cache.ts +261 -0
  281. package/server-managed/bundle-catalog.ts +29 -0
  282. package/server-managed/bundle-commits.ts +133 -0
  283. package/server-managed/bundle-dependency-reviews.ts +91 -0
  284. package/server-managed/bundle-store.ts +24 -0
  285. package/server-managed/bundle-summary-cache.ts +139 -0
  286. package/server-managed/bundle-validation.ts +33 -0
  287. package/server-managed/bundle.ts +151 -0
  288. package/server-managed/cache-storage.ts +20 -0
  289. package/server-managed/cli.js +21 -0
  290. package/server-managed/combined.ts +43 -0
  291. package/server-managed/comments.ts +138 -0
  292. package/server-managed/commit-coauthors.ts +105 -0
  293. package/server-managed/commit-lockfiles.ts +78 -0
  294. package/server-managed/comparison.ts +51 -0
  295. package/server-managed/config.ts +163 -0
  296. package/server-managed/content-access.ts +15 -0
  297. package/server-managed/crypto.ts +25 -0
  298. package/server-managed/db-methods.ts +1914 -0
  299. package/server-managed/db-neon.ts +398 -0
  300. package/server-managed/db-schema.ts +263 -0
  301. package/server-managed/db-table-names.ts +22 -0
  302. package/server-managed/db.ts +149 -0
  303. package/server-managed/dependabot-access.ts +61 -0
  304. package/server-managed/dependabot-alerts.ts +180 -0
  305. package/server-managed/dependency-review-comments.ts +143 -0
  306. package/server-managed/dependency-reviews.ts +369 -0
  307. package/server-managed/github-accounts.ts +59 -0
  308. package/server-managed/github-actions.ts +71 -0
  309. package/server-managed/github-app.ts +347 -0
  310. package/server-managed/github-errors.ts +92 -0
  311. package/server-managed/github-graphql.ts +42 -0
  312. package/server-managed/github-issue-links.ts +264 -0
  313. package/server-managed/github-issue-oauth.ts +30 -0
  314. package/server-managed/github-issues.ts +157 -0
  315. package/server-managed/github-link-oauth.ts +56 -0
  316. package/server-managed/github-links.ts +204 -0
  317. package/server-managed/github-metadata.ts +213 -0
  318. package/server-managed/github-oauth.ts +264 -0
  319. package/server-managed/github-pulls.ts +257 -0
  320. package/server-managed/github-requests.ts +181 -0
  321. package/server-managed/github-users.ts +30 -0
  322. package/server-managed/github-values.ts +26 -0
  323. package/server-managed/history-windows.ts +172 -0
  324. package/server-managed/http-response.ts +76 -0
  325. package/server-managed/http.ts +6324 -0
  326. package/server-managed/import-triage.ts +51 -0
  327. package/server-managed/index.ts +204 -0
  328. package/server-managed/kept-briefly.ts +37 -0
  329. package/server-managed/kept.ts +28 -0
  330. package/server-managed/link-reports.ts +149 -0
  331. package/server-managed/listed-activity.ts +39 -0
  332. package/server-managed/locked-packages.ts +234 -0
  333. package/server-managed/lockfile-scope.ts +58 -0
  334. package/server-managed/lru.ts +30 -0
  335. package/server-managed/managed-issues.ts +92 -0
  336. package/server-managed/management-catalog.ts +45 -0
  337. package/server-managed/management.ts +116 -0
  338. package/server-managed/npm-delta-worker.js +142 -0
  339. package/server-managed/npm-delta.ts +277 -0
  340. package/server-managed/npm-insights.ts +455 -0
  341. package/server-managed/npm-kept.ts +265 -0
  342. package/server-managed/npm-loads.ts +259 -0
  343. package/server-managed/npm-manifest.ts +117 -0
  344. package/server-managed/npm-packages.ts +469 -0
  345. package/server-managed/npm-patch-paths.ts +86 -0
  346. package/server-managed/npm-patch.ts +455 -0
  347. package/server-managed/npm-provenance.ts +127 -0
  348. package/server-managed/npm-risk.ts +287 -0
  349. package/server-managed/object-storage-disk.ts +147 -0
  350. package/server-managed/object-storage-vercel.ts +71 -0
  351. package/server-managed/object-storage.ts +82 -0
  352. package/server-managed/package-entry-points.ts +127 -0
  353. package/server-managed/pretty-copies.ts +22 -0
  354. package/server-managed/pretty-format.d.ts +3 -0
  355. package/server-managed/pretty-format.js +13 -0
  356. package/server-managed/pretty-print.ts +442 -0
  357. package/server-managed/public-workspace.ts +243 -0
  358. package/server-managed/pull-comment-reviews.ts +161 -0
  359. package/server-managed/pull-dependencies.ts +370 -0
  360. package/server-managed/pull-dependency-reviews.ts +407 -0
  361. package/server-managed/pull-reviews.ts +202 -0
  362. package/server-managed/queue.ts +54 -0
  363. package/server-managed/release-commits.ts +85 -0
  364. package/server-managed/rename-diff-worker.js +30 -0
  365. package/server-managed/rename-diff.ts +237 -0
  366. package/server-managed/repo-path.ts +21 -0
  367. package/server-managed/report-migration.ts +32 -0
  368. package/server-managed/report-opening.ts +77 -0
  369. package/server-managed/report-query.ts +10 -0
  370. package/server-managed/report-response.ts +16 -0
  371. package/server-managed/report-sources.ts +185 -0
  372. package/server-managed/report-store.ts +77 -0
  373. package/server-managed/repository-actions.ts +220 -0
  374. package/server-managed/repository-agents.ts +422 -0
  375. package/server-managed/repository-aliases.ts +119 -0
  376. package/server-managed/repository-browser.ts +361 -0
  377. package/server-managed/repository-changes.ts +280 -0
  378. package/server-managed/repository-code.ts +222 -0
  379. package/server-managed/repository-dependency-reviews.ts +182 -0
  380. package/server-managed/repository-discovery.ts +83 -0
  381. package/server-managed/repository-history.ts +428 -0
  382. package/server-managed/repository-issues.ts +293 -0
  383. package/server-managed/repository-policy.ts +27 -0
  384. package/server-managed/repository-pulls.ts +207 -0
  385. package/server-managed/repository-pulse.ts +477 -0
  386. package/server-managed/repository-risk-assess.ts +108 -0
  387. package/server-managed/repository-risk-audit.ts +78 -0
  388. package/server-managed/repository-risk-caches.ts +37 -0
  389. package/server-managed/repository-risk-read.ts +260 -0
  390. package/server-managed/repository-risk-stasis.ts +61 -0
  391. package/server-managed/repository-risk-turn.ts +97 -0
  392. package/server-managed/repository-risk.ts +516 -0
  393. package/server-managed/repository-squashes.ts +160 -0
  394. package/server-managed/repository-stamp.ts +41 -0
  395. package/server-managed/request-timing.ts +63 -0
  396. package/server-managed/reviewed-dependencies.ts +170 -0
  397. package/server-managed/revisions.ts +35 -0
  398. package/server-managed/scan-downloads.ts +121 -0
  399. package/server-managed/session.ts +132 -0
  400. package/server-managed/slugs.ts +38 -0
  401. package/server-managed/solidity-entry-points.ts +71 -0
  402. package/server-managed/sql-postgres.ts +34 -0
  403. package/server-managed/sql.ts +107 -0
  404. package/server-managed/stasis-config.ts +147 -0
  405. package/server-managed/stasis-dependencies.ts +221 -0
  406. package/server-managed/static.ts +28 -0
  407. package/server-managed/storage-command.ts +16 -0
  408. package/server-managed/storage-db.ts +183 -0
  409. package/server-managed/storage-encryption.ts +288 -0
  410. package/server-managed/storage-maintenance.ts +259 -0
  411. package/server-managed/storage-payload.ts +121 -0
  412. package/server-managed/storage-stores.ts +91 -0
  413. package/server-managed/storage.ts +82 -0
  414. package/server-managed/team-app-summaries.ts +56 -0
  415. package/server-managed/team-app.ts +156 -0
  416. package/server-managed/team-catalog.ts +7 -0
  417. package/server-managed/team-feed.ts +180 -0
  418. package/server-managed/team-npm-scopes.ts +103 -0
  419. package/server-managed/team-reports.ts +368 -0
  420. package/server-managed/triage-response.ts +16 -0
  421. package/server-managed/type-only-proof.js +161 -0
  422. package/server-managed/type-only-worker.js +31 -0
  423. package/server-managed/type-only.ts +135 -0
  424. package/server-managed/uploads.ts +106 -0
  425. package/server-managed/upstream-cache.ts +256 -0
  426. package/server-managed/view-as.ts +58 -0
  427. package/server-managed/worker-turns.ts +76 -0
  428. package/server-managed/workspace-shares.ts +170 -0
  429. package/server.ts +70 -0
  430. package/strip-types-loader.js +13 -10
  431. package/server/index.ts +0 -480
  432. package/server/lifecycle.ts +0 -208
  433. /package/{LICENSE → LICENSE-MIT} +0 -0
  434. /package/{server → server-e2e}/auth.ts +0 -0
  435. /package/{server → server-e2e}/config.example.json +0 -0
  436. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  437. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  438. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  439. /package/{server → server-e2e}/peer.ts +0 -0
  440. /package/{server → server-e2e}/sse-session.ts +0 -0
  441. /package/{server → server-e2e}/util.ts +0 -0
  442. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,1914 @@
1
+ import { type LinkReportStore, linkReportMethods, linkRevision, linkRevisionOf } from './link-reports.ts'
2
+ import { type RepositoryAliasStore, repositoryAliasMethods } from './repository-aliases.ts'
3
+ import { type DependencyReviewStore, dependencyReviewMethods } from './dependency-reviews.ts'
4
+ import { type RepositoryDependencyReviewStore, repositoryDependencyReviewMethods } from './repository-dependency-reviews.ts'
5
+ import { type TeamNpmScopeStore, teamNpmScopeMethods } from './team-npm-scopes.ts'
6
+ import { type GithubLinkStore, githubLinkMethods } from './github-links.ts'
7
+ import { createHash, randomUUID } from 'node:crypto'
8
+ import { teamCatalogRevision } from './team-catalog.ts'
9
+ import { type Role, roleAtLeast } from '../common/managed/roles.ts'
10
+ import type { TeamUserPermissions } from '../common/managed/permissions.ts'
11
+ import type { TriageEntryPatch } from '../common/managed/triage.ts'
12
+ import { preferredSlug } from './slugs.ts'
13
+ import { type CommentStore, commentMethods } from './comments.ts'
14
+ import { type ActivityStore, activityMethods } from './activity.ts'
15
+ import { type GithubCommitStore, type GithubMetadataStore, githubCommitMethods, githubMetadataMethods } from './github-metadata.ts'
16
+ import { type ManagedIssue, type ManagedIssueStore, managedIssueMethods } from './managed-issues.ts'
17
+ import type { IssueFixUpdate } from './github-issue-links.ts'
18
+ import { type BundleBuildLeaseStore, bundleBuildLeaseMethods } from './bundle-build-leases.ts'
19
+ import { type UpstreamCacheStore, upstreamCacheMethods } from './upstream-cache.ts'
20
+ import { type TeamAppSummaryStore, teamAppSummaryMethods } from './team-app-summaries.ts'
21
+ import { type ImportTriageStore, importTriageMethods } from './import-triage.ts'
22
+ import { type ManagedSql, jsonRows } from './sql.ts'
23
+ import { type WorkspaceShareStore, workspaceShareMethods } from './workspace-shares.ts'
24
+ import { ManagedMutationError, type ManagementStore, managementMethods } from './management.ts'
25
+ import { type ManagementCatalogStore, managementCatalogMethods } from './management-catalog.ts'
26
+ import { type StorageKey } from '../server-common/storage-crypto.ts'
27
+ import { type StorageDb, type StoredTokens, decodeStorageTokens, encodeStorageTokens, storageMethods, storageState, storageStateColumns, storageStateOf, validateStorageUpload } from './storage-db.ts'
28
+ import { inUserTeamScope, withinTeamPath } from './db-schema.ts'
29
+
30
+ // A managed user identity (the subset of GitHub's `GET /user` we keep). Input
31
+ // to the upsert; `githubUserId` is the provider lookup key, never exposed to
32
+ // clients.
33
+ export interface ManagedUser {
34
+ githubUserId: number
35
+ login: string
36
+ name: string | null
37
+ avatarUrl: string | null
38
+ }
39
+
40
+ // A persisted user as read back from a session — identified by the opaque `id`;
41
+ // the GitHub id stays server-internal.
42
+ export interface StoredUser {
43
+ id: string
44
+ login: string
45
+ name: string | null
46
+ avatarUrl: string | null
47
+ role: Role
48
+ }
49
+
50
+ // A user row for the admin users list.
51
+ export interface AdminUser {
52
+ id: string
53
+ login: string
54
+ name: string | null
55
+ role: Role
56
+ createdAt: number
57
+ lastSeenAt: number | null
58
+ lastActivityAt: number | null
59
+ }
60
+
61
+ // A user's persisted GitHub user-to-server token. `refreshToken` / `expiresAt`
62
+ // are null when the App issues non-expiring tokens.
63
+ export interface UserTokens {
64
+ accessToken: string
65
+ refreshToken: string | null
66
+ expiresAt: number | null
67
+ }
68
+
69
+ export interface ManagedSession {
70
+ id: string
71
+ userId: string
72
+ csrfToken: string
73
+ expiresAt: number
74
+ // Private JWK for sealed uploads; null until the session first asks for it.
75
+ uploadKey?: string | null
76
+ // Set on an administrator's read-only view as `userId` (see view-as.ts).
77
+ viewer?: ManagedViewer
78
+ }
79
+
80
+ export interface ManagedViewer {
81
+ id: string
82
+ login: string
83
+ name: string | null
84
+ }
85
+
86
+ // A repository selected for the workspace to operate on, with the context to
87
+ // read its contents: `installationId` mints an App installation token (Contents:
88
+ // Read) for a PRIVATE repo — null for a PUBLIC repo readable without the App —
89
+ // and `fullName` + `defaultBranch` locate the contents
90
+ // (GET /repos/{fullName}/contents?ref={defaultBranch}).
91
+ export interface SelectedRepo {
92
+ repoId: number
93
+ fullName: string
94
+ private: boolean
95
+ installationId: number | null
96
+ defaultBranch: string
97
+ // Last live default observed by the repository browser, independent of the
98
+ // selection/discovery snapshot above. NULL means unknown or unavailable.
99
+ cachedDefaultBranch: string | null
100
+ htmlUrl: string
101
+ addedBy: string | null
102
+ addedAt: number
103
+ }
104
+
105
+ // The admin repository directory includes inactive connections as well. Their
106
+ // metadata remains available for existing reports/bundles, while only active
107
+ // rows are returned by listSelectedRepos for new scans and attachments.
108
+ export interface ManagedRepo extends SelectedRepo {
109
+ active: boolean
110
+ }
111
+
112
+ // What a caller supplies to select (upsert) a repo; the store stamps the
113
+ // timestamps.
114
+ export type SelectedRepoInput = Omit<SelectedRepo, 'addedAt' | 'cachedDefaultBranch'>
115
+
116
+ // A stored report's metadata. The bytes live in the blob-store keyed by `id`;
117
+ // `contentType` + `filename` ride here so a download can label them, `sha256`
118
+ // (base64url) is the content hash for integrity, `uploadedBy` is the opaque
119
+ // uploader id (null once that user is removed).
120
+ export interface ReportRecord {
121
+ id: string
122
+ slug: string
123
+ filename: string
124
+ contentType: string
125
+ byteSize: number
126
+ sha256: string
127
+ uploadedBy: string | null
128
+ uploadedAt: number
129
+ repoId: number | null
130
+ repoDirectory: string
131
+ repoEmbedded: boolean
132
+ analyzer: string | null
133
+ visible: boolean
134
+ bundleId: string | null
135
+ // Whether it may be switched to open on Confirmed (null: not read yet), and
136
+ // whether it is (report-opening.ts).
137
+ confirmedOffered: boolean | null
138
+ confirmedDefault: boolean
139
+ }
140
+
141
+ // One transaction snapshots all metadata needed to authorize, filter and
142
+ // revalidate a report batch. Unauthorized/missing reports are omitted.
143
+ export interface ReportAccessRecord {
144
+ id: string
145
+ filename: string
146
+ byteSize: number
147
+ sha256: string
148
+ repo: { github: string | null; directory: string }
149
+ permissions: TeamUserPermissions
150
+ // Set where a team snapshot reads a report switched to open on Confirmed.
151
+ confirmedDefault?: true
152
+ }
153
+ export interface TeamReportAccessSnapshot extends ReportAccessSnapshot {
154
+ teamId: string | null
155
+ reportId?: string | null
156
+ hiddenReportId?: string | null
157
+ repositories: { repoId: number; github: string; path: string | null }[]
158
+ // By report ID, the content key its catalog entry has (UserTeamReport
159
+ // cacheKey) as read with the rest.
160
+ catalogKeys?: Readonly<Record<string, string>>
161
+ }
162
+ export interface ReportAccessSnapshot {
163
+ user: StoredUser
164
+ linkRevision?: string
165
+ reports: ReportAccessRecord[]
166
+ }
167
+
168
+ // What the upload handler supplies to record a report; the store stamps
169
+ // uploaded_at. `repoId` / `bundleId` are the (nullable) repo + auto-resolved
170
+ // bundle links; `bundleIntegrity` is the report's declared primary bundle (kept
171
+ // so a later bundle upload of that integrity re-links it).
172
+ export interface ReportRecordInput {
173
+ dataKey?: string | null
174
+ id: string
175
+ filename: string
176
+ contentType: string
177
+ byteSize: number
178
+ sha256: string
179
+ uploadedBy: string | null
180
+ uploadedByLogin: string | null
181
+ repoId: number | null
182
+ repoDirectory: string
183
+ repoEmbedded?: boolean
184
+ analyzer: string | null
185
+ visible: boolean
186
+ bundleId: string | null
187
+ bundleIntegrity: string | null
188
+ // Read of its content as it is uploaded (report-opening.ts); none: not yet.
189
+ confirmedOffered?: boolean | null
190
+ }
191
+
192
+ // A report row for the "Manage reports" list — adds display joins: uploader
193
+ // login, repo full name, and the linked bundle's filename (each null when
194
+ // absent / since removed).
195
+ export interface AdminReport {
196
+ id: string
197
+ slug: string
198
+ filename: string
199
+ contentType: string
200
+ byteSize: number
201
+ sha256: string
202
+ uploadedByLogin: string | null
203
+ repoId: number | null
204
+ repoFullName: string | null
205
+ repoDirectory: string
206
+ repoEmbedded: boolean
207
+ analyzer: string | null
208
+ visible: boolean
209
+ bundleId: string | null
210
+ bundleFilename: string | null
211
+ bundleIntegrity: string | null
212
+ uploadedAt: number
213
+ confirmedOffered: boolean | null
214
+ confirmedDefault: boolean
215
+ }
216
+
217
+ export interface RepoDataItem {
218
+ id: string
219
+ filename: string
220
+ }
221
+
222
+ export type RepoReportItem = Pick<ReportRecord, 'id' | 'filename' | 'sha256' | 'bundleId'>
223
+
224
+ // A report that names a bundle: linked to it (bundleId is that bundle's), or
225
+ // declaring its integrity as the bundle it was made from without the link.
226
+ // `readable`: whether the manager asking may read it (as getReportView tells).
227
+ export type BundleReportItem = Pick<ReportRecord, 'id' | 'filename' | 'bundleId'> & { readable: boolean }
228
+
229
+ // A stored per-finding triage row, with the last writer's login resolved like
230
+ // listReports (live login, falling back to the durable snapshot). `flagged`
231
+ // maps the tri-state column: null unset, true/false set. Every field null =
232
+ // the tombstone of a cleared entry.
233
+ export interface TriageRow {
234
+ findingId: string
235
+ color: string | null
236
+ triage: string | null
237
+ comment: string | null
238
+ fix: string | null
239
+ flagged: boolean | null
240
+ updatedByLogin: string | null
241
+ updatedAt: number
242
+ }
243
+
244
+ // One row of a finding's triage trail: the entry as written by that event
245
+ // (every field null = a clear), the actor's login resolved like TriageRow's
246
+ // writer, and the request it came in with.
247
+ export interface TriageEventRow {
248
+ seq: number
249
+ findingId: string
250
+ batchId: string
251
+ color: string | null
252
+ triage: string | null
253
+ comment: string | null
254
+ fix: string | null
255
+ flagged: boolean | null
256
+ actorId: string | null
257
+ actorLogin: string | null
258
+ actorName: string | null
259
+ at: number
260
+ }
261
+
262
+ // How a bundle's bytes arrived: uploaded, or generated by this server from a
263
+ // repository. null predates the distinction (possibly built).
264
+ export type BundleProvenance = 'upload' | 'build'
265
+
266
+ // The preset, export conditions and Metro platforms a server build of a JS/TS
267
+ // bundle resolved with, as the build request named them. Stored as JSON.
268
+ export interface BundleBuildConditions { preset: 'node' | 'browser' | 'metro'; conditions: string[]; platforms: string[] }
269
+
270
+ // A stored bundle's metadata. Bytes live in the blob-store keyed by `id`;
271
+ // `integrity` (sha512-<base64>) is the content-addressed identity (UNIQUE),
272
+ // matched against a report's bundleHashes to auto-link.
273
+ export interface ManagedBundle {
274
+ visible: boolean
275
+ id: string
276
+ slug: string
277
+ integrity: string
278
+ filename: string
279
+ kind: string | null
280
+ byteSize: number
281
+ uploadedBy: string | null
282
+ repoDirectory: string
283
+ repoId: number | null
284
+ uploadedAt: number
285
+ provenance: BundleProvenance | null
286
+ // null for uploads, Solidity builds, and builds predating the column.
287
+ buildConditions: BundleBuildConditions | null
288
+ }
289
+
290
+ // What the upload handler supplies to record a bundle; the store stamps
291
+ // uploaded_at. `uploadedByLogin` is the durable uploader-login snapshot.
292
+ export type BundleInput = Omit<ManagedBundle, 'uploadedAt' | 'slug' | 'repoDirectory' | 'visible' | 'provenance' | 'buildConditions'> & {
293
+ visible?: boolean; uploadedByLogin: string | null; repoDirectory?: string; dataKey?: string | null; provenance?: BundleProvenance | null
294
+ buildConditions?: BundleBuildConditions | null
295
+ }
296
+
297
+ // A repeated upload or build of stored bytes (see reuseBundle).
298
+ export interface BundleReuse { provenance: BundleProvenance; filename: string; kind: string | null; rename: boolean; buildConditions?: BundleBuildConditions | null }
299
+
300
+ // A bundle row for the "Manage bundles" list — adds the uploader login + repo
301
+ // full name display joins (null when absent / since removed).
302
+ export interface AdminBundle {
303
+ visible: boolean
304
+ id: string
305
+ slug: string
306
+ integrity: string
307
+ filename: string
308
+ kind: string | null
309
+ byteSize: number
310
+ uploadedByLogin: string | null
311
+ repoDirectory: string
312
+ repoId: number | null
313
+ repoFullName: string | null
314
+ uploadedAt: number
315
+ provenance: BundleProvenance | null
316
+ }
317
+
318
+ // A team's repo link (with its optional subpath) and member (with resolved
319
+ // login + visibility permissions), as carried in the AdminTeam detail.
320
+ export interface TeamRepoLink {
321
+ repoId: number
322
+ fullName: string
323
+ path: string | null
324
+ }
325
+ export interface TeamMember extends TeamUserPermissions {
326
+ userId: string
327
+ login: string
328
+ }
329
+
330
+ // A team with its links inlined, for the "Manage teams" page.
331
+ export interface AdminTeam {
332
+ id: string
333
+ slug: string
334
+ name: string
335
+ hidden: boolean
336
+ repos: TeamRepoLink[]
337
+ members: TeamMember[]
338
+ }
339
+
340
+ // A user id + login, for the team-member picker (lighter than the admin users
341
+ // list, and usable by manage — not just admin). A `type` (not interface) so a
342
+ // SQLite row casts straight to it.
343
+ export type UserOption = {
344
+ id: string
345
+ login: string
346
+ name: string | null
347
+ role: Role
348
+ }
349
+
350
+ // A team as shown in a member's own sidebar: the team name plus the reports and
351
+ // bundles attached to the team's repos (id + filename, newest first). An item
352
+ // shows under a team when its repo is one of the team's linked repos.
353
+ export interface UserTeamReport {
354
+ visible: boolean
355
+ id: string
356
+ slug: string
357
+ filename: string
358
+ analyzer: string | null
359
+ repoFullName: string | null
360
+ repoDirectory: string
361
+ cacheKey: string
362
+ }
363
+ export interface UserTeamBundle {
364
+ visible: boolean
365
+ id: string
366
+ slug: string
367
+ integrity: string
368
+ filename: string
369
+ kind: string | null
370
+ byteSize: number
371
+ repoDirectory: string
372
+ repoId: number
373
+ repoFullName: string
374
+ provenance: BundleProvenance | null
375
+ }
376
+ export interface UserTeam {
377
+ id: string
378
+ slug: string
379
+ name: string
380
+ dependencyReview?: boolean
381
+ permissions: TeamUserPermissions
382
+ cacheKey?: string
383
+ // The team's repository links, by name: its Repositories, whether or not
384
+ // anything is attached to them yet.
385
+ repos: TeamRepoLink[]
386
+ reports: UserTeamReport[]
387
+ bundles: UserTeamBundle[]
388
+ }
389
+
390
+ // Backend-agnostic store surface (SQLite + PostgreSQL implementations).
391
+ export interface ManagedDb extends DependencyReviewStore, RepositoryDependencyReviewStore, ActivityStore, CommentStore, GithubMetadataStore, GithubCommitStore, ManagedIssueStore, BundleBuildLeaseStore, UpstreamCacheStore, TeamAppSummaryStore, WorkspaceShareStore, ImportTriageStore, ManagementStore, ManagementCatalogStore, StorageDb, LinkReportStore, RepositoryAliasStore, TeamNpmScopeStore, GithubLinkStore {
392
+ claimMaintenanceLease(owner: string, now: number, until: number, migration?: boolean): Promise<boolean>
393
+ finishMaintenanceLease(owner: string, until: number): Promise<void>
394
+ getFeedState(sessionId: string, now: number): Promise<{ user: Pick<StoredUser, 'id' | 'role'>; catalog: number; annotations: number } | null>
395
+ // Reuse connections within a finite request or one feed polling iteration.
396
+ withRequest?<T>(work: () => Promise<T>): Promise<T>
397
+ // Upsert the identity; returns the user's opaque id (stable across logins),
398
+ // or null for an account linked to a user (github-links.ts), which neither
399
+ // signs in nor registers. A name chosen from a linked account is kept.
400
+ // Initial-admin approval comes only from trusted login configuration. It
401
+ // promotes a matching No access identity only while it is the sole user.
402
+ upsertUser(user: ManagedUser, now: number, initialAdminGithubId?: number | null): Promise<string | null>
403
+ createSession(session: ManagedSession, now: number): Promise<void>
404
+ // A sign-in session; never a view session, so a view token in the session
405
+ // cookie authenticates nothing.
406
+ sessionWithUser(id: string, now: number): Promise<{ session: ManagedSession; user: StoredUser } | null>
407
+ // Replace the view opened by an admin's session with a view as `userId`.
408
+ // False, keeping any earlier view, unless that session is current, its user
409
+ // is still an admin, and `userId` is another existing account. The view
410
+ // expires with that session.
411
+ createViewSession(view: { id: string; viewerSessionId: string; userId: string; csrfToken: string }, now: number): Promise<boolean>
412
+ // A view session opened by `viewerSessionId`, while that session is current
413
+ // and its user is still an admin. Presence is the admin's, not the viewed user's.
414
+ viewSessionWithUser(id: string, viewerSessionId: string, now: number): Promise<{ session: ManagedSession; user: StoredUser } | null>
415
+ // The two above as they read, recording no presence: for a read again in a
416
+ // request whose first read recorded it.
417
+ getSessionWithUser(id: string, now: number): Promise<{ session: ManagedSession; user: StoredUser } | null>
418
+ getViewSessionWithUser(id: string, viewerSessionId: string, now: number): Promise<{ session: ManagedSession; user: StoredUser } | null>
419
+ // Store `candidate` unless the session already has an upload key; returns
420
+ // the stored key, or null when the session no longer exists.
421
+ ensureSessionUploadKey(id: string, candidate: string): Promise<string | null>
422
+ deleteSession(id: string): Promise<void>
423
+ deleteExpiredSessions(now: number): Promise<number>
424
+ listUsers(): Promise<AdminUser[]>
425
+ // One user by id, as their sessions read them, or null; for an action naming
426
+ // one, where listUsers would work out every user's latest activity.
427
+ getUser(id: string): Promise<StoredUser | null>
428
+ // Set a user's role; resolves true iff a matching user row was updated.
429
+ setUserRole(id: string, role: Role): Promise<boolean>
430
+ // Persist / read a user's GitHub token (for on-demand repo listing).
431
+ setUserTokens(id: string, tokens: UserTokens): Promise<void>
432
+ getUserTokens(id: string): Promise<UserTokens | null>
433
+ getUserGithubId(id: string): Promise<number | null>
434
+ // Repo selection ("operate on"). selectRepo upserts by repo id, refreshing the
435
+ // mutable context while keeping the original added_by/added_at; deselectRepo
436
+ // resolves true iff a row was removed.
437
+ selectRepo(repo: SelectedRepoInput, now: number): Promise<void>
438
+ cacheRepoDefaultBranch(repo: SelectedRepo, branch: string | null): Promise<boolean>
439
+ connectRepoInstallation(repo: SelectedRepo, installationId: number, sessionId: string, now: number): Promise<boolean>
440
+ deselectRepo(repoId: number): Promise<boolean>
441
+ listSelectedRepos(): Promise<SelectedRepo[]>
442
+ listAllRepos(): Promise<ManagedRepo[]>
443
+ // A selected repository's full name, active or not; null for none.
444
+ getRepoFullName(repoId: number): Promise<string | null>
445
+ deactivateRepo(repoId: number): Promise<boolean>
446
+ reactivateRepo(repoId: number): Promise<boolean>
447
+ deleteRepo(repoId: number): Promise<boolean>
448
+ listReportsForRepo(repoId: number): Promise<RepoReportItem[]>
449
+ listBundlesForRepo(repoId: number): Promise<RepoDataItem[]>
450
+ deleteReportsForRepo(repoId: number): Promise<number>
451
+ deleteBundlesForRepo(repoId: number): Promise<number>
452
+ // Permanently delete current annotations AND their history atomically.
453
+ // Returns the number of current rows removed (not the number of events).
454
+ deleteTriage(findingIds: readonly string[]): Promise<number>
455
+ // Reports ("Manage reports"). insertReport records an uploaded report's
456
+ // metadata (bytes are written to the blob-store separately); listReports joins
457
+ // the uploader login + repo + linked-bundle filename for the admin list;
458
+ // getReport reads one row (for download); deleteReport resolves true iff a row
459
+ // was removed.
460
+ insertReport(report: ReportRecordInput, now: number): Promise<void>
461
+ // Content reuse is atomic with insertion, including across server instances.
462
+ // Existing copies are kept; the oldest matching row is the stable identity.
463
+ // HTTP uploads pass sessionId to recheck role/destination in that transaction.
464
+ insertOrReuseReport(report: ReportRecordInput, now: number, sessionId?: string): Promise<ReportRecord>
465
+ getReportByHash(sha256: string, analyzer: string | null): Promise<ReportRecord | null>
466
+ listReports(userId?: string): Promise<AdminReport[]>
467
+ listFindingCatalogReports(after: string, limit: number): Promise<Pick<ReportRecord, 'id' | 'byteSize'>[]>
468
+ getReport(id: string): Promise<ReportRecord | null>
469
+ // Writer-locked reconciliation waits for an uncertain earlier insert.
470
+ resolveReportUpload(id: string): Promise<ReportRecord | null>
471
+ getTeamReportAccessSnapshot(sessionId: string, now: number, teamId: string, reportId?: string | null): Promise<TeamReportAccessSnapshot | null>
472
+ getReportAccessSnapshot(sessionId: string, now: number, ids: readonly string[]): Promise<ReportAccessSnapshot | null>
473
+ listReportFilenamesWithBundleHash(bundleId: string, sha256: string): Promise<string[]>
474
+ // The reports linked to a bundle, or whose bundleHashes declared its integrity
475
+ // (bundle_integrity), newest first: what deleting it leaves without code.
476
+ // Each says whether the manager `userId` (none: an admin) may read it.
477
+ listReportsForBundle(bundleId: string, integrity: string, userId?: string): Promise<BundleReportItem[]>
478
+ deleteReport(id: string): Promise<boolean>
479
+ // Attach / detach a report's repo + directory link (repoId null = detach);
480
+ // resolves true iff the report exists. The caller validates repoId and the
481
+ // directory path.
482
+ setReportRepo(id: string, repoId: number | null, repoDirectory?: string): Promise<boolean>
483
+ setReportVisible(id: string, visible: boolean): Promise<boolean>
484
+ // A manager's switch of a report to open on Confirmed, resolving true iff it
485
+ // changed; and, of those not read for it yet, whether each may be
486
+ // (report-opening.ts), all in one write, any another read already told
487
+ // left as it is.
488
+ setReportConfirmedDefault(id: string, on: boolean): Promise<boolean>
489
+ setReportsConfirmedOffered(read: readonly { id: string; offered: boolean }[]): Promise<void>
490
+ // Per-finding triage annotations, keyed by finding id alone (shared by every
491
+ // report carrying the finding). listTriage reads the rows for a set of ids —
492
+ // the endpoint passes a viewer's visible findings of one report; a cleared
493
+ // entry comes back as a row with every field null (its tombstone).
494
+ // setTriage replaces one row wholesale, stamping the writer — a null/empty
495
+ // entry writes the tombstone rather than deleting; setTriageEntries does the
496
+ // same for a batch in one transaction: it lands whole or not at all. A write
497
+ // that leaves the entry as it is changes nothing — neither the row's writer
498
+ // stamp nor the trail. Every change also appends to managed_finding_triage_event;
499
+ // listTriageHistory walks one finding's trail, newest first.
500
+ listTriage(findingIds: readonly string[]): Promise<TriageRow[]>
501
+ // The distinct Fix links of those, without the rest of their entries.
502
+ listTriageFixes(findingIds: readonly string[]): Promise<string[]>
503
+ getAnnotations(findingIds: readonly string[]): Promise<{ triage: TriageRow[]; comments: Awaited<ReturnType<CommentStore['listComments']>>; issues: Awaited<ReturnType<ManagedIssueStore['listManagedIssues']>> }>
504
+ applyManagedIssueFixes(sessionId: string, snapshot: TeamReportAccessSnapshot, updates: IssueFixUpdate[]): Promise<boolean>
505
+ // A content-free fingerprint of current annotations, read in one snapshot.
506
+ getAnnotationRevision(findingIds: readonly string[]): Promise<string>
507
+ setTriage(findingId: string, entry: TriageEntryPatch | null, updatedBy: string | null, updatedByLogin: string | null, now: number): Promise<void>
508
+ setTriageEntries(entries: readonly (readonly [string, TriageEntryPatch | null])[], updatedBy: string | null, updatedByLogin: string | null, now: number, reportId?: string): Promise<void>
509
+ listTriageHistory(findingId: string, limit: number): Promise<TriageEventRow[]>
510
+ // Bundles ("Manage bundles"). insertBundle records an uploaded bundle (bytes
511
+ // in the blob-store); getBundleByIntegrity dedupes uploads + resolves a
512
+ // report's bundleHashes; getBundle reads one row (download); listBundles joins
513
+ // uploader login + repo; deleteBundle resolves true iff a row was removed
514
+ // (referencing reports' bundle_id null out via the FK). linkReportsToBundle
515
+ // attaches a freshly-stored bundle to the (still-unlinked) reports that
516
+ // declared its integrity. reuseBundle records a repeated upload or build of
517
+ // stored bytes: a build always marks the row built and records its conditions
518
+ // where the row has none, and with `rename` an uploaded row takes the new
519
+ // filename/kind. A built row is never renamed; one predating provenance is
520
+ // renamed only by a build. Resolves true iff changed.
521
+ // The caller authorizes `rename` (see reuseBundleUpload).
522
+ insertBundle(bundle: BundleInput, now: number, sessionId?: string): Promise<void>
523
+ reuseBundle(id: string, reuse: BundleReuse): Promise<boolean>
524
+ getBundleByIntegrity(integrity: string): Promise<ManagedBundle | null>
525
+ resolveBundleUpload(integrity: string): Promise<ManagedBundle | null>
526
+ getBundle(id: string): Promise<ManagedBundle | null>
527
+ // One statement reads the live session, bundle and grants. Passing a team
528
+ // (or null for any team) also checks advisory security access; omission skips it.
529
+ getBundleAccessSnapshot(sessionId: string, now: number, id: string, advisoriesTeamId?: string | null): Promise<{
530
+ bundle: ManagedBundle | null; canReadAdvisories: boolean
531
+ } | null>
532
+ listBundles(userId?: string): Promise<AdminBundle[]>
533
+ listReadableBundleIds(userId: string, ids: readonly string[]): Promise<string[]>
534
+ userCanReadBundle(userId: string, id: string): Promise<boolean>
535
+ userCanReadRepo(userId: string, repoId: number): Promise<boolean>
536
+ userCanReadBundleAdvisories(userId: string, bundleId: string, teamId: string | null): Promise<boolean>
537
+ userCanReadRepoPath(userId: string, repoId: number, directory: string): Promise<boolean>
538
+ deleteBundle(id: string): Promise<boolean>
539
+ // Set a bundle's repository and normalized directory (repoId null detaches
540
+ // and clears the directory). The caller validates the location and access.
541
+ setBundleRepo(id: string, repoId: number | null, directory?: string): Promise<boolean>
542
+ setBundleVisible(id: string, visible: boolean): Promise<boolean>
543
+ linkReportsToBundle(integrity: string, bundleId: string, userId?: string): Promise<void>
544
+ // Teams ("Manage teams"). createTeam inserts a team (false iff the name is
545
+ // taken); renameTeam changes a team's name ('name-taken' iff another team
546
+ // already has it, 'not-found' iff no such team, 'ok' otherwise — same name is
547
+ // idempotent); deleteTeam drops it (cascading its links); listTeams returns
548
+ // every team (including hidden ones) with its repos + members inlined; listUserOptions is the id+login+name
549
+ // set for the member picker. The set*/remove* pairs maintain the link tables:
550
+ // setTeamRepo adds a path (whole repo replaces paths); setTeamMember upserts a
551
+ // membership + its visibility permissions (each resolves true iff a row was
552
+ // written / removed; the caller validates the team/repo/user exist first).
553
+ createTeam(id: string, name: string, now: number): Promise<boolean>
554
+ renameTeam(id: string, name: string, now: number): Promise<'ok' | 'name-taken' | 'not-found'>
555
+ // Hiding preserves links but disables all grants and workspace access.
556
+ setTeamHidden(id: string, hidden: boolean, now: number): Promise<boolean>
557
+ deleteTeam(id: string): Promise<boolean>
558
+ getTeam(id: string): Promise<{ id: string; slug: string; name: string; hidden: boolean } | null>
559
+ listTeams(): Promise<AdminTeam[]>
560
+ listUserOptions(): Promise<UserOption[]>
561
+ // Current grants for manager content reads, writes, and repository pickers.
562
+ listRepoScopesForUser(userId: string): Promise<{ repoId: number; path: string | null }[]>
563
+ // The non-hidden teams a given user belongs to (name-sorted), each with reports and
564
+ // bundles attached to that team's repos — for that user's own sidebar Teams section.
565
+ // Any user; only their own memberships.
566
+ listTeamsForUser(userId: string): Promise<UserTeam[]>
567
+ getUserTeamFeedSnapshot(sessionId: string, now: number): Promise<{ user: Pick<StoredUser, 'id' | 'role'>; revision: string; teams: UserTeam[]; catalog: number } | null>
568
+ // Whether `userId` may read `reportId`: true iff the report's repo belongs to
569
+ // a non-hidden team the user is a member of. Backs the team-scoped report view endpoint.
570
+ userCanReadReport(userId: string, reportId: string): Promise<boolean>
571
+ // What viewing `reportId` turns on, in one read: who uploaded it, whether it
572
+ // is published, and whether userCanReadReport; null where there is none.
573
+ getReportView(userId: string, reportId: string): Promise<{ uploadedBy: string | null; visible: boolean; readable: boolean } | null>
574
+ // The viewer's effective visibility permissions for a report, OR'd across the
575
+ // teams (holding the report's repo) the user belongs to — drives the content
576
+ // filter (a viewer without a permission has those findings stripped).
577
+ reportPermissionsFor(userId: string, reportId: string): Promise<TeamUserPermissions>
578
+ setTeamRepo(teamId: string, repoId: number, path: string | null): Promise<void>
579
+ removeTeamRepo(teamId: string, repoId: number, path?: string | null): Promise<boolean>
580
+ setTeamMember(teamId: string, userId: string, perms: TeamUserPermissions): Promise<void>
581
+ removeTeamMember(teamId: string, userId: string): Promise<boolean>
582
+ close(): Promise<void>
583
+ }
584
+
585
+ type SessionRow = {
586
+ id: string; csrf: string; exp: number; uploadKey: string | null
587
+ uid: string; login: string; name: string | null; avatar: string | null; role: Role
588
+ }
589
+ type ViewSessionRow = SessionRow & { viewerId: string; viewerLogin: string; viewerName: string | null }
590
+ const storedUser = (row: Pick<SessionRow, 'uid' | 'login' | 'name' | 'avatar' | 'role'>): StoredUser =>
591
+ ({ id: row.uid, login: row.login, name: row.name, avatarUrl: row.avatar, role: row.role })
592
+ const ownSession = (row: SessionRow) => ({
593
+ session: { id: row.id, userId: row.uid, csrfToken: row.csrf, expiresAt: row.exp, uploadKey: row.uploadKey },
594
+ user: storedUser(row),
595
+ })
596
+ const viewSession = (row: ViewSessionRow) => {
597
+ const { session, user } = ownSession(row)
598
+ return { session: { ...session, viewer: { id: row.viewerId, login: row.viewerLogin, name: row.viewerName } }, user }
599
+ }
600
+
601
+ type UserRow = { id: string; login: string; name: string | null; role: Role; created: number; lastSeen: number | null; lastActivity: number | null }
602
+
603
+ // Whether a write changed any row.
604
+ const anyChanged = (result: { changes: number | bigint }) => Number(result.changes) > 0
605
+
606
+ const REPORT_IN_TEAM_PATH_SQL = withinTeamPath('r.repo_directory')
607
+ const BUNDLE_IN_TEAM_PATH_SQL = withinTeamPath('b.repo_directory')
608
+
609
+ // What a user's team catalog reads (listTeamsForUser), for `user`: a
610
+ // placeholder, or a column of a statement reading it with more. Their teams,
611
+ // `dependencyReview` where the user reviews dependencies in the team
612
+ // (dependency-reviews.ts reviewsIn): one that reviews them, and a member
613
+ // who manages, or triages and may see its dependencies; an admin in any.
614
+ const USER_TEAMS_SQL = (user: string) => `SELECT t.id AS id, t.slug AS slug, t.name AS name,
615
+ CASE WHEN t.dependency_review = 1 AND (u.role IN ('admin', 'manage') OR (u.role = 'triage' AND tu.view_dependencies = 1))
616
+ THEN 1 ELSE 0 END AS dependencyReview,
617
+ tu.view_dependencies AS dependencies, tu.view_security AS security
618
+ FROM managed_team_user tu JOIN managed_team t ON t.id = tu.team_id JOIN managed_user u ON u.id = tu.user_id
619
+ WHERE tu.user_id = ${user} AND t.hidden = 0`
620
+ // Their teams' repository scopes.
621
+ const USER_TEAM_SCOPES_SQL = (user: string) => `SELECT tr.team_id AS teamId, tr.repo_id AS repoId, tr.path AS path, sr.full_name AS fullName
622
+ FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
623
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
624
+ JOIN managed_selected_repo sr ON sr.repo_id = tr.repo_id
625
+ WHERE tu.user_id = ${user}`
626
+ // Reports attached to the repos of their teams, tagged by team (a report
627
+ // shows under every team whose repo it's attached to).
628
+ const USER_TEAM_REPORTS_SQL = (user: string) => `SELECT DISTINCT tr.team_id AS teamId, r.id AS id, r.slug AS slug, r.filename AS filename, r.analyzer, r.visible, r.uploaded_at,
629
+ r.sha256 AS sha256, r.bundle_id AS bundleId, r.repo_id AS repoId, r.repo_directory AS repoDirectory, sr.full_name AS repoFullName,
630
+ r.confirmed_default AS confirmedDefault, tu.view_dependencies AS dependencies, tu.view_security AS security,
631
+ (SELECT role FROM managed_user WHERE id = tu.user_id) AS role
632
+ FROM managed_team_user tu
633
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
634
+ JOIN managed_team_repo tr ON tr.team_id = tu.team_id
635
+ JOIN managed_report r ON r.repo_id = tr.repo_id AND ${REPORT_IN_TEAM_PATH_SQL}
636
+ LEFT JOIN managed_selected_repo sr ON sr.repo_id = r.repo_id
637
+ WHERE tu.user_id = ${user} AND (r.visible = 1 OR (SELECT role FROM managed_user WHERE id = tu.user_id) IN ('admin', 'manage'))`
638
+ // Bundles, scoped through the same team -> repository links as reports.
639
+ // Hidden bundles remain available to managers within their team scopes.
640
+ const USER_TEAM_BUNDLES_SQL = (user: string) => `SELECT DISTINCT tr.team_id AS teamId, b.id AS id, b.slug AS slug, b.integrity AS integrity,
641
+ b.filename AS filename, b.kind, b.visible, b.byte_size AS byteSize, b.repo_id AS repoId, b.repo_directory AS repoDirectory, sr.full_name AS repoFullName, b.uploaded_at, b.provenance
642
+ FROM managed_team_user tu
643
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
644
+ JOIN managed_team_repo tr ON tr.team_id = tu.team_id
645
+ JOIN managed_bundle b ON b.repo_id = tr.repo_id AND ${BUNDLE_IN_TEAM_PATH_SQL}
646
+ JOIN managed_selected_repo sr ON sr.repo_id = b.repo_id
647
+ WHERE tu.user_id = ${user} AND (b.visible = 1 OR (SELECT role FROM managed_user WHERE id = tu.user_id) IN ('admin', 'manage'))`
648
+
649
+ // Whether a repeated upload/build renames the stored row. Uploads never rename
650
+ // a built row, or one whose provenance is unknown; builds rename either. The
651
+ // kind must stay readable from its blob store (sourcemaps are stored apart):
652
+ // keep it, or let an unrecognized archive become Stasis — never downgrade.
653
+ const BUNDLE_RENAMED_SQL = `(:rename = 1 AND (provenance = 'upload' OR (:provenance = 'build' AND provenance IS NULL))
654
+ AND (COALESCE(kind, '') = COALESCE(:kind, '') OR (kind IS NULL AND :kind = 'stasis'))
655
+ AND (filename <> :filename OR kind IS DISTINCT FROM :kind))`
656
+
657
+ // The rows a user's team catalog is built of (USER_TEAMS_SQL and the rest).
658
+ type UserTeamRows = {
659
+ teams: { id: string; slug: string; name: string; dependencyReview: number; dependencies: number; security: number }[]
660
+ scopes: { teamId: string; repoId: number; path: string; fullName: string }[]
661
+ reports: {
662
+ teamId: string; id: string; slug: string; filename: string; analyzer: string | null; sha256: string; bundleId: string | null; repoId: number
663
+ repoDirectory: string; repoFullName: string | null; visible: number; confirmedDefault: number; dependencies: number; security: number; role: string
664
+ }[]
665
+ bundles: (Omit<UserTeamBundle, 'visible'> & { teamId: string; visible: number })[]
666
+ }
667
+
668
+ // A catalog report's content key: its content, where it is, whether it opens
669
+ // on Confirmed, and what its reader may see of it (their grants and role)
670
+ // under the link reports' revision `links`. A team snapshot names it of each
671
+ // report it reads.
672
+ type CatalogReportRow = Pick<UserTeamRows['reports'][number], 'sha256' | 'bundleId' | 'filename' | 'repoId' | 'repoDirectory' | 'repoFullName' | 'confirmedDefault' | 'dependencies' | 'security'>
673
+ function reportCatalogKey(r: CatalogReportRow, role: string, links: string): string {
674
+ return createHash('sha256').update(JSON.stringify([
675
+ r.sha256, r.bundleId, r.filename, r.repoId, r.repoDirectory, r.repoFullName, r.dependencies, r.security, role, links,
676
+ ...r.confirmedDefault === 1 ? ['confirmed'] : [],
677
+ ])).digest('base64url')
678
+ }
679
+
680
+ // A user's team catalog from its rows, `links` the link reports' revision.
681
+ function userTeams(teams: UserTeamRows['teams'], scopes: UserTeamRows['scopes'], links: string, reports: UserTeamRows['reports'], bundles: UserTeamRows['bundles']): UserTeam[] {
682
+ const reportsByTeam = Map.groupBy(reports, r => r.teamId)
683
+ const bundlesByTeam = Map.groupBy(bundles, b => b.teamId)
684
+ return teams.map((t) => {
685
+ const teamScopes = scopes.filter(scope => scope.teamId === t.id)
686
+ return {
687
+ id: t.id, slug: t.slug, name: t.name,
688
+ ...(t.dependencyReview === 1 ? { dependencyReview: true } : {}),
689
+ permissions: { dependencies: t.dependencies === 1, security: t.security === 1 },
690
+ cacheKey: createHash('sha256').update(JSON.stringify([t.dependencies, t.security, links, teamScopes])).digest('base64url'),
691
+ repos: teamScopes.map(scope => ({ repoId: scope.repoId, fullName: scope.fullName, path: scope.path || null }))
692
+ .toSorted((a, b) => a.fullName.localeCompare(b.fullName) || (a.path ?? '').localeCompare(b.path ?? '')),
693
+ reports: (reportsByTeam.get(t.id) ?? []).map(r => ({ id: r.id, slug: r.slug, filename: r.filename, visible: r.visible === 1,
694
+ analyzer: r.analyzer, repoFullName: r.repoFullName, repoDirectory: r.repoDirectory, cacheKey: reportCatalogKey(r, r.role, links) })),
695
+ bundles: (bundlesByTeam.get(t.id) ?? []).map(b => ({ id: b.id, slug: b.slug, integrity: b.integrity, filename: b.filename, visible: b.visible === 1,
696
+ kind: b.kind, byteSize: b.byteSize, repoId: b.repoId, repoDirectory: b.repoDirectory, repoFullName: b.repoFullName, provenance: b.provenance })),
697
+ }
698
+ })
699
+ }
700
+
701
+ // A selected repository's row (RepoRow), and a bundle's (BundleRow) of `b`.
702
+ const REPO_COLUMNS = `repo_id AS repoId, full_name AS fullName, is_private AS priv,
703
+ installation_id AS installId, default_branch AS branch, cached_default_branch AS cachedDefaultBranch, html_url AS htmlUrl,
704
+ added_by AS addedBy, added_at AS addedAt, active AS active`
705
+ const bundleColumns = (b: string) => `${b}.id AS id, ${b}.slug AS slug, ${b}.integrity AS integrity, ${b}.filename AS filename,
706
+ ${b}.kind AS kind, ${b}.byte_size AS byteSize, ${b}.uploaded_by AS uploadedBy, ${b}.repo_id AS repoId, ${b}.repo_directory AS repoDirectory,
707
+ ${b}.visible AS visible, ${b}.uploaded_at AS uploadedAt, ${b}.provenance AS provenance, ${b}.build_conditions AS buildConditions`
708
+
709
+ // What storedUser reads of `u`, a session's user (SessionRow); and a
710
+ // snapshot's `viewer`, the user of the live session `?` at `?` read so.
711
+ const SESSION_USER_COLUMNS = 'u.id AS uid, u.login AS login, u.name AS name, u.avatar_url AS avatar, u.role AS role'
712
+ const VIEWER_SQL = `viewer AS (SELECT ${SESSION_USER_COLUMNS}
713
+ FROM managed_session s JOIN managed_user u ON u.id = s.user_id WHERE s.id = ? AND s.expires_at > ?)`
714
+ // The enabled link reports' rows, as linkRevisionOf reads them.
715
+ const ENABLED_LINKS_SQL = `(SELECT json_group_array(json_object('id', id, 'sha256', sha256) ORDER BY id) FROM managed_link_report WHERE enabled = 1)`
716
+
717
+ // Whether the manager `?` may read `row`, a report or bundle: their own
718
+ // upload, or one a scope of theirs holds. Both placeholders take the user.
719
+ const uploadedOrInScope = (row: string) => `(${row}.uploaded_by = ? OR ${inUserTeamScope('?', row)})`
720
+ // The same, of the user its first placeholder takes too, any row where that
721
+ // is NULL (an admin): its three placeholders as asManager gives them.
722
+ const managerReads = (row: string) => `(? IS NULL OR ${uploadedOrInScope(row)})`
723
+ const asManager = (userId?: string) => [userId ?? null, userId ?? null, userId ?? null]
724
+
725
+ // Whether a scope of a non-hidden team of `user` holding bundle `b` shows
726
+ // them its advisories, in the team `?` (any, where NULL; both placeholders
727
+ // take it).
728
+ const bundleAdvisories = (user: string) => `EXISTS (SELECT 1 FROM managed_team_repo tr
729
+ JOIN managed_team_user tu ON tu.team_id = tr.team_id
730
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
731
+ WHERE tr.repo_id = b.repo_id AND ${BUNDLE_IN_TEAM_PATH_SQL} AND tu.user_id = ${user} AND tu.view_security = 1
732
+ AND (? IS NULL OR tr.team_id = ?))`
733
+
734
+ // Prepare every statement the store uses, returned as a bag the factory
735
+ // destructures — keeps createManagedMethods itself small (one place per query).
736
+ function prepareStatements(db: ManagedSql) {
737
+ return {
738
+ // Identity refreshes preserve roles. Login can separately bootstrap the
739
+ // configured sole No access user within this same writer transaction.
740
+ upsertUserStmt: db.prepare(
741
+ `INSERT INTO managed_user (id, github_user_id, login, name, github_name, avatar_url, role, created_at, updated_at)
742
+ VALUES (?, ?, ?, ?, ?, ?, 'none', ?, ?)
743
+ ON CONFLICT(github_user_id) DO UPDATE SET
744
+ login = excluded.login, github_name = excluded.github_name,
745
+ name = CASE WHEN managed_user.name_link IS NULL THEN excluded.name ELSE managed_user.name END,
746
+ avatar_url = excluded.avatar_url, updated_at = excluded.updated_at`,
747
+ ),
748
+ selectLinkedStmt: db.prepare(`SELECT 1 AS linked FROM managed_github_link WHERE github_user_id = ?`),
749
+ selectUserIdStmt: db.prepare(`SELECT id, role FROM managed_user WHERE github_user_id = ?`),
750
+ promoteInitialAdminStmt: db.prepare(
751
+ `UPDATE managed_user SET role = 'admin' WHERE id = ? AND role = 'none'
752
+ AND NOT EXISTS(SELECT 1 FROM managed_user WHERE id <> ?)`,
753
+ ),
754
+ selectGithubIdStmt: db.prepare(`SELECT github_user_id AS githubId FROM managed_user WHERE id = ?`),
755
+ insertSessionStmt: db.prepare(
756
+ `INSERT INTO managed_session (id, user_id, csrf_token, created_at, expires_at) VALUES (?, ?, ?, ?, ?)`,
757
+ ),
758
+ selectOwnSessionStmt: db.prepare(
759
+ `SELECT s.id AS id, s.csrf_token AS csrf, s.expires_at AS exp, s.upload_key AS uploadKey, ${SESSION_USER_COLUMNS}
760
+ FROM managed_session s
761
+ JOIN managed_user u ON u.id = s.user_id
762
+ WHERE s.id = ? AND s.expires_at > ? AND s.viewer_session IS NULL`,
763
+ ),
764
+ // selectOwnSessionStmt with touchUserSeenStmt in one statement: the user of
765
+ // a live own session seen, and returned with it.
766
+ touchOwnSessionStmt: db.prepare(
767
+ `UPDATE managed_user SET last_seen_at = CASE WHEN last_seen_at IS NULL OR last_seen_at < ? THEN ? ELSE last_seen_at END
768
+ WHERE id = (SELECT user_id FROM managed_session WHERE id = ? AND expires_at > ? AND viewer_session IS NULL)
769
+ RETURNING (SELECT id FROM managed_session WHERE id = ?) AS id, (SELECT csrf_token FROM managed_session WHERE id = ?) AS csrf,
770
+ (SELECT expires_at FROM managed_session WHERE id = ?) AS exp, (SELECT upload_key FROM managed_session WHERE id = ?) AS uploadKey,
771
+ id AS uid, login AS login, name AS name, avatar_url AS avatar, role AS role`,
772
+ ),
773
+ selectViewSessionStmt: db.prepare(
774
+ `SELECT s.id AS id, s.csrf_token AS csrf, s.expires_at AS exp, s.upload_key AS uploadKey, ${SESSION_USER_COLUMNS},
775
+ a.id AS viewerId, a.login AS viewerLogin, a.name AS viewerName
776
+ FROM managed_session s
777
+ JOIN managed_user u ON u.id = s.user_id
778
+ JOIN managed_session p ON p.id = s.viewer_session
779
+ JOIN managed_user a ON a.id = p.user_id
780
+ WHERE s.id = ? AND s.viewer_session = ? AND s.expires_at > ?
781
+ AND p.expires_at > ? AND p.viewer_session IS NULL AND a.role = 'admin'`,
782
+ ),
783
+ deleteOtherViewsStmt: db.prepare(`DELETE FROM managed_session WHERE viewer_session = ? AND id <> ?`),
784
+ insertViewSessionStmt: db.prepare(
785
+ `INSERT INTO managed_session (id, user_id, csrf_token, created_at, expires_at, viewer_session)
786
+ SELECT ?, u.id, ?, ?, p.expires_at, p.id
787
+ FROM managed_session p
788
+ JOIN managed_user a ON a.id = p.user_id
789
+ JOIN managed_user u ON u.id = ?
790
+ WHERE p.id = ? AND p.expires_at > ? AND p.viewer_session IS NULL AND a.role = 'admin' AND u.id <> a.id`,
791
+ ),
792
+ // A former admin's views end with the role, even if it is granted again.
793
+ deleteDemotedViewsStmt: db.prepare(
794
+ `DELETE FROM managed_session WHERE viewer_session IN (SELECT id FROM managed_session WHERE user_id = ?)`,
795
+ ),
796
+ selectUsersStmt: db.prepare(
797
+ `SELECT u.id, u.login, u.name, u.role, u.created_at AS created, u.last_seen_at AS lastSeen,
798
+ (SELECT MAX(at) FROM (
799
+ SELECT MAX(e.at) AS at FROM managed_finding_triage_event e WHERE e.actor_id = u.id
800
+ UNION ALL SELECT MAX(a.at) AS at FROM managed_activity a WHERE a.actor_id = u.id
801
+ UNION ALL SELECT MAX(c.at) AS at FROM managed_finding_comment_event c WHERE c.actor_id = u.id
802
+ ) AS events) AS lastActivity
803
+ FROM managed_user u ORDER BY u.created_at ASC, u.login ASC`,
804
+ ),
805
+ selectUserStmt: db.prepare(`SELECT id, login, name, avatar_url AS avatarUrl, role FROM managed_user WHERE id = ?`),
806
+ touchUserSeenStmt: db.prepare(
807
+ `UPDATE managed_user SET last_seen_at = ? WHERE id = ? AND (last_seen_at IS NULL OR last_seen_at < ?)`,
808
+ ),
809
+ updateRoleStmt: db.prepare(`UPDATE managed_user SET role = ?, updated_at = ? WHERE id = ?`),
810
+ updateTokensStmt: db.prepare(
811
+ `UPDATE managed_user
812
+ SET gh_access_token = ?, gh_refresh_token = ?, gh_token_expires_at = ?, gh_tokens_encrypted = ?, updated_at = ?
813
+ WHERE id = ?`,
814
+ ),
815
+ // A user's GitHub tokens with storage-db.ts storageState's read, in one
816
+ // statement.
817
+ selectTokensStateStmt: db.prepare(
818
+ `SELECT u.id AS userId, u.gh_access_token AS access, u.gh_refresh_token AS refresh, u.gh_token_expires_at AS exp, u.gh_tokens_encrypted AS encrypted,
819
+ e.id AS stateId, ${storageStateColumns('e')}
820
+ FROM (SELECT 1 AS one) AS o
821
+ LEFT JOIN managed_user u ON u.id = ?
822
+ LEFT JOIN managed_storage_encryption e ON e.id = 1`,
823
+ ),
824
+ // Concurrent first requests keep whichever key was stored first.
825
+ ensureUploadKeyStmt: db.prepare(
826
+ `UPDATE managed_session SET upload_key = COALESCE(upload_key, ?) WHERE id = ? RETURNING upload_key AS uploadKey`,
827
+ ),
828
+ deleteSessionStmt: db.prepare(`DELETE FROM managed_session WHERE id = ?`),
829
+ deleteExpiredStmt: db.prepare(`DELETE FROM managed_session WHERE expires_at <= ?`),
830
+ upsertRepoStmt: db.prepare(
831
+ `INSERT INTO managed_selected_repo (repo_id, full_name, is_private, installation_id, default_branch, html_url, added_by, added_at, updated_at, active)
832
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
833
+ ON CONFLICT(repo_id) DO UPDATE SET
834
+ full_name = excluded.full_name, is_private = excluded.is_private,
835
+ installation_id = excluded.installation_id, default_branch = excluded.default_branch,
836
+ html_url = excluded.html_url, updated_at = excluded.updated_at, active = 1`,
837
+ ),
838
+ // Never reactivate or recreate a repo, overwrite another connection, or
839
+ // commit after the administrator's session/role was revoked during GitHub I/O.
840
+ connectRepoInstallationStmt: db.prepare(`UPDATE managed_selected_repo SET installation_id = ?, updated_at = ?
841
+ WHERE repo_id = ? AND full_name = ? AND added_at = ? AND installation_id IS NULL
842
+ AND EXISTS (SELECT 1 FROM managed_session s JOIN managed_user u ON u.id = s.user_id
843
+ WHERE s.id = ? AND s.expires_at > ? AND u.role = 'admin')`),
844
+ cacheRepoDefaultBranchStmt: db.prepare(`UPDATE managed_selected_repo SET cached_default_branch = ?
845
+ WHERE repo_id = ? AND full_name = ? AND added_at = ? AND active = 1`),
846
+ deleteRepoStmt: db.prepare(`DELETE FROM managed_selected_repo WHERE repo_id = ?`),
847
+ deactivateRepoStmt: db.prepare(`UPDATE managed_selected_repo SET active = 0 WHERE repo_id = ? AND active = 1`),
848
+ reactivateRepoStmt: db.prepare(`UPDATE managed_selected_repo SET active = 1 WHERE repo_id = ? AND active = 0`),
849
+ selectReportsForRepoStmt: db.prepare(`SELECT id, filename, sha256, bundle_id AS bundleId FROM managed_report WHERE repo_id = ? ORDER BY filename ASC`),
850
+ selectBundlesForRepoStmt: db.prepare(`SELECT id, filename FROM managed_bundle WHERE repo_id = ? ORDER BY filename ASC`),
851
+ deleteReportsForRepoStmt: db.prepare(`DELETE FROM managed_report WHERE repo_id = ?`),
852
+ deleteBundlesForRepoStmt: db.prepare(`DELETE FROM managed_bundle WHERE repo_id = ?`),
853
+ deleteTriageStmt: db.prepare(`DELETE FROM managed_finding_triage WHERE finding_id IN (SELECT value FROM json_each(?))`),
854
+ deleteTriageHistoryStmt: db.prepare(`DELETE FROM managed_finding_triage_event WHERE finding_id IN (SELECT value FROM json_each(?))`),
855
+ deleteCommentsStmt: db.prepare(`DELETE FROM managed_finding_comment WHERE finding_id IN (SELECT value FROM json_each(?))`),
856
+ deleteCommentHistoryStmt: db.prepare(`DELETE FROM managed_finding_comment_event WHERE finding_id IN (SELECT value FROM json_each(?))`),
857
+ countAnnotationsStmt: db.prepare(`SELECT count(*) AS total FROM (
858
+ SELECT finding_id FROM managed_finding_triage WHERE finding_id IN (SELECT value FROM json_each(?))
859
+ UNION SELECT finding_id FROM managed_finding_comment WHERE finding_id IN (SELECT value FROM json_each(?))
860
+ UNION SELECT finding_id FROM managed_finding_comment_event WHERE finding_id IN (SELECT value FROM json_each(?))) AS annotations`),
861
+ selectReposStmt: db.prepare(`SELECT ${REPO_COLUMNS} FROM managed_selected_repo WHERE active = 1 ORDER BY full_name ASC`),
862
+ selectRepoFullNameStmt: db.prepare(`SELECT full_name AS fullName FROM managed_selected_repo WHERE repo_id = ?`),
863
+ selectAllReposStmt: db.prepare(`SELECT ${REPO_COLUMNS} FROM managed_selected_repo ORDER BY full_name ASC`),
864
+ insertReportStmt: db.prepare(
865
+ `WITH candidate(id, slug) AS (VALUES (?, ?))
866
+ INSERT INTO managed_report (id, slug, filename, content_type, byte_size, sha256, uploaded_by, uploaded_by_login, repo_id, repo_directory, repo_embedded, analyzer, visible, bundle_id, bundle_integrity, uploaded_at, data_key, storage_encrypted, confirmed_offered)
867
+ SELECT id, CASE WHEN EXISTS (SELECT 1 FROM managed_report WHERE slug = candidate.slug) THEN id ELSE slug END,
868
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM candidate`,
869
+ ),
870
+ // LEFT JOINs so a report whose uploader / repo / bundle was removed (the FK
871
+ // nulled) still lists, with null display fields.
872
+ selectReportsStmt: db.prepare(
873
+ `SELECT r.id AS id, r.slug AS slug, r.filename AS filename, r.content_type AS contentType,
874
+ r.byte_size AS byteSize, r.sha256 AS sha256, COALESCE(u.login, r.uploaded_by_login) AS uploadedByLogin,
875
+ r.repo_id AS repoId, sr.full_name AS repoFullName,
876
+ r.repo_directory AS repoDirectory, r.repo_embedded AS repoEmbedded,
877
+ r.analyzer AS analyzer, r.visible AS visible,
878
+ r.bundle_id AS bundleId, b.filename AS bundleFilename, r.bundle_integrity AS bundleIntegrity,
879
+ r.uploaded_at AS uploadedAt, r.confirmed_offered AS confirmedOffered, r.confirmed_default AS confirmedDefault
880
+ FROM managed_report r
881
+ LEFT JOIN managed_user u ON u.id = r.uploaded_by
882
+ LEFT JOIN managed_selected_repo sr ON sr.repo_id = r.repo_id
883
+ LEFT JOIN managed_bundle b ON b.id = r.bundle_id
884
+ WHERE ${managerReads('r')}
885
+ ORDER BY r.uploaded_at DESC, r.filename ASC`,
886
+ ),
887
+ findingCatalogReportsStmt: db.prepare(`SELECT id, byte_size AS byteSize FROM managed_report WHERE id > ? ORDER BY id LIMIT ?`),
888
+ selectReportStmt: db.prepare(
889
+ `SELECT id, slug, filename, content_type AS contentType, byte_size AS byteSize,
890
+ sha256, uploaded_by AS uploadedBy, uploaded_at AS uploadedAt,
891
+ repo_id AS repoId, repo_directory AS repoDirectory, repo_embedded AS repoEmbedded,
892
+ analyzer AS analyzer, visible AS visible, bundle_id AS bundleId,
893
+ confirmed_offered AS confirmedOffered, confirmed_default AS confirmedDefault
894
+ FROM managed_report WHERE id = ?`,
895
+ ),
896
+ selectReportByHashStmt: db.prepare(
897
+ `SELECT id FROM managed_report WHERE sha256 = ? AND COALESCE(analyzer, '') = COALESCE(?, '')
898
+ ORDER BY uploaded_at, id LIMIT 1`,
899
+ ),
900
+ // A report access snapshot's reads in one statement, so one snapshot of
901
+ // the database answers them all: the session's user; those of the
902
+ // requested reports (a JSON array of ids) they may read, each with the
903
+ // grants their teams give them (a JSON array); and the enabled link
904
+ // reports (linkRevision).
905
+ selectReportSnapshotStmt: db.prepare(
906
+ `WITH ${VIEWER_SQL}, requested AS (SELECT value AS id FROM json_each(?)), report_grants AS (
907
+ SELECT r.id AS id, MAX(tu.view_dependencies) AS dependencies, MAX(tu.view_security) AS security
908
+ FROM managed_report r JOIN requested q ON q.id = r.id
909
+ JOIN managed_team_repo tr ON tr.repo_id = r.repo_id AND ${REPORT_IN_TEAM_PATH_SQL}
910
+ JOIN managed_team_user tu ON tu.team_id = tr.team_id AND tu.user_id = (SELECT uid FROM viewer)
911
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
912
+ GROUP BY r.id
913
+ )
914
+ SELECT v.uid AS uid, v.login AS login, v.name AS name, v.avatar AS avatar, v.role AS role,
915
+ (SELECT json_group_array(json_object('id', r.id, 'filename', r.filename, 'byteSize', r.byte_size, 'sha256', r.sha256,
916
+ 'repoDirectory', r.repo_directory, 'repoFullName', sr.full_name,
917
+ 'dependencies', COALESCE(g.dependencies, 0), 'security', COALESCE(g.security, 0)) ORDER BY r.id)
918
+ FROM managed_report r JOIN requested q ON q.id = r.id
919
+ LEFT JOIN managed_selected_repo sr ON sr.repo_id = r.repo_id
920
+ LEFT JOIN report_grants g ON g.id = r.id
921
+ WHERE v.role = 'admin' OR (v.role = 'manage' AND r.uploaded_by = v.uid)
922
+ OR (g.id IS NOT NULL AND (v.role = 'manage' OR r.visible = 1))) AS reports,
923
+ ${ENABLED_LINKS_SQL} AS links
924
+ FROM viewer v`,
925
+ ),
926
+ // A team snapshot's reads in one statement, so one snapshot of the
927
+ // database answers them all: the session's user; whether they see the
928
+ // team; the team's visible reports in the scopes it grants them, with the
929
+ // grants, and the hidden one asked for where their role may preview it;
930
+ // the team's repositories (each a JSON array); and the enabled link
931
+ // reports (linkRevision).
932
+ selectTeamSnapshotStmt: db.prepare(
933
+ `WITH ${VIEWER_SQL}
934
+ SELECT v.uid AS uid, v.login AS login, v.name AS name, v.avatar AS avatar, v.role AS role,
935
+ EXISTS(SELECT 1 FROM managed_team_user tu JOIN managed_team t ON t.id = tu.team_id
936
+ WHERE tu.user_id = v.uid AND tu.team_id = ? AND t.hidden = 0) AS member,
937
+ (SELECT json_group_array(json_object('id', x.id, 'filename', x.filename, 'byteSize', x.byteSize, 'sha256', x.sha256,
938
+ 'visible', x.visible, 'bundleId', x.bundleId, 'repoId', x.repoId, 'repoDirectory', x.repoDirectory, 'repoFullName', x.repoFullName,
939
+ 'confirmedDefault', x.confirmedDefault, 'dependencies', x.dependencies, 'security', x.security) ORDER BY x.id)
940
+ FROM (SELECT DISTINCT r.id AS id, r.filename AS filename, r.byte_size AS byteSize, r.sha256 AS sha256, r.visible AS visible,
941
+ r.bundle_id AS bundleId, r.repo_id AS repoId, r.repo_directory AS repoDirectory, sr.full_name AS repoFullName,
942
+ r.confirmed_default AS confirmedDefault,
943
+ tu.view_dependencies AS dependencies, tu.view_security AS security
944
+ FROM managed_team_user tu
945
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
946
+ JOIN managed_team_repo tr ON tr.team_id = tu.team_id
947
+ JOIN managed_report r ON r.repo_id = tr.repo_id AND ${REPORT_IN_TEAM_PATH_SQL}
948
+ LEFT JOIN managed_selected_repo sr ON sr.repo_id = r.repo_id
949
+ WHERE tu.user_id = v.uid AND tu.team_id = ? AND (r.visible = 1 OR (v.role IN ('admin', 'manage') AND r.id = ?))) AS x) AS reports,
950
+ (SELECT json_group_array(json_object('repoId', tr.repo_id, 'github', sr.full_name, 'path', tr.path) ORDER BY tr.repo_id, tr.path)
951
+ FROM managed_team_repo tr JOIN managed_selected_repo sr ON sr.repo_id = tr.repo_id
952
+ WHERE tr.team_id = ?) AS repositories,
953
+ ${ENABLED_LINKS_SQL} AS links
954
+ FROM viewer v`,
955
+ ),
956
+ reportFilenamesWithBundleHashStmt: db.prepare(`SELECT DISTINCT filename FROM managed_report WHERE bundle_id = ? AND sha256 = ?`),
957
+ reportsForBundleStmt: db.prepare(
958
+ `SELECT r.id AS id, r.filename AS filename, r.bundle_id AS bundleId,
959
+ ${managerReads('r')} AS readable
960
+ FROM managed_report r WHERE r.bundle_id = ? OR r.bundle_integrity = ?
961
+ ORDER BY r.uploaded_at DESC, r.filename ASC, r.id ASC`,
962
+ ),
963
+ deleteReportStmt: db.prepare(`DELETE FROM managed_report WHERE id = ?`),
964
+ setReportRepoStmt: db.prepare(`UPDATE managed_report SET repo_id = ?, repo_directory = ? WHERE id = ?`),
965
+ setReportVisibleStmt: db.prepare(`UPDATE managed_report SET visible = ? WHERE id = ?`),
966
+ setReportConfirmedDefaultStmt: db.prepare(`UPDATE managed_report SET confirmed_default = ? WHERE id = ? AND confirmed_default <> ?`),
967
+ setReportsConfirmedOfferedStmt: db.prepare(`UPDATE managed_report SET confirmed_offered = ?
968
+ WHERE confirmed_offered IS NULL AND id IN (SELECT value FROM json_each(?))`),
969
+ upsertTriageStmt: db.prepare(
970
+ `INSERT INTO managed_finding_triage (finding_id, color, triage, comment, fix, flagged, updated_by, updated_by_login, updated_at)
971
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
972
+ ON CONFLICT(finding_id) DO UPDATE SET
973
+ color = excluded.color, triage = excluded.triage, comment = excluded.comment,
974
+ fix = excluded.fix, flagged = excluded.flagged, updated_by = excluded.updated_by,
975
+ updated_by_login = excluded.updated_by_login, updated_at = excluded.updated_at`,
976
+ ),
977
+ selectTriageStateStmt: db.prepare(
978
+ `SELECT color, triage, comment, fix, flagged FROM managed_finding_triage WHERE finding_id = ?`,
979
+ ),
980
+ insertTriageEventStmt: db.prepare(
981
+ `INSERT INTO managed_finding_triage_event (finding_id, batch_id, color, triage, comment, fix, flagged, actor_id, actor_login, at, report_id, report, repo)
982
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
983
+ (SELECT filename FROM managed_report WHERE id = ?),
984
+ (SELECT p.full_name FROM managed_report r JOIN managed_selected_repo p ON p.repo_id = r.repo_id WHERE r.id = ?))`,
985
+ ),
986
+ // With a retention limit set: keep the newest N events of a finding.
987
+ trimTriageEventsStmt: db.prepare(
988
+ `DELETE FROM managed_finding_triage_event
989
+ WHERE finding_id = ?
990
+ AND seq NOT IN (SELECT seq FROM managed_finding_triage_event WHERE finding_id = ? ORDER BY seq DESC LIMIT ?)`,
991
+ ),
992
+ selectTriageHistoryStmt: db.prepare(
993
+ `SELECT e.seq AS seq, e.finding_id AS findingId, e.batch_id AS batchId, e.color AS color, e.triage AS triage,
994
+ e.comment AS comment, e.fix AS fix, e.flagged AS flagged,
995
+ u.id AS actorId, COALESCE(u.login, e.actor_login) AS actorLogin, u.name AS actorName, e.at AS at
996
+ FROM managed_finding_triage_event e
997
+ LEFT JOIN managed_user u ON u.id = e.actor_id
998
+ WHERE e.finding_id = ?
999
+ ORDER BY e.seq DESC
1000
+ LIMIT ?`,
1001
+ ),
1002
+ // The ids arrive as one JSON array (json_each), so a report's worth of
1003
+ // them is one statement, not a chunked IN list. COALESCE the live login
1004
+ // over the durable snapshot, like selectReportsStmt.
1005
+ selectTriageStmt: db.prepare(
1006
+ `SELECT t.finding_id AS findingId, t.color AS color, t.triage AS triage,
1007
+ t.comment AS comment, t.fix AS fix, t.flagged AS flagged,
1008
+ COALESCE(u.login, t.updated_by_login) AS updatedByLogin, t.updated_at AS updatedAt
1009
+ FROM managed_finding_triage t
1010
+ LEFT JOIN managed_user u ON u.id = t.updated_by
1011
+ WHERE t.finding_id IN (SELECT value FROM json_each(?))
1012
+ ORDER BY t.finding_id ASC`,
1013
+ ),
1014
+ // A set of findings' triage (selectTriageStmt), comments (comments.ts
1015
+ // listComments) and issues (managed-issues.ts listManagedIssues), each
1016
+ // a JSON array of the rows those read, in their order, from one snapshot.
1017
+ selectAnnotationsStmt: db.prepare(
1018
+ `WITH requested AS (SELECT value AS id FROM json_each(?))
1019
+ SELECT (SELECT json_group_array(json_object('findingId', t.finding_id, 'color', t.color, 'triage', t.triage, 'comment', t.comment,
1020
+ 'fix', t.fix, 'flagged', t.flagged, 'updatedByLogin', COALESCE(u.login, t.updated_by_login), 'updatedAt', t.updated_at)
1021
+ ORDER BY t.finding_id ASC)
1022
+ FROM managed_finding_triage t LEFT JOIN managed_user u ON u.id = t.updated_by
1023
+ WHERE t.finding_id IN (SELECT id FROM requested)) AS triage,
1024
+ (SELECT json_group_array(json_object('id', c.id, 'findingId', c.finding_id, 'body', c.body, 'authorId', c.author_id,
1025
+ 'authorLogin', COALESCE(u.login, c.author_login), 'authorName', u.name,
1026
+ 'createdAt', c.created_at, 'updatedAt', c.updated_at, 'version', c.version)
1027
+ ORDER BY c.created_at NULLS FIRST, c.id)
1028
+ FROM managed_finding_comment c LEFT JOIN managed_user u ON u.id = c.author_id
1029
+ WHERE c.finding_id IN (SELECT id FROM requested)) AS comments,
1030
+ (SELECT json_group_array(json_object('findingId', i.finding_id, 'repoId', i.repo_id, 'repository', i.repository, 'requestId', i.request_id,
1031
+ 'issueUrl', i.issue_url, 'autoFixUrl', i.auto_fix_url, 'autoFixCheckedAt', i.auto_fix_checked_at,
1032
+ 'duplicateOfUrl', i.duplicate_of_url, 'createdBy', i.created_by, 'createdAt', i.created_at) ORDER BY i.finding_id)
1033
+ FROM managed_finding_issue i WHERE i.finding_id IN (SELECT id FROM requested)) AS issues`,
1034
+ ),
1035
+ selectTriageFixesStmt: db.prepare(`SELECT DISTINCT fix FROM managed_finding_triage
1036
+ WHERE finding_id IN (SELECT value FROM json_each(?)) AND fix IS NOT NULL ORDER BY fix`),
1037
+ // Each finding's latest triage batch, comment versions and linked issues,
1038
+ // in one statement.
1039
+ annotationRevisionStmt: db.prepare(
1040
+ `WITH requested AS (SELECT value AS id FROM json_each(?))
1041
+ SELECT (SELECT json_group_array(json_object('id', t.finding_id, 'revision', (SELECT e.batch_id FROM managed_finding_triage_event e
1042
+ WHERE e.finding_id = t.finding_id ORDER BY e.seq DESC LIMIT 1)) ORDER BY t.finding_id)
1043
+ FROM managed_finding_triage t WHERE t.finding_id IN (SELECT id FROM requested)) AS triage,
1044
+ (SELECT json_group_array(json_object('id', c.id, 'version', c.version) ORDER BY c.id)
1045
+ FROM managed_finding_comment c WHERE c.finding_id IN (SELECT id FROM requested)) AS comments,
1046
+ (SELECT json_group_array(json_object('findingId', i.finding_id, 'issueUrl', i.issue_url, 'autoFixUrl', i.auto_fix_url,
1047
+ 'duplicateOfUrl', i.duplicate_of_url) ORDER BY i.finding_id)
1048
+ FROM managed_finding_issue i WHERE i.finding_id IN (SELECT id FROM requested) AND i.issue_url IS NOT NULL) AS issues`,
1049
+ ),
1050
+ insertBundleStmt: db.prepare(
1051
+ `WITH candidate(id, slug) AS (VALUES (?, ?))
1052
+ INSERT INTO managed_bundle (id, slug, integrity, filename, kind, byte_size, uploaded_by, uploaded_by_login, repo_id, repo_directory, visible, uploaded_at, data_key, storage_encrypted, provenance, build_conditions)
1053
+ SELECT id, CASE WHEN EXISTS (SELECT 1 FROM managed_bundle WHERE slug = candidate.slug) THEN id ELSE slug END,
1054
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM candidate`,
1055
+ ),
1056
+ // SET reads the pre-update row. Unchanged rows match nothing, so identical
1057
+ // retries do not bump the catalog revision. Conditions that rebuild the same
1058
+ // bytes describe them equally, so the first recorded ones stay.
1059
+ reuseBundleStmt: db.prepare(
1060
+ `UPDATE managed_bundle SET
1061
+ filename = CASE WHEN ${BUNDLE_RENAMED_SQL} THEN :filename ELSE filename END,
1062
+ kind = CASE WHEN ${BUNDLE_RENAMED_SQL} THEN :kind ELSE kind END,
1063
+ provenance = CASE WHEN :provenance = 'build' THEN 'build' ELSE provenance END,
1064
+ build_conditions = CASE WHEN :provenance = 'build' THEN COALESCE(build_conditions, :buildConditions) ELSE build_conditions END
1065
+ WHERE id = :id AND (${BUNDLE_RENAMED_SQL} OR (:provenance = 'build' AND (provenance IS DISTINCT FROM 'build'
1066
+ OR build_conditions IS DISTINCT FROM COALESCE(build_conditions, :buildConditions))))`,
1067
+ ),
1068
+ selectBundleByIntegrityStmt: db.prepare(`SELECT ${bundleColumns('b')} FROM managed_bundle b WHERE b.integrity = ?`),
1069
+ selectBundleStmt: db.prepare(`SELECT ${bundleColumns('b')} FROM managed_bundle b WHERE b.id = ?`),
1070
+ selectBundlesStmt: db.prepare(
1071
+ `SELECT b.id AS id, b.slug AS slug, b.integrity AS integrity, b.filename AS filename, b.kind AS kind,
1072
+ b.byte_size AS byteSize, COALESCE(u.login, b.uploaded_by_login) AS uploadedByLogin,
1073
+ b.repo_id AS repoId, b.repo_directory AS repoDirectory, b.visible, sr.full_name AS repoFullName, b.uploaded_at AS uploadedAt, b.provenance
1074
+ FROM managed_bundle b
1075
+ LEFT JOIN managed_user u ON u.id = b.uploaded_by
1076
+ LEFT JOIN managed_selected_repo sr ON sr.repo_id = b.repo_id
1077
+ WHERE ${managerReads('b')}
1078
+ ORDER BY b.uploaded_at DESC, b.filename ASC`,
1079
+ ),
1080
+ selectBundleReadableStmt: db.prepare(
1081
+ `SELECT 1 FROM managed_bundle b WHERE b.id = ? AND ${uploadedOrInScope('b')}`,
1082
+ ),
1083
+ selectReadableBundleIdsStmt: db.prepare(
1084
+ `SELECT b.id FROM managed_bundle b WHERE b.id IN (SELECT value FROM json_each(?)) AND ${uploadedOrInScope('b')}`,
1085
+ ),
1086
+ selectRepoReadableStmt: db.prepare(
1087
+ `SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
1088
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1089
+ WHERE tr.repo_id = ? AND tu.user_id = ? LIMIT 1`,
1090
+ ),
1091
+ selectRepoPathReadableStmt: db.prepare(
1092
+ `WITH r(repo_directory) AS (VALUES (?))
1093
+ SELECT 1 FROM r JOIN managed_team_repo tr ON tr.repo_id = ? AND ${REPORT_IN_TEAM_PATH_SQL}
1094
+ JOIN managed_team_user tu ON tu.team_id = tr.team_id
1095
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1096
+ WHERE tu.user_id = ? LIMIT 1`,
1097
+ ),
1098
+ deleteBundleStmt: db.prepare(`DELETE FROM managed_bundle WHERE id = ?`),
1099
+ setBundleRepoStmt: db.prepare(`UPDATE managed_bundle SET repo_id = ?, repo_directory = ? WHERE id = ?`),
1100
+ setBundleVisibleStmt: db.prepare(`UPDATE managed_bundle SET visible = ? WHERE id = ?`),
1101
+ // Attach a freshly-stored bundle to the reports that declared its integrity
1102
+ // but haven't been linked yet (bundle uploaded after the report).
1103
+ linkReportsToBundleStmt: db.prepare(
1104
+ `UPDATE managed_report AS r SET bundle_id = ? WHERE bundle_integrity = ? AND bundle_id IS NULL
1105
+ AND ${managerReads('r')}`,
1106
+ ),
1107
+ // OR IGNORE: a duplicate name (UNIQUE) is the "taken" signal (0 changes); the
1108
+ // uuid PK never collides.
1109
+ insertTeamStmt: db.prepare(`WITH candidate(id, slug) AS (VALUES (?, ?))
1110
+ INSERT OR IGNORE INTO managed_team (id, slug, name, created_at, updated_at)
1111
+ SELECT id, CASE WHEN EXISTS (SELECT 1 FROM managed_team WHERE slug = candidate.slug) THEN id ELSE slug END,
1112
+ ?, ?, ? FROM candidate`),
1113
+ deleteTeamStmt: db.prepare(`DELETE FROM managed_team WHERE id = ?`),
1114
+ selectTeamStmt: db.prepare(`SELECT id, slug, name, hidden FROM managed_team WHERE id = ?`),
1115
+ selectTeamByNameStmt: db.prepare(`SELECT id FROM managed_team WHERE name = ?`),
1116
+ renameTeamStmt: db.prepare(`UPDATE managed_team SET name = ?, updated_at = ? WHERE id = ?`),
1117
+ setTeamHiddenStmt: db.prepare(`UPDATE managed_team SET hidden = ?, updated_at = ? WHERE id = ?`),
1118
+ selectTeamsStmt: db.prepare(`SELECT id, slug, name, hidden FROM managed_team ORDER BY name ASC`),
1119
+ selectTeamsForUserStmt: db.prepare(`${USER_TEAMS_SQL('?')} ORDER BY t.name ASC, t.id ASC`),
1120
+ selectUserTeamScopesStmt: db.prepare(`${USER_TEAM_SCOPES_SQL('?')} ORDER BY tr.team_id, tr.repo_id, tr.path`),
1121
+ selectUserTeamReportsStmt: db.prepare(`${USER_TEAM_REPORTS_SQL('?')} ORDER BY r.uploaded_at DESC, r.filename ASC, r.id ASC`),
1122
+ selectUserTeamBundlesStmt: db.prepare(`${USER_TEAM_BUNDLES_SQL('?')} ORDER BY b.uploaded_at DESC, b.filename ASC, b.id ASC`),
1123
+ // getUserTeamFeedSnapshot's reads in one statement, so one snapshot of the
1124
+ // database answers them all: the session's user and the change revisions
1125
+ // (getFeedState), and listTeamsForUser's lists, each a JSON array in the
1126
+ // order those statements read it.
1127
+ selectUserTeamFeedStmt: db.prepare(
1128
+ `WITH viewer AS (
1129
+ SELECT u.id AS id, u.role AS role, r.catalog AS catalog, r.annotations AS annotations
1130
+ FROM managed_session s JOIN managed_user u ON u.id = s.user_id JOIN managed_change_revision r ON r.id = 1
1131
+ WHERE s.id = ? AND s.expires_at > ?
1132
+ )
1133
+ SELECT v.id AS id, v.role AS role, v.catalog AS catalog, v.annotations AS annotations,
1134
+ (SELECT json_group_array(json_object('id', x.id, 'slug', x.slug, 'name', x.name, 'dependencyReview', x.dependencyReview,
1135
+ 'dependencies', x.dependencies, 'security', x.security) ORDER BY x.name ASC, x.id ASC)
1136
+ FROM (${USER_TEAMS_SQL('v.id')}) AS x) AS teams,
1137
+ (SELECT json_group_array(json_object('teamId', x.teamId, 'repoId', x.repoId, 'path', x.path, 'fullName', x.fullName)
1138
+ ORDER BY x.teamId, x.repoId, x.path)
1139
+ FROM (${USER_TEAM_SCOPES_SQL('v.id')}) AS x) AS scopes,
1140
+ ${ENABLED_LINKS_SQL} AS links,
1141
+ (SELECT json_group_array(json_object('teamId', x.teamId, 'id', x.id, 'slug', x.slug, 'filename', x.filename, 'analyzer', x.analyzer,
1142
+ 'visible', x.visible, 'sha256', x.sha256, 'bundleId', x.bundleId, 'repoId', x.repoId, 'repoDirectory', x.repoDirectory,
1143
+ 'repoFullName', x.repoFullName, 'confirmedDefault', x.confirmedDefault, 'dependencies', x.dependencies, 'security', x.security, 'role', x.role)
1144
+ ORDER BY x.uploaded_at DESC, x.filename ASC, x.id ASC)
1145
+ FROM (${USER_TEAM_REPORTS_SQL('v.id')}) AS x) AS reports,
1146
+ (SELECT json_group_array(json_object('teamId', x.teamId, 'id', x.id, 'slug', x.slug, 'integrity', x.integrity, 'filename', x.filename,
1147
+ 'kind', x.kind, 'visible', x.visible, 'byteSize', x.byteSize, 'repoId', x.repoId, 'repoDirectory', x.repoDirectory,
1148
+ 'repoFullName', x.repoFullName, 'provenance', x.provenance)
1149
+ ORDER BY x.uploaded_at DESC, x.filename ASC, x.id ASC)
1150
+ FROM (${USER_TEAM_BUNDLES_SQL('v.id')}) AS x) AS bundles
1151
+ FROM viewer v`,
1152
+ ),
1153
+ selectUserRepoScopesStmt: db.prepare(
1154
+ `SELECT DISTINCT tr.repo_id AS repoId, NULLIF(tr.path, '') AS path
1155
+ FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
1156
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1157
+ WHERE tu.user_id = ?`,
1158
+ ),
1159
+ // A report is readable iff one of the user's team scopes contains it.
1160
+ selectReportReadableStmt: db.prepare(`SELECT 1 FROM managed_report r WHERE r.id = ? AND ${inUserTeamScope('?', 'r')}`),
1161
+ selectReportViewStmt: db.prepare(
1162
+ `SELECT r.uploaded_by AS uploadedBy, r.visible AS visible, ${inUserTeamScope('?', 'r')} AS readable
1163
+ FROM managed_report r WHERE r.id = ?`,
1164
+ ),
1165
+ selectBundleSecurityStmt: db.prepare(`SELECT 1 FROM managed_bundle b WHERE b.id = ? AND ${bundleAdvisories('?')}`),
1166
+ // A bundle access snapshot's reads in one statement, so one snapshot of
1167
+ // the database answers them all: the session's user, view sessions
1168
+ // included; the bundle, NULL where there is none; whether one of the
1169
+ // user's team scopes contains it, the grant both selectBundleReadableStmt
1170
+ // (a manager's, beside their own uploads) and selectRepoPathReadableStmt
1171
+ // (a reader's, of its repository directory) ask for; and, where the flag
1172
+ // asks, whether one in the team (any, where NULL) shows them its
1173
+ // advisories (selectBundleSecurityStmt).
1174
+ selectBundleAccessStmt: db.prepare(
1175
+ `WITH ${VIEWER_SQL}
1176
+ SELECT v.uid AS uid, v.role AS role, ${bundleColumns('b')},
1177
+ ${inUserTeamScope('v.uid', 'b')} AS granted, (? = 1 AND ${bundleAdvisories('v.uid')}) AS security
1178
+ FROM viewer v LEFT JOIN managed_bundle b ON b.id = ?`,
1179
+ ),
1180
+ // The viewer's effective visibility permissions for a report: OR'd (MAX over
1181
+ // 0/1) across memberships whose repository path contains the report. NULLs
1182
+ // (no such membership) read as 0 = no permission.
1183
+ selectReportPermsStmt: db.prepare(
1184
+ `SELECT MAX(tu.view_dependencies) AS dependencies, MAX(tu.view_security) AS security
1185
+ FROM managed_report r
1186
+ JOIN managed_team_repo tr ON tr.repo_id = r.repo_id AND ${REPORT_IN_TEAM_PATH_SQL}
1187
+ JOIN managed_team_user tu ON tu.team_id = tr.team_id AND tu.user_id = ?
1188
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1189
+ WHERE r.id = ?`,
1190
+ ),
1191
+ selectUserOptionsStmt: db.prepare(`SELECT id, login, name, role FROM managed_user ORDER BY login ASC`),
1192
+ selectTeamReposStmt: db.prepare(
1193
+ `SELECT tr.team_id AS teamId, tr.repo_id AS repoId, sr.full_name AS fullName, NULLIF(tr.path, '') AS path
1194
+ FROM managed_team_repo tr JOIN managed_selected_repo sr ON sr.repo_id = tr.repo_id
1195
+ ORDER BY sr.full_name ASC, tr.path ASC`,
1196
+ ),
1197
+ selectTeamMembersStmt: db.prepare(
1198
+ `SELECT tu.team_id AS teamId, tu.user_id AS userId, u.login AS login,
1199
+ tu.view_dependencies AS viewDependencies, tu.view_security AS viewSecurity
1200
+ FROM managed_team_user tu JOIN managed_user u ON u.id = tu.user_id
1201
+ ORDER BY u.login ASC`,
1202
+ ),
1203
+ upsertTeamRepoStmt: db.prepare(
1204
+ `INSERT OR IGNORE INTO managed_team_repo (team_id, repo_id, path)
1205
+ SELECT ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM managed_team_repo WHERE team_id = ? AND repo_id = ? AND path = '')`,
1206
+ ),
1207
+ deleteTeamRepoStmt: db.prepare(`DELETE FROM managed_team_repo WHERE team_id = ? AND repo_id = ?`),
1208
+ deleteTeamRepoPathStmt: db.prepare(`DELETE FROM managed_team_repo WHERE team_id = ? AND repo_id = ? AND path = ?`),
1209
+ upsertTeamMemberStmt: db.prepare(
1210
+ `INSERT INTO managed_team_user (team_id, user_id, view_dependencies, view_security) VALUES (?, ?, ?, ?)
1211
+ ON CONFLICT(team_id, user_id) DO UPDATE SET
1212
+ view_dependencies = excluded.view_dependencies, view_security = excluded.view_security`,
1213
+ ),
1214
+ deleteTeamMemberStmt: db.prepare(`DELETE FROM managed_team_user WHERE team_id = ? AND user_id = ?`),
1215
+ }
1216
+ }
1217
+
1218
+ type RepoRow = {
1219
+ repoId: number; fullName: string; priv: number; installId: number | null
1220
+ branch: string; cachedDefaultBranch: string | null; htmlUrl: string; addedBy: string | null; addedAt: number; active: number
1221
+ }
1222
+
1223
+ // The repo-selection slice of ManagedDb, split out to keep createManagedMethods
1224
+ // within the per-function line budget. Closes over its prepared statements.
1225
+ function selectedRepoMethods(stmts: ReturnType<typeof prepareStatements>) {
1226
+ const { upsertRepoStmt, deleteRepoStmt, deactivateRepoStmt, reactivateRepoStmt, selectReposStmt, selectAllReposStmt,
1227
+ selectReportsForRepoStmt, selectBundlesForRepoStmt, deleteReportsForRepoStmt, deleteBundlesForRepoStmt } = stmts
1228
+ const readRepo = (r: RepoRow): SelectedRepo => ({
1229
+ repoId: r.repoId, fullName: r.fullName, private: r.priv === 1,
1230
+ installationId: r.installId, defaultBranch: r.branch, cachedDefaultBranch: r.cachedDefaultBranch, htmlUrl: r.htmlUrl,
1231
+ addedBy: r.addedBy, addedAt: r.addedAt,
1232
+ })
1233
+ const readManagedRepo = (r: RepoRow): ManagedRepo => ({ ...readRepo(r), active: r.active === 1 })
1234
+ return {
1235
+ async selectRepo(repo: SelectedRepoInput, now: number): Promise<void> {
1236
+ await upsertRepoStmt.run(
1237
+ repo.repoId, repo.fullName, repo.private ? 1 : 0, repo.installationId,
1238
+ repo.defaultBranch, repo.htmlUrl, repo.addedBy, now, now,
1239
+ )
1240
+ },
1241
+ async cacheRepoDefaultBranch(repo: SelectedRepo, branch: string | null): Promise<boolean> {
1242
+ return anyChanged(await stmts.cacheRepoDefaultBranchStmt.run(branch, repo.repoId, repo.fullName, repo.addedAt))
1243
+ },
1244
+ async deselectRepo(repoId: number): Promise<boolean> {
1245
+ return anyChanged(await deleteRepoStmt.run(repoId))
1246
+ },
1247
+ async connectRepoInstallation(repo: SelectedRepo, installationId: number, sessionId: string, now: number): Promise<boolean> {
1248
+ return anyChanged(await stmts.connectRepoInstallationStmt.run(installationId, now, repo.repoId, repo.fullName, repo.addedAt, sessionId, now))
1249
+ },
1250
+ async listSelectedRepos(): Promise<SelectedRepo[]> {
1251
+ const rows = (await selectReposStmt.all()) as RepoRow[]
1252
+ return rows.map(readRepo)
1253
+ },
1254
+ async listAllRepos(): Promise<ManagedRepo[]> {
1255
+ const rows = (await selectAllReposStmt.all()) as RepoRow[]
1256
+ return rows.map(readManagedRepo)
1257
+ },
1258
+ async getRepoFullName(repoId: number): Promise<string | null> {
1259
+ return ((await stmts.selectRepoFullNameStmt.get(repoId)) as { fullName: string } | undefined)?.fullName ?? null
1260
+ },
1261
+ async deactivateRepo(repoId: number): Promise<boolean> {
1262
+ return anyChanged(await deactivateRepoStmt.run(repoId))
1263
+ },
1264
+ async reactivateRepo(repoId: number): Promise<boolean> {
1265
+ return anyChanged(await reactivateRepoStmt.run(repoId))
1266
+ },
1267
+ async deleteRepo(repoId: number): Promise<boolean> {
1268
+ return anyChanged(await deleteRepoStmt.run(repoId))
1269
+ },
1270
+ async listReportsForRepo(repoId: number): Promise<RepoReportItem[]> {
1271
+ return (await selectReportsForRepoStmt.all(repoId)) as unknown as RepoReportItem[]
1272
+ },
1273
+ async listBundlesForRepo(repoId: number): Promise<RepoDataItem[]> {
1274
+ return (await selectBundlesForRepoStmt.all(repoId)) as unknown as RepoDataItem[]
1275
+ },
1276
+ async deleteReportsForRepo(repoId: number): Promise<number> {
1277
+ return Number((await deleteReportsForRepoStmt.run(repoId)).changes)
1278
+ },
1279
+ async deleteBundlesForRepo(repoId: number): Promise<number> {
1280
+ return Number((await deleteBundlesForRepoStmt.run(repoId)).changes)
1281
+ },
1282
+ }
1283
+ }
1284
+
1285
+ type ReportListRow = {
1286
+ id: string; slug: string; filename: string; contentType: string; byteSize: number
1287
+ sha256: string; uploadedByLogin: string | null
1288
+ repoId: number | null; repoFullName: string | null
1289
+ repoDirectory: string; repoEmbedded: number; analyzer: string | null; visible: number
1290
+ bundleId: string | null; bundleFilename: string | null; bundleIntegrity: string | null
1291
+ uploadedAt: number; confirmedOffered: number | null; confirmedDefault: number
1292
+ }
1293
+ type ReportRow = {
1294
+ id: string; slug: string; filename: string; contentType: string; byteSize: number
1295
+ sha256: string; uploadedBy: string | null; uploadedAt: number
1296
+ repoId: number | null; repoDirectory: string; repoEmbedded: number; analyzer: string | null; visible: number
1297
+ bundleId: string | null; confirmedOffered: number | null; confirmedDefault: number
1298
+ }
1299
+ // Its opening's columns as a report gives them.
1300
+ const reportOpening = (row: { confirmedOffered: number | null; confirmedDefault: number }) =>
1301
+ ({ confirmedOffered: row.confirmedOffered == null ? null : row.confirmedOffered === 1, confirmedDefault: row.confirmedDefault === 1 })
1302
+
1303
+ // A report as an access snapshot read it, and as the snapshot gives it: with
1304
+ // every permission where the reader's role sees `whole` reports.
1305
+ type AccessRow = Pick<ReportAccessRecord, 'id' | 'filename' | 'byteSize' | 'sha256'> & {
1306
+ repoDirectory: string; repoFullName: string | null; dependencies: number; security: number; confirmedDefault?: number
1307
+ }
1308
+ const accessRecord = (row: AccessRow, whole: boolean): ReportAccessRecord => ({
1309
+ id: row.id, filename: row.filename, byteSize: row.byteSize, sha256: row.sha256,
1310
+ repo: { github: row.repoFullName, directory: row.repoDirectory },
1311
+ permissions: { dependencies: whole || row.dependencies === 1, security: whole || row.security === 1 },
1312
+ ...row.confirmedDefault === 1 ? { confirmedDefault: true as const } : {},
1313
+ })
1314
+
1315
+ // Byte storage may outlast a logout or grant change. HTTP uploads reauthorize
1316
+ // inside the metadata writer transaction after their bytes have been stored.
1317
+ async function authorizeUpload(stmts: ReturnType<typeof prepareStatements>, sessionId: string | undefined,
1318
+ item: { uploadedBy: string | null; repoId: number | null; repoDirectory?: string }) {
1319
+ if (sessionId === undefined) return // Trusted imports and fixtures use the raw store API.
1320
+ const user = await stmts.selectOwnSessionStmt.get(sessionId, Date.now()) as SessionRow | undefined
1321
+ if (!user) throw new ManagedMutationError(401, 'unauthenticated')
1322
+ if (user.uid !== item.uploadedBy || !roleAtLeast(user.role, 'manage')) throw new ManagedMutationError(403, 'forbidden')
1323
+ if (item.repoId === null) return
1324
+ if (!(await stmts.selectReposStmt.all() as RepoRow[]).some(repo => repo.repoId === item.repoId)) throw new ManagedMutationError(400, 'repo-not-selected')
1325
+ if (user.role !== 'admin' && !await stmts.selectRepoPathReadableStmt.get(item.repoDirectory ?? '', item.repoId, user.uid)) throw new ManagedMutationError(403, 'repo-forbidden')
1326
+ }
1327
+
1328
+ // The report slice of ManagedDb closes over its prepared statements.
1329
+ function reportMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql, key: StorageKey | null) {
1330
+ const { insertReportStmt, selectReportsStmt, selectReportStmt, deleteReportStmt, setReportRepoStmt, setReportVisibleStmt } = stmts
1331
+ async function getReport(id: string): Promise<ReportRecord | null> {
1332
+ const row = (await selectReportStmt.get(id)) as ReportRow | undefined
1333
+ if (row == null) return null
1334
+ return { ...row, repoEmbedded: row.repoEmbedded === 1, visible: row.visible === 1, ...reportOpening(row) }
1335
+ }
1336
+ async function getReportByHash(sha256: string, analyzer: string | null): Promise<ReportRecord | null> {
1337
+ const row = await stmts.selectReportByHashStmt.get(sha256, analyzer) as { id: string } | undefined
1338
+ return row ? getReport(row.id) : null
1339
+ }
1340
+ async function insertReport(report: ReportRecordInput, now: number): Promise<void> {
1341
+ await validateStorageUpload(db, key, 'report', report.id, report.dataKey)
1342
+ await insertReportStmt.run(
1343
+ report.id, preferredSlug(report.id), report.filename, report.contentType, report.byteSize,
1344
+ report.sha256, report.uploadedBy, report.uploadedByLogin ?? null, report.repoId,
1345
+ report.repoDirectory ?? '', report.repoEmbedded ? 1 : 0, report.analyzer ?? null, report.visible ? 1 : 0, report.bundleId ?? null,
1346
+ report.bundleIntegrity ?? null, now, report.dataKey ?? null, report.dataKey ? 1 : 0,
1347
+ report.confirmedOffered == null ? null : report.confirmedOffered ? 1 : 0,
1348
+ )
1349
+ }
1350
+ return {
1351
+ insertReport,
1352
+ getReport,
1353
+ resolveReportUpload: getReport,
1354
+ getReportByHash,
1355
+ async insertOrReuseReport(report: ReportRecordInput, now: number, sessionId?: string): Promise<ReportRecord> {
1356
+ await authorizeUpload(stmts, sessionId, report)
1357
+ // The driver holds its writer lock for this whole operation. Checking
1358
+ // again here closes the race between the HTTP lookup and blob upload.
1359
+ const existing = await getReportByHash(report.sha256, report.analyzer ?? null)
1360
+ if (existing) return existing
1361
+ await insertReport(report, now)
1362
+ return (await getReport(report.id))!
1363
+ },
1364
+ async listReports(userId?: string): Promise<AdminReport[]> {
1365
+ const rows = (await selectReportsStmt.all(...asManager(userId))) as ReportListRow[]
1366
+ return rows.map(r => ({ ...r, repoEmbedded: r.repoEmbedded === 1, visible: r.visible === 1, ...reportOpening(r) }))
1367
+ },
1368
+ async listFindingCatalogReports(after: string, limit: number): Promise<Pick<ReportRecord, 'id' | 'byteSize'>[]> {
1369
+ return await stmts.findingCatalogReportsStmt.all(after, limit) as Pick<ReportRecord, 'id' | 'byteSize'>[]
1370
+ },
1371
+ async getTeamReportAccessSnapshot(sessionId: string, now: number, teamId: string, reportId: string | null = null): Promise<TeamReportAccessSnapshot | null> {
1372
+ const session = await stmts.selectTeamSnapshotStmt.get(sessionId, now, teamId, teamId, reportId, teamId) as
1373
+ SessionRow & { member: unknown; reports: unknown; repositories: unknown; links: unknown } | undefined
1374
+ if (!session) return null
1375
+ const user = storedUser(session)
1376
+ if (user.role === 'none' || !session.member) return { user, teamId: null, reports: [], repositories: [] }
1377
+ const whole = roleAtLeast(user.role, 'manage')
1378
+ const rows = jsonRows<CatalogReportRow & { id: string; byteSize: number; visible: number }>(session.reports)
1379
+ // Only privileged callers can receive a hidden row from this query. Give
1380
+ // that individual preview its own capacity; published report selections
1381
+ // still use the complete workspace for cross-report classification.
1382
+ const hidden = rows.find(row => row.id === reportId && row.visible === 0)
1383
+ const selected = hidden ? [hidden] : rows
1384
+ const repositories = jsonRows<TeamReportAccessSnapshot['repositories'][number]>(session.repositories)
1385
+ const links = linkRevisionOf(jsonRows(session.links))
1386
+ return { user, teamId, reportId, hiddenReportId: hidden?.id ?? null, repositories, linkRevision: links,
1387
+ reports: selected.map(row => accessRecord(row, whole)),
1388
+ catalogKeys: Object.fromEntries(selected.map(row => [row.id, reportCatalogKey(row, user.role, links)])) }
1389
+ },
1390
+ async getReportAccessSnapshot(sessionId: string, now: number, ids: readonly string[]): Promise<ReportAccessSnapshot | null> {
1391
+ const session = await stmts.selectReportSnapshotStmt.get(sessionId, now, JSON.stringify([...new Set(ids)])) as
1392
+ SessionRow & { reports: unknown; links: unknown } | undefined
1393
+ if (!session) return null
1394
+ const user = storedUser(session)
1395
+ if (user.role === 'none' || ids.length === 0) return { user, reports: [] }
1396
+ const whole = roleAtLeast(user.role, 'manage')
1397
+ const reports = jsonRows<AccessRow>(session.reports).map(row => accessRecord(row, whole))
1398
+ return { user, linkRevision: linkRevisionOf(jsonRows(session.links)), reports }
1399
+ },
1400
+ async listReportFilenamesWithBundleHash(bundleId: string, sha256: string): Promise<string[]> {
1401
+ const rows = (await stmts.reportFilenamesWithBundleHashStmt.all(bundleId, sha256)) as { filename: string }[]
1402
+ return rows.map(row => row.filename)
1403
+ },
1404
+ async listReportsForBundle(bundleId: string, integrity: string, userId?: string): Promise<BundleReportItem[]> {
1405
+ const rows = await stmts.reportsForBundleStmt.all(...asManager(userId), bundleId, integrity) as
1406
+ (Omit<BundleReportItem, 'readable'> & { readable: unknown })[]
1407
+ return rows.map(row => ({ id: row.id, filename: row.filename, bundleId: row.bundleId, readable: Boolean(row.readable) }))
1408
+ },
1409
+ async deleteReport(id: string): Promise<boolean> {
1410
+ return anyChanged(await deleteReportStmt.run(id))
1411
+ },
1412
+ async setReportRepo(id: string, repoId: number | null, repoDirectory = ''): Promise<boolean> {
1413
+ return anyChanged(await setReportRepoStmt.run(repoId, repoId == null ? '' : repoDirectory, id))
1414
+ },
1415
+ async setReportVisible(id: string, visible: boolean): Promise<boolean> {
1416
+ return anyChanged(await setReportVisibleStmt.run(visible ? 1 : 0, id))
1417
+ },
1418
+ async setReportConfirmedDefault(id: string, on: boolean): Promise<boolean> {
1419
+ return anyChanged(await stmts.setReportConfirmedDefaultStmt.run(on ? 1 : 0, id, on ? 1 : 0))
1420
+ },
1421
+ async setReportsConfirmedOffered(read: readonly { id: string; offered: boolean }[]): Promise<void> {
1422
+ for (const offered of [true, false]) {
1423
+ const ids = read.filter(entry => entry.offered === offered).map(entry => entry.id)
1424
+ if (ids.length > 0) await stmts.setReportsConfirmedOfferedStmt.run(offered ? 1 : 0, JSON.stringify(ids))
1425
+ }
1426
+ },
1427
+ }
1428
+ }
1429
+
1430
+ type TriageDbRow = {
1431
+ findingId: string; color: string | null; triage: string | null
1432
+ comment: string | null; fix: string | null; flagged: number | null
1433
+ updatedByLogin: string | null; updatedAt: number
1434
+ }
1435
+ const triageRow = (r: TriageDbRow): TriageRow => ({ ...r, flagged: r.flagged == null ? null : r.flagged === 1 })
1436
+ type TriageStateDbRow = { color: string | null; triage: string | null; comment: string | null; fix: string | null; flagged: number | null }
1437
+ // An entry as its row stores it. `flagged: false` is a real value (the
1438
+ // explicit un-flag tombstone), so it is 0 here and only null/absent maps to NULL.
1439
+ function triageState(entry: TriageEntryPatch | null): TriageStateDbRow {
1440
+ const e = entry ?? {}
1441
+ return { color: e.color ?? null, triage: e.triage ?? null, comment: e.comment ?? null,
1442
+ fix: e.fix ?? null, flagged: e.flagged == null ? null : (e.flagged ? 1 : 0) }
1443
+ }
1444
+ const sameTriageState = (a: TriageStateDbRow, b: TriageStateDbRow) =>
1445
+ a.color === b.color && a.triage === b.triage && a.comment === b.comment && a.fix === b.fix && a.flagged === b.flagged
1446
+ type TriageEventDbRow = TriageStateDbRow & {
1447
+ seq: number; findingId: string; batchId: string; actorId: string | null; actorLogin: string | null; actorName: string | null; at: number
1448
+ }
1449
+
1450
+ // The per-finding triage slice of ManagedDb. Closes over its prepared
1451
+ // statements (and the handle, for the batch write's transaction). A
1452
+ // null/empty entry writes the tombstone — every field NULL, writer and time
1453
+ // stamped — so a later reader learns the entry was cleared rather than never
1454
+ // set. Every change is also appended to the trail; a write equal to the
1455
+ // current row is skipped altogether, so a client re-pushing what already
1456
+ // stands neither re-stamps the writer nor echoes into the trail. `historyLimit`
1457
+ // > 0 keeps only that many events per finding; 0 keeps everything.
1458
+ function triageMethods(stmts: ReturnType<typeof prepareStatements>, historyLimit: number, db: ManagedSql) {
1459
+ const { upsertTriageStmt, selectTriageStmt, selectTriageStateStmt, insertTriageEventStmt, trimTriageEventsStmt, selectTriageHistoryStmt,
1460
+ deleteTriageStmt, deleteTriageHistoryStmt, deleteCommentsStmt, deleteCommentHistoryStmt, countAnnotationsStmt } = stmts
1461
+ async function writeEntry(findingId: string, entry: TriageEntryPatch | null, batchId: string, updatedBy: string | null, updatedByLogin: string | null, now: number, reportId: string | null = null): Promise<void> {
1462
+ const next = triageState(entry)
1463
+ const cur = (await selectTriageStateStmt.get(findingId)) as TriageStateDbRow | undefined
1464
+ if (cur != null && sameTriageState(cur, next)) return
1465
+ await upsertTriageStmt.run(findingId, next.color, next.triage, next.comment, next.fix, next.flagged, updatedBy, updatedByLogin, now)
1466
+ await insertTriageEventStmt.run(findingId, batchId, next.color, next.triage, next.comment, next.fix, next.flagged, updatedBy, updatedByLogin, now, reportId, reportId, reportId)
1467
+ if (historyLimit > 0) await trimTriageEventsStmt.run(findingId, findingId, historyLimit)
1468
+ }
1469
+ return {
1470
+ async getAnnotationRevision(findingIds: readonly string[]): Promise<string> {
1471
+ if (findingIds.length === 0) return '[]'
1472
+ // Batch UUIDs survive history trimming and distinguish same-timestamp
1473
+ // writes, even if SQLite reuses a sequence after an annotation purge.
1474
+ const row = await stmts.annotationRevisionStmt.get(JSON.stringify(findingIds)) as { triage: unknown; comments: unknown; issues: unknown }
1475
+ return JSON.stringify([jsonRows(row.triage), jsonRows(row.comments), jsonRows(row.issues)])
1476
+ },
1477
+ async deleteTriage(findingIds: readonly string[]): Promise<number> {
1478
+ if (findingIds.length === 0) return 0
1479
+ const ids = JSON.stringify(findingIds)
1480
+ const { total: deleted } = (await countAnnotationsStmt.get(ids, ids, ids)) as { total: number }
1481
+ await deleteTriageStmt.run(ids)
1482
+ await deleteTriageHistoryStmt.run(ids)
1483
+ await deleteCommentsStmt.run(ids)
1484
+ await deleteCommentHistoryStmt.run(ids)
1485
+ return deleted
1486
+ },
1487
+ async listTriageHistory(findingId: string, limit: number): Promise<TriageEventRow[]> {
1488
+ const rows = (await selectTriageHistoryStmt.all(findingId, limit)) as TriageEventDbRow[]
1489
+ return rows.map(r => ({ ...r, flagged: r.flagged == null ? null : r.flagged === 1 }))
1490
+ },
1491
+ async listTriageFixes(findingIds: readonly string[]): Promise<string[]> {
1492
+ if (findingIds.length === 0) return []
1493
+ return ((await stmts.selectTriageFixesStmt.all(JSON.stringify(findingIds))) as { fix: string }[]).map(row => row.fix)
1494
+ },
1495
+ async listTriage(findingIds: readonly string[]): Promise<TriageRow[]> {
1496
+ if (findingIds.length === 0) return []
1497
+ return ((await selectTriageStmt.all(JSON.stringify(findingIds))) as TriageDbRow[]).map(triageRow)
1498
+ },
1499
+ async setTriage(findingId: string, entry: TriageEntryPatch | null, updatedBy: string | null, updatedByLogin: string | null, now: number): Promise<void> {
1500
+ // A single write is its own batch. The row and its event go together.
1501
+ await writeEntry(findingId, entry, randomUUID(), updatedBy, updatedByLogin, now)
1502
+ },
1503
+ async setTriageEntries(entries: readonly (readonly [string, TriageEntryPatch | null])[], updatedBy: string | null, updatedByLogin: string | null, now: number, reportId?: string): Promise<void> {
1504
+ // One transaction, so a batch is never half-applied by a mid-loop error
1505
+ // (and costs one fsync under synchronous = FULL, not one per row); one
1506
+ // batch id groups its rows in the trail.
1507
+ const batchId = randomUUID()
1508
+ if (new Set(entries.map(([id]) => id)).size !== entries.length) {
1509
+ // Preserve the ordered history of callers that supply repeated IDs.
1510
+ for (const [id, entry] of entries) await writeEntry(id, entry, batchId, updatedBy, updatedByLogin, now, reportId)
1511
+ return
1512
+ }
1513
+ const current = new Map((await selectTriageStmt.all(JSON.stringify(entries.map(([id]) => id))) as TriageDbRow[])
1514
+ .map(row => [row.findingId, row]))
1515
+ const changed = entries.flatMap(([id, entry]) => {
1516
+ const next = triageState(entry), previous = current.get(id)
1517
+ if (previous && sameTriageState(previous, next)) return []
1518
+ return [[id, next.color, next.triage, next.comment, next.fix, next.flagged]]
1519
+ })
1520
+ // Bound SQL parameters while keeping the entire batch/history atomic.
1521
+ for (let offset = 0; offset < changed.length; offset += 200) {
1522
+ const rows = changed.slice(offset, offset + 200), values = rows.flat()
1523
+ const input = `WITH changes(finding_id, color, triage, comment, fix, flagged, ordinal) AS
1524
+ (VALUES ${rows.map((_, index) => `(?, ?, ?, ?, ?, CAST(? AS INTEGER), ${index})`).join(',')})`
1525
+ await db.prepare(`${input}
1526
+ INSERT INTO managed_finding_triage (finding_id, color, triage, comment, fix, flagged, updated_by, updated_by_login, updated_at)
1527
+ SELECT finding_id, color, triage, comment, fix, flagged, ?, ?, CAST(? AS BIGINT) FROM changes WHERE TRUE
1528
+ ON CONFLICT(finding_id) DO UPDATE SET color = excluded.color, triage = excluded.triage,
1529
+ comment = excluded.comment, fix = excluded.fix, flagged = excluded.flagged, updated_by = excluded.updated_by,
1530
+ updated_by_login = excluded.updated_by_login, updated_at = excluded.updated_at`).run(...values, updatedBy, updatedByLogin, now)
1531
+ await db.prepare(`${input}
1532
+ INSERT INTO managed_finding_triage_event (finding_id, batch_id, color, triage, comment, fix, flagged, actor_id, actor_login, at, report_id, report, repo)
1533
+ SELECT c.finding_id, ?, c.color, c.triage, c.comment, c.fix, c.flagged, ?, ?, CAST(? AS BIGINT), ?, r.filename, p.full_name
1534
+ FROM changes c LEFT JOIN managed_report r ON r.id = ? LEFT JOIN managed_selected_repo p ON p.repo_id = r.repo_id ORDER BY c.ordinal`)
1535
+ .run(...values, batchId, updatedBy, updatedByLogin, now, reportId ?? null, reportId ?? null)
1536
+ if (historyLimit > 0) {
1537
+ await db.prepare(`DELETE FROM managed_finding_triage_event WHERE seq IN (
1538
+ SELECT seq FROM (SELECT seq, ROW_NUMBER() OVER (PARTITION BY finding_id ORDER BY seq DESC) AS position
1539
+ FROM managed_finding_triage_event WHERE finding_id IN (SELECT value FROM json_each(?))) ranked WHERE position > ?)`)
1540
+ .run(JSON.stringify(rows.map(row => row[0])), historyLimit)
1541
+ }
1542
+ }
1543
+ },
1544
+ }
1545
+ }
1546
+
1547
+ type BundleRow = {
1548
+ visible: number
1549
+ id: string; slug: string; integrity: string; filename: string; kind: string | null; byteSize: number
1550
+ uploadedBy: string | null; repoId: number | null; repoDirectory: string; uploadedAt: number; provenance: BundleProvenance | null
1551
+ buildConditions: string | null
1552
+ }
1553
+ type BundleListRow = {
1554
+ visible: number
1555
+ id: string; slug: string; integrity: string; filename: string; kind: string | null; byteSize: number
1556
+ uploadedByLogin: string | null; repoId: number | null; repoFullName: string | null; repoDirectory: string; uploadedAt: number
1557
+ provenance: BundleProvenance | null
1558
+ }
1559
+
1560
+ function mapBundle(r: BundleRow): ManagedBundle {
1561
+ return {
1562
+ id: r.id, slug: r.slug, integrity: r.integrity, filename: r.filename, kind: r.kind,
1563
+ byteSize: r.byteSize, uploadedBy: r.uploadedBy, repoId: r.repoId, repoDirectory: r.repoDirectory, uploadedAt: r.uploadedAt, visible: r.visible === 1,
1564
+ provenance: r.provenance, buildConditions: r.buildConditions == null ? null : JSON.parse(r.buildConditions) as BundleBuildConditions,
1565
+ }
1566
+ }
1567
+
1568
+ // The bundle slice of ManagedDb. Closes over its prepared statements.
1569
+ function bundleMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql, key: StorageKey | null) {
1570
+ const {
1571
+ insertBundleStmt, selectBundleByIntegrityStmt, selectBundleStmt,
1572
+ selectBundlesStmt, deleteBundleStmt, setBundleRepoStmt, linkReportsToBundleStmt, selectBundleReadableStmt, selectRepoReadableStmt, selectRepoPathReadableStmt,
1573
+ } = stmts
1574
+ async function getBundleByIntegrity(integrity: string): Promise<ManagedBundle | null> {
1575
+ const row = (await selectBundleByIntegrityStmt.get(integrity)) as BundleRow | undefined
1576
+ return row == null ? null : mapBundle(row)
1577
+ }
1578
+ return {
1579
+ async insertBundle(bundle: BundleInput, now: number, sessionId?: string): Promise<void> {
1580
+ await authorizeUpload(stmts, sessionId, bundle)
1581
+ await validateStorageUpload(db, key, 'bundle', bundle.id, bundle.dataKey)
1582
+ await insertBundleStmt.run(
1583
+ bundle.id, preferredSlug(bundle.id), bundle.integrity, bundle.filename, bundle.kind,
1584
+ bundle.byteSize, bundle.uploadedBy, bundle.uploadedByLogin ?? null, bundle.repoId, bundle.repoId == null ? '' : bundle.repoDirectory ?? '', bundle.visible === false ? 0 : 1, now, bundle.dataKey ?? null, bundle.dataKey ? 1 : 0,
1585
+ bundle.provenance ?? null, bundle.buildConditions == null ? null : JSON.stringify(bundle.buildConditions),
1586
+ )
1587
+ },
1588
+ async reuseBundle(id: string, { provenance, filename, kind, rename, buildConditions }: BundleReuse): Promise<boolean> {
1589
+ return anyChanged(await stmts.reuseBundleStmt.run({ id, provenance, filename, kind, rename: rename ? 1 : 0,
1590
+ buildConditions: buildConditions == null ? null : JSON.stringify(buildConditions) }))
1591
+ },
1592
+ getBundleByIntegrity,
1593
+ // The distinct method name selects a writer-locked reconciliation scope.
1594
+ resolveBundleUpload: getBundleByIntegrity,
1595
+ async getBundle(id: string): Promise<ManagedBundle | null> {
1596
+ const row = (await selectBundleStmt.get(id)) as BundleRow | undefined
1597
+ return row == null ? null : mapBundle(row)
1598
+ },
1599
+ async getBundleAccessSnapshot(sessionId: string, now: number, id: string, advisoriesTeamId?: string | null) {
1600
+ // One statement, shared by SQLite and Postgres; the advisories grant is
1601
+ // read only where a team (or null, any) is passed.
1602
+ const team = advisoriesTeamId ?? null
1603
+ const row = await stmts.selectBundleAccessStmt.get(sessionId, now, advisoriesTeamId === undefined ? 0 : 1, team, team, id) as
1604
+ { uid: string; role: Role; granted: unknown; security: unknown } & (BundleRow | { id: null }) | undefined
1605
+ if (!row) return null
1606
+ const denied = { bundle: null, canReadAdvisories: false }
1607
+ if (!roleAtLeast(row.role, 'view') || row.id === null) return denied
1608
+ const manager = roleAtLeast(row.role, 'manage')
1609
+ if (!manager && row.visible !== 1) return denied
1610
+ // Admins read every bundle, managers their own uploads too.
1611
+ if (row.role !== 'admin' && !(row.granted || (manager && row.uploadedBy === row.uid))) return denied
1612
+ return { bundle: mapBundle(row), canReadAdvisories: manager || Boolean(row.security) }
1613
+ },
1614
+ async listBundles(userId?: string): Promise<AdminBundle[]> {
1615
+ const rows = (await selectBundlesStmt.all(...asManager(userId))) as BundleListRow[]
1616
+ return rows.map((r) => ({
1617
+ id: r.id, slug: r.slug, integrity: r.integrity, filename: r.filename, kind: r.kind, byteSize: r.byteSize,
1618
+ uploadedByLogin: r.uploadedByLogin, repoId: r.repoId, repoFullName: r.repoFullName, repoDirectory: r.repoDirectory, visible: r.visible === 1,
1619
+ uploadedAt: r.uploadedAt, provenance: r.provenance,
1620
+ }))
1621
+ },
1622
+ async userCanReadBundle(userId: string, id: string): Promise<boolean> {
1623
+ return (await selectBundleReadableStmt.get(id, userId, userId)) != null
1624
+ },
1625
+ async listReadableBundleIds(userId: string, ids: readonly string[]): Promise<string[]> {
1626
+ if (ids.length === 0) return []
1627
+ const rows = await stmts.selectReadableBundleIdsStmt.all(JSON.stringify([...new Set(ids)]), userId, userId) as { id: string }[]
1628
+ return rows.map(row => row.id)
1629
+ },
1630
+ async userCanReadRepo(userId: string, repoId: number): Promise<boolean> {
1631
+ return (await selectRepoReadableStmt.get(repoId, userId)) != null
1632
+ },
1633
+ async userCanReadRepoPath(userId: string, repoId: number, directory: string): Promise<boolean> {
1634
+ return (await selectRepoPathReadableStmt.get(directory, repoId, userId)) != null
1635
+ },
1636
+ async deleteBundle(id: string): Promise<boolean> {
1637
+ return anyChanged(await deleteBundleStmt.run(id))
1638
+ },
1639
+ async setBundleVisible(id: string, visible: boolean): Promise<boolean> {
1640
+ return anyChanged(await stmts.setBundleVisibleStmt.run(visible ? 1 : 0, id))
1641
+ },
1642
+ async setBundleRepo(id: string, repoId: number | null, directory?: string): Promise<boolean> {
1643
+ return anyChanged(await setBundleRepoStmt.run(repoId, repoId == null ? '' : directory ?? '', id))
1644
+ },
1645
+ async linkReportsToBundle(integrity: string, bundleId: string, userId?: string): Promise<void> {
1646
+ await linkReportsToBundleStmt.run(bundleId, integrity, ...asManager(userId))
1647
+ },
1648
+ }
1649
+ }
1650
+
1651
+ type TeamRow = { id: string; slug: string; name: string; hidden: number }
1652
+ type TeamRepoRow = { teamId: string; repoId: number; fullName: string; path: string | null }
1653
+ type TeamMemberRow = { teamId: string; userId: string; login: string; viewDependencies: number; viewSecurity: number }
1654
+
1655
+ // The team slice of ManagedDb. listTeams reads the three tables in full and
1656
+ // groups in JS (3 queries, not N+1) — fine for the handful of teams a managed
1657
+ // workspace has.
1658
+ function teamMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql) {
1659
+ const {
1660
+ insertTeamStmt, selectTeamByNameStmt, renameTeamStmt, setTeamHiddenStmt, deleteTeamStmt, selectTeamStmt,
1661
+ selectUserRepoScopesStmt, selectTeamsStmt, selectTeamsForUserStmt, selectUserTeamReportsStmt, selectUserTeamBundlesStmt, selectReportReadableStmt,
1662
+ selectReportPermsStmt, selectUserOptionsStmt, selectTeamReposStmt, selectTeamMembersStmt,
1663
+ upsertTeamRepoStmt, deleteTeamRepoStmt, deleteTeamRepoPathStmt, upsertTeamMemberStmt, deleteTeamMemberStmt,
1664
+ } = stmts
1665
+ return {
1666
+ async createTeam(id: string, name: string, now: number): Promise<boolean> {
1667
+ return anyChanged(await insertTeamStmt.run(id, preferredSlug(id), name, now, now))
1668
+ },
1669
+ async renameTeam(id: string, name: string, now: number): Promise<'ok' | 'name-taken' | 'not-found'> {
1670
+ // The operation transaction serializes the existence/name checks and rename.
1671
+ if ((await selectTeamStmt.get(id)) == null) return 'not-found'
1672
+ const clash = (await selectTeamByNameStmt.get(name)) as { id: string } | undefined
1673
+ if (clash != null && clash.id !== id) return 'name-taken'
1674
+ await renameTeamStmt.run(name, now, id)
1675
+ return 'ok'
1676
+ },
1677
+ async deleteTeam(id: string): Promise<boolean> {
1678
+ return anyChanged(await deleteTeamStmt.run(id))
1679
+ },
1680
+ async setTeamHidden(id: string, hidden: boolean, now: number): Promise<boolean> {
1681
+ return anyChanged(await setTeamHiddenStmt.run(hidden ? 1 : 0, now, id))
1682
+ },
1683
+ async getTeam(id: string): Promise<{ id: string; slug: string; name: string; hidden: boolean } | null> {
1684
+ const row = (await selectTeamStmt.get(id)) as TeamRow | undefined
1685
+ return row == null ? null : { id: row.id, slug: row.slug, name: row.name, hidden: row.hidden === 1 }
1686
+ },
1687
+ async listUserOptions(): Promise<UserOption[]> {
1688
+ return ((await selectUserOptionsStmt.all()) as UserOption[]).map((u) => ({ id: u.id, login: u.login, name: u.name, role: u.role }))
1689
+ },
1690
+ async listRepoScopesForUser(userId: string): Promise<{ repoId: number; path: string | null }[]> {
1691
+ return (await selectUserRepoScopesStmt.all(userId)) as { repoId: number; path: string | null }[]
1692
+ },
1693
+ async listTeamsForUser(userId: string): Promise<UserTeam[]> {
1694
+ return userTeams(await selectTeamsForUserStmt.all(userId) as UserTeamRows['teams'], await stmts.selectUserTeamScopesStmt.all(userId) as UserTeamRows['scopes'],
1695
+ await linkRevision(db), await selectUserTeamReportsStmt.all(userId) as UserTeamRows['reports'], await selectUserTeamBundlesStmt.all(userId) as UserTeamRows['bundles'])
1696
+ },
1697
+ async getFeedState(sessionId: string, now: number) {
1698
+ const row = await db.prepare(`SELECT u.id, u.role, r.catalog, r.annotations FROM managed_session s
1699
+ JOIN managed_user u ON u.id = s.user_id JOIN managed_change_revision r ON r.id = 1
1700
+ WHERE s.id = ? AND s.expires_at > ?`).get(sessionId, now) as { id: string; role: Role; catalog: number; annotations: number } | undefined
1701
+ return row ? { user: { id: row.id, role: row.role }, catalog: row.catalog, annotations: row.annotations } : null
1702
+ },
1703
+ async getUserTeamFeedSnapshot(sessionId: string, now: number) {
1704
+ // One statement, shared by SQLite and Postgres. Never touch last-seen
1705
+ // timestamps or include other users' memberships.
1706
+ const row = await stmts.selectUserTeamFeedStmt.get(sessionId, now) as {
1707
+ id: string; role: Role; catalog: number; annotations: number; teams: unknown; scopes: unknown; links: unknown; reports: unknown; bundles: unknown
1708
+ } | undefined
1709
+ if (!row) return null
1710
+ const teams = row.role === 'none' ? [] : userTeams(jsonRows(row.teams), jsonRows(row.scopes), linkRevisionOf(jsonRows(row.links)), jsonRows(row.reports), jsonRows(row.bundles))
1711
+ return { user: { id: row.id, role: row.role }, catalog: row.catalog, teams, revision: teamCatalogRevision(teams) }
1712
+ },
1713
+ async userCanReadReport(userId: string, reportId: string): Promise<boolean> {
1714
+ return (await selectReportReadableStmt.get(reportId, userId)) != null
1715
+ },
1716
+ async getReportView(userId: string, reportId: string) {
1717
+ const row = await stmts.selectReportViewStmt.get(userId, reportId) as { uploadedBy: string | null; visible: number; readable: unknown } | undefined
1718
+ return row ? { uploadedBy: row.uploadedBy, visible: row.visible === 1, readable: Boolean(row.readable) } : null
1719
+ },
1720
+ async userCanReadBundleAdvisories(userId: string, bundleId: string, teamId: string | null): Promise<boolean> {
1721
+ return (await stmts.selectBundleSecurityStmt.get(bundleId, userId, teamId, teamId)) != null
1722
+ },
1723
+ async reportPermissionsFor(userId: string, reportId: string): Promise<TeamUserPermissions> {
1724
+ const row = (await selectReportPermsStmt.get(userId, reportId)) as { dependencies: number | null; security: number | null } | undefined
1725
+ return { dependencies: row?.dependencies === 1, security: row?.security === 1 }
1726
+ },
1727
+ async listTeams(): Promise<AdminTeam[]> {
1728
+ const teams = (await selectTeamsStmt.all()) as TeamRow[]
1729
+ const reposByTeam = Map.groupBy((await selectTeamReposStmt.all()) as TeamRepoRow[], r => r.teamId)
1730
+ const membersByTeam = Map.groupBy((await selectTeamMembersStmt.all()) as TeamMemberRow[], m => m.teamId)
1731
+ return teams.map((t) => ({
1732
+ id: t.id, slug: t.slug, name: t.name,
1733
+ hidden: t.hidden === 1,
1734
+ repos: (reposByTeam.get(t.id) ?? []).map(r => ({ repoId: r.repoId, fullName: r.fullName, path: r.path })),
1735
+ members: (membersByTeam.get(t.id) ?? []).map(m => ({ userId: m.userId, login: m.login,
1736
+ dependencies: m.viewDependencies === 1, security: m.viewSecurity === 1 })),
1737
+ }))
1738
+ },
1739
+ async setTeamRepo(teamId: string, repoId: number, path: string | null): Promise<void> {
1740
+ // A whole-repository grant supersedes all its path grants atomically.
1741
+ // Adding a redundant path to an existing whole-repo grant is a no-op.
1742
+ if (path == null || path === '') await deleteTeamRepoStmt.run(teamId, repoId)
1743
+ await upsertTeamRepoStmt.run(teamId, repoId, path ?? '', teamId, repoId)
1744
+ },
1745
+ async removeTeamRepo(teamId: string, repoId: number, path?: string | null): Promise<boolean> {
1746
+ const result = path === undefined ? (await deleteTeamRepoStmt.run(teamId, repoId)) : (await deleteTeamRepoPathStmt.run(teamId, repoId, path ?? ''))
1747
+ return anyChanged(result)
1748
+ },
1749
+ async setTeamMember(teamId: string, userId: string, perms: TeamUserPermissions): Promise<void> {
1750
+ await upsertTeamMemberStmt.run(teamId, userId, perms.dependencies ? 1 : 0, perms.security ? 1 : 0)
1751
+ },
1752
+ async removeTeamMember(teamId: string, userId: string): Promise<boolean> {
1753
+ return anyChanged(await deleteTeamMemberStmt.run(teamId, userId))
1754
+ },
1755
+ }
1756
+ }
1757
+
1758
+ // `triageHistoryLimit`: events kept per finding in the triage trail; 0 (the
1759
+ // default) keeps everything. See ManagedConfig.
1760
+ export interface ManagedDbOptions {
1761
+ storageEncryptionKey?: StorageKey | null
1762
+ triageHistoryLimit?: number
1763
+ }
1764
+
1765
+ export function createManagedMethods(db: ManagedSql, options: ManagedDbOptions = {}): ManagedDb {
1766
+ const key = options.storageEncryptionKey ?? null
1767
+ const comments = commentMethods(db)
1768
+ const activity = activityMethods(db)
1769
+ const stmts = prepareStatements(db)
1770
+ const reports = reportMethods(stmts, db, key)
1771
+ const triage = triageMethods(stmts, options.triageHistoryLimit ?? 0, db)
1772
+ const {
1773
+ upsertUserStmt, selectLinkedStmt, selectUserIdStmt, promoteInitialAdminStmt, selectGithubIdStmt, insertSessionStmt, selectOwnSessionStmt, selectUsersStmt,
1774
+ selectUserStmt, touchOwnSessionStmt, touchUserSeenStmt, updateRoleStmt, updateTokensStmt, ensureUploadKeyStmt, deleteSessionStmt, deleteExpiredStmt,
1775
+ selectViewSessionStmt, deleteOtherViewsStmt, insertViewSessionStmt, deleteDemotedViewsStmt,
1776
+ } = stmts
1777
+
1778
+ // Claimed at every automatic reap: prepared once.
1779
+ const claimLeaseStmt = db.prepare(`INSERT INTO managed_maintenance_lease (id, owner, expires_at) VALUES (?, ?, ?)
1780
+ ON CONFLICT(id) DO UPDATE SET owner = excluded.owner, expires_at = excluded.expires_at
1781
+ WHERE managed_maintenance_lease.expires_at <= ? RETURNING id`)
1782
+ const finishLeaseStmt = db.prepare('UPDATE managed_maintenance_lease SET expires_at = ? WHERE owner = ?')
1783
+
1784
+ const methods: Omit<ManagedDb, keyof ManagementStore | keyof ManagementCatalogStore> = {
1785
+ ...storageMethods(db, key),
1786
+ ...linkReportMethods(db, key),
1787
+ ...repositoryAliasMethods(db),
1788
+ ...teamNpmScopeMethods(db),
1789
+ ...githubLinkMethods(db),
1790
+ ...dependencyReviewMethods(db),
1791
+ ...repositoryDependencyReviewMethods(db),
1792
+ ...bundleBuildLeaseMethods(db),
1793
+ ...upstreamCacheMethods(db),
1794
+ ...teamAppSummaryMethods(db),
1795
+ async claimMaintenanceLease(owner, now, until, migration = false) {
1796
+ return !!await claimLeaseStmt.get(migration ? 2 : 1, owner, until, now)
1797
+ },
1798
+ async finishMaintenanceLease(owner, until) {
1799
+ await finishLeaseStmt.run(until, owner)
1800
+ },
1801
+ async upsertUser(user, now, initialAdminGithubId = null) {
1802
+ if (await selectLinkedStmt.get(user.githubUserId)) return null
1803
+ // New row → a fresh id; ON CONFLICT(github_user_id) keeps an existing
1804
+ // user's id (DO UPDATE leaves it untouched), so re-read to return it.
1805
+ await upsertUserStmt.run(randomUUID(), user.githubUserId, user.login, user.name, user.name, user.avatarUrl, now, now)
1806
+ const row = (await selectUserIdStmt.get(user.githubUserId)) as { id: string; role: Role }
1807
+ // Avoid the population check unless this login matches the configured
1808
+ // identity and still needs approval. NOT EXISTS stops at any other user.
1809
+ if (initialAdminGithubId != null && Number.isSafeInteger(initialAdminGithubId) && initialAdminGithubId > 0
1810
+ && user.githubUserId === initialAdminGithubId && row.role === 'none') {
1811
+ await promoteInitialAdminStmt.run(row.id, row.id)
1812
+ }
1813
+ return row.id
1814
+ },
1815
+ async createSession(session, now) {
1816
+ await insertSessionStmt.run(session.id, session.userId, session.csrfToken, now, session.expiresAt)
1817
+ await touchUserSeenStmt.run(now, session.userId, now)
1818
+ },
1819
+ async sessionWithUser(id, now) {
1820
+ const row = (await touchOwnSessionStmt.get(now, now, id, now, id, id, id, id)) as SessionRow | undefined
1821
+ return row == null ? null : ownSession(row)
1822
+ },
1823
+ async getSessionWithUser(id, now) {
1824
+ const row = (await selectOwnSessionStmt.get(id, now)) as SessionRow | undefined
1825
+ return row == null ? null : ownSession(row)
1826
+ },
1827
+ async createViewSession(view, now) {
1828
+ if (!anyChanged(await insertViewSessionStmt.run(view.id, view.csrfToken, now, view.userId, view.viewerSessionId, now))) return false
1829
+ await deleteOtherViewsStmt.run(view.viewerSessionId, view.id)
1830
+ return true
1831
+ },
1832
+ async viewSessionWithUser(id, viewerSessionId, now) {
1833
+ const row = (await selectViewSessionStmt.get(id, viewerSessionId, now, now)) as ViewSessionRow | undefined
1834
+ if (row == null) return null
1835
+ await touchUserSeenStmt.run(now, row.viewerId, now)
1836
+ return viewSession(row)
1837
+ },
1838
+ async getViewSessionWithUser(id, viewerSessionId, now) {
1839
+ const row = (await selectViewSessionStmt.get(id, viewerSessionId, now, now)) as ViewSessionRow | undefined
1840
+ return row == null ? null : viewSession(row)
1841
+ },
1842
+ async ensureSessionUploadKey(id, candidate) {
1843
+ const row = (await ensureUploadKeyStmt.get(candidate, id)) as { uploadKey: string } | undefined
1844
+ return row?.uploadKey ?? null
1845
+ },
1846
+ async deleteSession(id) {
1847
+ await deleteSessionStmt.run(id)
1848
+ },
1849
+ async deleteExpiredSessions(now) {
1850
+ return Number((await deleteExpiredStmt.run(now)).changes)
1851
+ },
1852
+ async listUsers() {
1853
+ const rows = (await selectUsersStmt.all()) as UserRow[]
1854
+ return rows.map((r) => ({ id: r.id, login: r.login, name: r.name, role: r.role, createdAt: r.created, lastSeenAt: r.lastSeen, lastActivityAt: r.lastActivity }))
1855
+ },
1856
+ async getUser(id) {
1857
+ const row = (await selectUserStmt.get(id)) as StoredUser | undefined
1858
+ return row == null ? null : { id: row.id, login: row.login, name: row.name, avatarUrl: row.avatarUrl, role: row.role }
1859
+ },
1860
+ async setUserRole(id, role) {
1861
+ if (role !== 'admin') await deleteDemotedViewsStmt.run(id)
1862
+ return anyChanged(await updateRoleStmt.run(role, Date.now(), id))
1863
+ },
1864
+ async setUserTokens(id, tokens) {
1865
+ const state = await storageState(db, key)
1866
+ const value = state ? encodeStorageTokens(key!, id, tokens.accessToken, tokens.refreshToken) : { access: tokens.accessToken, refresh: tokens.refreshToken }
1867
+ await updateTokensStmt.run(value.access, value.refresh, tokens.expiresAt, state ? 1 : 0, Date.now(), id)
1868
+ },
1869
+ async getUserTokens(id) {
1870
+ // The tokens and the storage encryption state they were kept under, in
1871
+ // one read: a user missing reads as no tokens, no encryption row as none.
1872
+ const read = (await stmts.selectTokensStateStmt.get(id)) as StoredTokens & Parameters<typeof storageStateOf>[0] & { userId: string | null; stateId: number | null }
1873
+ const state = storageStateOf(read.stateId == null ? undefined : read, key)
1874
+ if (read.userId == null || read.access == null) return null
1875
+ if (read.encrypted && !state) throw new Error('Encrypted tokens without storage encryption state')
1876
+ if (!read.encrypted && state?.complete) throw new Error('Unexpected plaintext GitHub tokens')
1877
+ const value = read.encrypted ? decodeStorageTokens(key!, id, read) : read
1878
+ return { accessToken: value.access!, refreshToken: value.refresh, expiresAt: read.exp }
1879
+ },
1880
+ async getUserGithubId(id) {
1881
+ const row = (await selectGithubIdStmt.get(id)) as { githubId: number } | undefined
1882
+ return row?.githubId ?? null
1883
+ },
1884
+ ...githubMetadataMethods(db),
1885
+ ...githubCommitMethods(db),
1886
+ ...managedIssueMethods(db),
1887
+ ...selectedRepoMethods(stmts),
1888
+ ...activity,
1889
+ ...comments,
1890
+ async getAnnotations(ids) {
1891
+ // listTriage, listComments and listManagedIssues in one statement.
1892
+ const row = await stmts.selectAnnotationsStmt.get(JSON.stringify(ids)) as { triage: unknown; comments: unknown; issues: unknown }
1893
+ return { triage: ids.length > 0 ? jsonRows<TriageDbRow>(row.triage).map(triageRow) : [], comments: ids.length > 0 ? jsonRows<Awaited<ReturnType<CommentStore['listComments']>>[number]>(row.comments) : [],
1894
+ issues: jsonRows<ManagedIssue>(row.issues) }
1895
+ },
1896
+ async applyManagedIssueFixes(sessionId, snapshot, updates) {
1897
+ // Recheck access inside the same write transaction as the derived field.
1898
+ const current = await methods.getTeamReportAccessSnapshot(sessionId, Date.now(), snapshot.teamId!, snapshot.reportId)
1899
+ if (!current?.teamId || JSON.stringify(current) !== JSON.stringify(snapshot)) return false
1900
+ for (const update of updates) await methods.setManagedIssueTracking(update.findingId, update.issueUrl, update.previous, update.next, update.checkedAt)
1901
+ return true
1902
+ },
1903
+ ...workspaceShareMethods(db),
1904
+ ...reports,
1905
+ ...triage,
1906
+ ...importTriageMethods({ getReport: reports.getReport, ...triage, ...comments }),
1907
+ ...bundleMethods(stmts, db, key),
1908
+ ...teamMethods(stmts, db),
1909
+ async close() {
1910
+ await db.close()
1911
+ },
1912
+ }
1913
+ return { ...methods, ...managementMethods(methods), ...managementCatalogMethods(methods) }
1914
+ }