@preventive/triage 1.0.0-alpha.6 → 1.0.0-alpha.60

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