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

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