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

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