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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (409) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +17 -0
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +3 -0
  13. package/common/bundle-compare-diff.js +376 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-metadata.d.ts +15 -0
  20. package/common/bundle-metadata.js +226 -0
  21. package/common/bundle-pkg-of.d.ts +1 -0
  22. package/common/bundle-pkg-of.js +90 -0
  23. package/common/bundle-reasons.d.ts +2 -0
  24. package/common/bundle-reasons.js +21 -0
  25. package/common/bundle-source-links.d.ts +6 -0
  26. package/common/bundle-source-links.js +216 -0
  27. package/common/bundle-sourcemap.d.ts +10 -0
  28. package/common/bundle-sourcemap.js +100 -0
  29. package/common/bundle-sources.d.ts +7 -0
  30. package/common/bundle-sources.js +333 -0
  31. package/common/bundle-stats.js +41 -0
  32. package/common/bundle-tabs.js +1 -0
  33. package/common/code-language.js +65 -0
  34. package/common/default-scan-models.ts +36 -0
  35. package/common/dependency-reviews.d.ts +18 -0
  36. package/common/dependency-reviews.js +64 -0
  37. package/common/finding-duplicates.js +58 -0
  38. package/common/finding-filters.js +274 -0
  39. package/common/finding-id.js +47 -0
  40. package/common/finding-repo.d.ts +5 -0
  41. package/common/finding-repo.js +67 -0
  42. package/common/github-issue-labels.d.ts +1 -0
  43. package/common/github-issue-labels.js +11 -0
  44. package/common/github-pr.ts +56 -0
  45. package/common/gzip.js +59 -0
  46. package/common/line-diff.d.ts +8 -0
  47. package/common/line-diff.js +57 -0
  48. package/common/linked-workspace-groups.js +63 -0
  49. package/common/managed/agent-tasks.ts +292 -0
  50. package/common/managed/comments.ts +43 -0
  51. package/common/managed/finding-detail.d.ts +5 -0
  52. package/common/managed/finding-detail.js +75 -0
  53. package/common/managed/finding-values.d.ts +2 -0
  54. package/common/managed/finding-values.js +44 -0
  55. package/common/managed/github-agents.ts +114 -0
  56. package/common/managed/github-logins.ts +49 -0
  57. package/common/managed/lite-name.d.ts +2 -0
  58. package/common/managed/lite-name.js +20 -0
  59. package/common/managed/npm-packages.d.ts +7 -0
  60. package/common/managed/npm-packages.js +51 -0
  61. package/common/managed/permissions.ts +31 -0
  62. package/common/managed/report-content.ts +72 -0
  63. package/common/managed/report-filter.ts +120 -0
  64. package/common/managed/repository-alias.ts +65 -0
  65. package/common/managed/roles.ts +35 -0
  66. package/common/managed/routes.d.ts +2 -0
  67. package/common/managed/routes.js +363 -0
  68. package/common/managed/scan-models.ts +6 -0
  69. package/common/managed/team-app.d.ts +15 -0
  70. package/common/managed/team-app.js +100 -0
  71. package/common/managed/team-filters.js +26 -0
  72. package/common/managed/triage.ts +83 -0
  73. package/common/managed/upload-seal.ts +126 -0
  74. package/common/pretty-print.d.ts +5 -0
  75. package/common/pretty-print.js +24 -0
  76. package/common/repo-commit.d.ts +4 -0
  77. package/common/repo-commit.js +30 -0
  78. package/common/revalidation-conflicts.js +48 -0
  79. package/common/revalidation-input-groups.js +56 -0
  80. package/common/save-error-reason.ts +20 -7
  81. package/common/scan-server.ts +13 -0
  82. package/common/security-links.d.ts +5 -0
  83. package/common/security-links.js +33 -0
  84. package/common/server-info.ts +46 -0
  85. package/common/utf8.d.ts +3 -0
  86. package/common/utf8.js +45 -0
  87. package/common/workspace-app.js +71 -0
  88. package/common/workspace-groups.js +176 -0
  89. package/out/activity.js +4 -0
  90. package/out/brotli-fallback.js +3 -3
  91. package/out/chunk-2XUEZHIP.js +28 -0
  92. package/out/chunk-4EMM6UCD.js +1 -0
  93. package/out/chunk-4ISO5F7Y.js +7 -0
  94. package/out/chunk-4XIH7YTX.js +1 -0
  95. package/out/chunk-6CCSTJWB.js +1 -0
  96. package/out/chunk-74AEKRES.js +10 -0
  97. package/out/chunk-7BKKYVWR.js +7 -0
  98. package/out/chunk-7C7DWL7I.js +1 -0
  99. package/out/chunk-B3FNMHOE.js +1 -0
  100. package/out/chunk-BNH52UHC.js +2 -0
  101. package/out/chunk-BRO77PQY.js +42 -0
  102. package/out/chunk-C4Z6ZBXV.js +10 -0
  103. package/out/chunk-DEVAORP2.js +1 -0
  104. package/out/chunk-E3LFSUDJ.js +9 -0
  105. package/out/chunk-G3LY2FV4.js +1 -0
  106. package/out/chunk-GO7FT4OD.js +1 -0
  107. package/out/chunk-GRGIZOTP.js +4 -0
  108. package/out/chunk-HAZKDK4M.js +4 -0
  109. package/out/chunk-HOB3YPS5.js +1 -0
  110. package/out/chunk-IYPY47MC.js +1 -0
  111. package/out/chunk-IZ6MYRYB.js +3 -0
  112. package/out/chunk-J2FWBXFV.js +1 -0
  113. package/out/chunk-JCIIBLKR.js +1 -0
  114. package/out/chunk-JFL7WLRV.js +1 -0
  115. package/out/chunk-JJK5OZG2.js +15 -0
  116. package/out/chunk-JMG5DXII.js +2 -0
  117. package/out/chunk-JOXLZXMI.js +1 -0
  118. package/out/chunk-M37X4LCF.js +14 -0
  119. package/out/chunk-M3Y6SLC4.js +1 -0
  120. package/out/chunk-NRPC74AM.js +1 -0
  121. package/out/chunk-NXATZJQ2.js +1 -0
  122. package/out/chunk-OFZYEWBH.js +244 -0
  123. package/out/chunk-OIERSXON.js +1 -0
  124. package/out/chunk-OOJM4CTU.js +1 -0
  125. package/out/chunk-PAD2JHZT.js +1 -0
  126. package/out/chunk-PNHBZGDD.js +1 -0
  127. package/out/chunk-PTFQKLKO.js +1 -0
  128. package/out/chunk-PWFUOLZK.js +17 -0
  129. package/out/chunk-PXK7EU4V.js +1 -0
  130. package/out/chunk-QCOGVL37.js +52 -0
  131. package/out/chunk-QMVOEBWC.js +13 -0
  132. package/out/chunk-QRKFPLA4.js +80 -0
  133. package/out/chunk-R3NZFXVR.js +1 -0
  134. package/out/chunk-R5O6FAW4.js +2 -0
  135. package/out/chunk-RRBIJL2B.js +1 -0
  136. package/out/chunk-SYXT3SFP.js +2 -0
  137. package/out/chunk-TOXMUOIW.js +5 -0
  138. package/out/chunk-TUII34K2.js +1 -0
  139. package/out/chunk-UCP3JRE2.js +1 -0
  140. package/out/chunk-VFWMQ3LG.js +2 -0
  141. package/out/chunk-VRX2APNA.js +9 -0
  142. package/out/chunk-W3QFV4SP.js +3 -0
  143. package/out/chunk-W6VOKW2N.js +12 -0
  144. package/out/chunk-WCPJDAYA.js +10 -0
  145. package/out/chunk-WMFDQS2L.js +11 -0
  146. package/out/chunk-WREU7JAG.js +1 -0
  147. package/out/chunk-Y5ZHFNBD.js +2 -0
  148. package/out/chunk-YF4M5OCI.js +1 -0
  149. package/out/chunk-Z667U2UJ.js +1 -0
  150. package/out/chunk-ZQHLECTI.js +1 -0
  151. package/out/chunk-ZQNEWVGG.js +1 -0
  152. package/out/client-managed-import.js +4 -0
  153. package/out/client-managed.js +34 -0
  154. package/out/client-sync.js +11 -17
  155. package/out/compare.js +40 -0
  156. package/out/dialogs.js +40 -0
  157. package/out/github-issue-authorized.html +3 -0
  158. package/out/github-issue-authorized.js +1 -0
  159. package/out/graph.js +19 -4
  160. package/out/index.html +106 -8
  161. package/out/prism.js +14 -10
  162. package/out/scan.js +2 -0
  163. package/out/stasis.svg +20 -0
  164. package/out/terminal.js +366 -39
  165. package/out/view.css +1 -1
  166. package/out/view.js +19 -144
  167. package/package.json +383 -63
  168. package/risk/actions/findings.js +161 -0
  169. package/risk/actions/resolve.js +250 -0
  170. package/risk/actions/scripts/commands.js +182 -0
  171. package/risk/actions/scripts/grade.js +113 -0
  172. package/risk/actions/scripts/packages.js +123 -0
  173. package/risk/actions/scripts/shell.js +169 -0
  174. package/risk/actions/uses.js +76 -0
  175. package/risk/actions/workflow.js +110 -0
  176. package/risk/files/characters.js +196 -0
  177. package/risk/files/hosts.js +205 -0
  178. package/risk/files/readability.js +177 -0
  179. package/risk/files/runs-code.js +615 -0
  180. package/risk/files/script.js +118 -0
  181. package/risk/files/stamps.js +47 -0
  182. package/risk/index.d.ts +272 -0
  183. package/risk/index.js +11 -0
  184. package/risk/npm/assess.js +285 -0
  185. package/risk/npm/combined.js +68 -0
  186. package/risk/npm/compare.js +257 -0
  187. package/risk/npm/dependencies.js +172 -0
  188. package/risk/npm/diff.js +79 -0
  189. package/risk/npm/downloads.js +84 -0
  190. package/risk/npm/files.js +445 -0
  191. package/risk/npm/held.js +63 -0
  192. package/risk/npm/install-scripts.js +34 -0
  193. package/risk/npm/malware.js +38 -0
  194. package/risk/npm/manifest.js +65 -0
  195. package/risk/npm/new-dependency.js +60 -0
  196. package/risk/npm/old-version.js +108 -0
  197. package/risk/npm/registry.js +390 -0
  198. package/risk/npm/release.js +85 -0
  199. package/risk/npm/score.js +59 -0
  200. package/risk/npm/specs.js +124 -0
  201. package/risk/npm/tarball.js +96 -0
  202. package/server-common/database-config.ts +16 -0
  203. package/server-common/initialize.ts +18 -0
  204. package/server-common/npm-advisories.ts +101 -0
  205. package/{server → server-common}/origin.ts +5 -5
  206. package/server-common/reap.ts +48 -0
  207. package/server-common/scan-config.ts +19 -0
  208. package/server-common/standalone.ts +29 -0
  209. package/server-common/storage-crypto.ts +182 -0
  210. package/server-common/storage-log.ts +38 -0
  211. package/server-common/vercel-blob.ts +103 -0
  212. package/server-e2e/app.ts +487 -0
  213. package/{server → server-e2e}/bus-receiver.ts +2 -1
  214. package/{server → server-e2e}/cli.js +9 -4
  215. package/{server → server-e2e}/config.ts +50 -42
  216. package/{server → server-e2e}/db-neon.ts +2 -2
  217. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  218. package/{server → server-e2e}/db-stmt.ts +2 -2
  219. package/{server → server-e2e}/db.ts +7 -7
  220. package/{server → server-e2e}/http.ts +44 -13
  221. package/{server → server-e2e}/hub.ts +40 -9
  222. package/server-e2e/index.ts +17 -0
  223. package/server-e2e/lifecycle.ts +95 -0
  224. package/{server → server-e2e}/neon-driver.ts +2 -2
  225. package/{server → server-e2e}/npm-proxy.ts +12 -145
  226. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  227. package/{server → server-e2e}/objstore/blob.ts +1 -1
  228. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  229. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  230. package/{server → server-e2e}/objstore/init.ts +19 -27
  231. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  232. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  233. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  234. package/{server → server-e2e}/objstore/rest.ts +3 -3
  235. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  236. package/{server → server-e2e}/objstore/store.ts +7 -7
  237. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  238. package/{server → server-e2e}/pubsub.ts +12 -9
  239. package/{server → server-e2e}/sign.ts +4 -4
  240. package/{server → server-e2e}/sse-server.ts +60 -33
  241. package/{server → server-e2e}/static.ts +31 -21
  242. package/{server → server-e2e}/sync-handlers.ts +64 -30
  243. package/{server → server-e2e}/ws-server.ts +20 -9
  244. package/server-managed/activity.ts +238 -0
  245. package/server-managed/agent-merges.ts +109 -0
  246. package/server-managed/app-agents.ts +23 -0
  247. package/server-managed/avatar-store.ts +13 -0
  248. package/server-managed/blob-store.ts +26 -0
  249. package/server-managed/brotli.ts +10 -0
  250. package/server-managed/bundle-advisories.ts +103 -0
  251. package/server-managed/bundle-advisory-inventory.ts +77 -0
  252. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  253. package/server-managed/bundle-build-diagnostics.js +23 -0
  254. package/server-managed/bundle-build-leases.ts +41 -0
  255. package/server-managed/bundle-build-worker.js +238 -0
  256. package/server-managed/bundle-build.ts +240 -0
  257. package/server-managed/bundle-cache.ts +199 -0
  258. package/server-managed/bundle-catalog.ts +29 -0
  259. package/server-managed/bundle-commits.ts +133 -0
  260. package/server-managed/bundle-dependency-reviews.ts +68 -0
  261. package/server-managed/bundle-store.ts +24 -0
  262. package/server-managed/bundle-summary-cache.ts +139 -0
  263. package/server-managed/bundle-validation.ts +33 -0
  264. package/server-managed/bundle.ts +119 -0
  265. package/server-managed/cache-storage.ts +20 -0
  266. package/server-managed/cli.js +21 -0
  267. package/server-managed/combined.ts +43 -0
  268. package/server-managed/comments.ts +138 -0
  269. package/server-managed/commit-coauthors.ts +105 -0
  270. package/server-managed/commit-lockfiles.ts +77 -0
  271. package/server-managed/comparison.ts +50 -0
  272. package/server-managed/config.ts +163 -0
  273. package/server-managed/content-access.ts +15 -0
  274. package/server-managed/crypto.ts +25 -0
  275. package/server-managed/db-methods.ts +1877 -0
  276. package/server-managed/db-neon.ts +388 -0
  277. package/server-managed/db-schema.ts +253 -0
  278. package/server-managed/db-table-names.ts +22 -0
  279. package/server-managed/db.ts +146 -0
  280. package/server-managed/dependabot-access.ts +61 -0
  281. package/server-managed/dependabot-alerts.ts +180 -0
  282. package/server-managed/dependency-review-comments.ts +92 -0
  283. package/server-managed/dependency-reviews.ts +363 -0
  284. package/server-managed/github-accounts.ts +59 -0
  285. package/server-managed/github-actions.ts +71 -0
  286. package/server-managed/github-app.ts +347 -0
  287. package/server-managed/github-errors.ts +70 -0
  288. package/server-managed/github-graphql.ts +42 -0
  289. package/server-managed/github-issue-links.ts +264 -0
  290. package/server-managed/github-issue-oauth.ts +30 -0
  291. package/server-managed/github-issues.ts +157 -0
  292. package/server-managed/github-link-oauth.ts +56 -0
  293. package/server-managed/github-links.ts +204 -0
  294. package/server-managed/github-metadata.ts +213 -0
  295. package/server-managed/github-oauth.ts +264 -0
  296. package/server-managed/github-pulls.ts +257 -0
  297. package/server-managed/github-requests.ts +179 -0
  298. package/server-managed/github-users.ts +30 -0
  299. package/server-managed/github-values.ts +26 -0
  300. package/server-managed/history-windows.ts +172 -0
  301. package/server-managed/http-response.ts +76 -0
  302. package/server-managed/http.ts +5796 -0
  303. package/server-managed/import-triage.ts +51 -0
  304. package/server-managed/index.ts +204 -0
  305. package/server-managed/kept-briefly.ts +37 -0
  306. package/server-managed/kept.ts +28 -0
  307. package/server-managed/link-reports.ts +149 -0
  308. package/server-managed/listed-activity.ts +39 -0
  309. package/server-managed/locked-packages.ts +152 -0
  310. package/server-managed/lockfile-scope.ts +49 -0
  311. package/server-managed/lru.ts +30 -0
  312. package/server-managed/managed-issues.ts +92 -0
  313. package/server-managed/management-catalog.ts +45 -0
  314. package/server-managed/management.ts +110 -0
  315. package/server-managed/npm-delta-worker.js +23 -0
  316. package/server-managed/npm-delta.ts +159 -0
  317. package/server-managed/npm-insights.ts +455 -0
  318. package/server-managed/npm-kept.ts +234 -0
  319. package/server-managed/npm-loads.ts +259 -0
  320. package/server-managed/npm-manifest.ts +117 -0
  321. package/server-managed/npm-packages.ts +462 -0
  322. package/server-managed/npm-patch.ts +317 -0
  323. package/server-managed/npm-provenance.ts +127 -0
  324. package/server-managed/npm-risk.ts +287 -0
  325. package/server-managed/object-storage-disk.ts +147 -0
  326. package/server-managed/object-storage-vercel.ts +71 -0
  327. package/server-managed/object-storage.ts +82 -0
  328. package/server-managed/package-entry-points.ts +79 -0
  329. package/server-managed/pretty-print.ts +425 -0
  330. package/server-managed/public-workspace.ts +242 -0
  331. package/server-managed/pull-comment-reviews.ts +161 -0
  332. package/server-managed/pull-dependencies.ts +340 -0
  333. package/server-managed/pull-dependency-reviews.ts +327 -0
  334. package/server-managed/pull-reviews.ts +202 -0
  335. package/server-managed/queue.ts +53 -0
  336. package/server-managed/release-commits.ts +85 -0
  337. package/server-managed/rename-diff-worker.js +26 -0
  338. package/server-managed/rename-diff.ts +236 -0
  339. package/server-managed/repo-path.ts +21 -0
  340. package/server-managed/report-migration.ts +32 -0
  341. package/server-managed/report-query.ts +10 -0
  342. package/server-managed/report-response.ts +16 -0
  343. package/server-managed/report-sources.ts +181 -0
  344. package/server-managed/report-store.ts +77 -0
  345. package/server-managed/repository-actions.ts +220 -0
  346. package/server-managed/repository-agents.ts +422 -0
  347. package/server-managed/repository-aliases.ts +85 -0
  348. package/server-managed/repository-browser.ts +303 -0
  349. package/server-managed/repository-changes.ts +280 -0
  350. package/server-managed/repository-code.ts +215 -0
  351. package/server-managed/repository-dependency-reviews.ts +159 -0
  352. package/server-managed/repository-discovery.ts +83 -0
  353. package/server-managed/repository-history.ts +428 -0
  354. package/server-managed/repository-issues.ts +224 -0
  355. package/server-managed/repository-policy.ts +27 -0
  356. package/server-managed/repository-pulls.ts +207 -0
  357. package/server-managed/repository-pulse.ts +477 -0
  358. package/server-managed/repository-risk-assess.ts +108 -0
  359. package/server-managed/repository-risk-audit.ts +78 -0
  360. package/server-managed/repository-risk-read.ts +170 -0
  361. package/server-managed/repository-risk.ts +483 -0
  362. package/server-managed/repository-squashes.ts +160 -0
  363. package/server-managed/repository-stamp.ts +41 -0
  364. package/server-managed/request-timing.ts +63 -0
  365. package/server-managed/reviewed-dependencies.ts +149 -0
  366. package/server-managed/revisions.ts +35 -0
  367. package/server-managed/scan-downloads.ts +87 -0
  368. package/server-managed/session.ts +132 -0
  369. package/server-managed/slugs.ts +38 -0
  370. package/server-managed/solidity-entry-points.ts +71 -0
  371. package/server-managed/sql-postgres.ts +34 -0
  372. package/server-managed/sql.ts +107 -0
  373. package/server-managed/stasis-config.ts +55 -0
  374. package/server-managed/static.ts +28 -0
  375. package/server-managed/storage-command.ts +16 -0
  376. package/server-managed/storage-db.ts +183 -0
  377. package/server-managed/storage-encryption.ts +288 -0
  378. package/server-managed/storage-maintenance.ts +259 -0
  379. package/server-managed/storage-payload.ts +121 -0
  380. package/server-managed/storage-stores.ts +91 -0
  381. package/server-managed/storage.ts +82 -0
  382. package/server-managed/team-app-summaries.ts +54 -0
  383. package/server-managed/team-app.ts +154 -0
  384. package/server-managed/team-catalog.ts +7 -0
  385. package/server-managed/team-feed.ts +180 -0
  386. package/server-managed/team-npm-scopes.ts +103 -0
  387. package/server-managed/team-reports.ts +351 -0
  388. package/server-managed/triage-response.ts +16 -0
  389. package/server-managed/type-only-proof.js +108 -0
  390. package/server-managed/type-only-worker.js +31 -0
  391. package/server-managed/type-only.ts +115 -0
  392. package/server-managed/uploads.ts +106 -0
  393. package/server-managed/upstream-cache.ts +250 -0
  394. package/server-managed/view-as.ts +58 -0
  395. package/server-managed/worker-turns.ts +76 -0
  396. package/server-managed/workspace-shares.ts +170 -0
  397. package/server.ts +70 -0
  398. package/server/index.ts +0 -480
  399. package/server/lifecycle.ts +0 -208
  400. /package/{LICENSE → LICENSE-MIT} +0 -0
  401. /package/{server → server-e2e}/auth.ts +0 -0
  402. /package/{server → server-e2e}/config.example.json +0 -0
  403. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  404. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  405. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  406. /package/{server → server-e2e}/peer.ts +0 -0
  407. /package/{server → server-e2e}/sse-session.ts +0 -0
  408. /package/{server → server-e2e}/util.ts +0 -0
  409. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,388 @@
1
+ import { DEPENDENCY_REVIEW_COLUMNS, DEPENDENCY_REVIEW_INDEXES, DEPENDENCY_REVIEW_SCHEMA } from './dependency-reviews.ts'
2
+ import { LINK_REPORT_SCHEMA } from './link-reports.ts'
3
+ import { REPOSITORY_ALIAS_SCHEMA } from './repository-aliases.ts'
4
+ import { TEAM_NPM_SCOPE_SCHEMA } from './team-npm-scopes.ts'
5
+ import { GITHUB_LINK_SCHEMA, GITHUB_LINK_USER_COLUMNS } from './github-links.ts'
6
+ import { REPOSITORY_DEPENDENCY_REVIEW_COLUMNS } from './repository-dependency-reviews.ts'
7
+ import { AsyncLocalStorage } from 'node:async_hooks'
8
+ import { WebSocket } from 'ws'
9
+ import { type ManagedDb, type ManagedDbOptions, createManagedMethods } from './db-methods.ts'
10
+ import { revisionSchema } from './revisions.ts'
11
+ import { MANAGED_SCHEMA, REPO_UPLOAD_INDEXES, VIEW_SESSION_INDEX } from './db-schema.ts'
12
+ import { STORAGE_SCHEMA } from './storage-db.ts'
13
+ import { GITHUB_COMMIT_SCHEMA, GITHUB_METADATA_SCHEMA, GITHUB_STATE_REASON_COLUMN } from './github-metadata.ts'
14
+ import { MANAGED_ISSUE_SCHEMA } from './managed-issues.ts'
15
+ import { BUNDLE_BUILD_LEASE_SCHEMA } from './bundle-build-leases.ts'
16
+ import { UPSTREAM_CACHE_SCHEMA } from './upstream-cache.ts'
17
+ import { TEAM_APP_SUMMARY_SCHEMA } from './team-app-summaries.ts'
18
+ import { COMMENT_SCHEMA } from './comments.ts'
19
+ import { ACTIVITY_SCHEMA, uploadAction } from './activity.ts'
20
+ import { type ManagedSqlDriver, scopeManagedMethods } from './sql.ts'
21
+ import { countStatement, timed } from './request-timing.ts'
22
+ import { postgresSchema, postgresSql } from './sql-postgres.ts'
23
+ import { managedTableRenames } from './db-table-names.ts'
24
+ import { WORKSPACE_SHARE_SCHEMA } from './workspace-shares.ts'
25
+ import { allocateMissingSlugs } from './slugs.ts'
26
+
27
+ export interface PgConnection {
28
+ query(sql: string, params?: unknown[]): Promise<{
29
+ rows: Record<string, unknown>[]; rowCount?: number | null
30
+ fields?: { name: string; dataTypeID: number }[]
31
+ }>
32
+ // After a failure the connection's state is unknown: discard it, never reuse it.
33
+ release(discard?: boolean): Promise<void>
34
+ }
35
+ export type PgConnect = () => Promise<PgConnection>
36
+ // Content/access mutations cooperate on this transaction-scoped lock. Reads,
37
+ // presence updates, and maintenance leases do not take it. Also fences migrations.
38
+ const LOCK = 'SELECT pg_advisory_xact_lock(1937006964, 1835101793)'
39
+
40
+ // Whether every version up to the latest is recorded, in one round trip at
41
+ // a cold start: a database with no versions table yet (undefined_table) has
42
+ // none. Outside a transaction, so the failed read aborts nothing.
43
+ const SCHEMA_VERSIONS = 35
44
+ async function currentSchema(db: PgConnection): Promise<boolean> {
45
+ try {
46
+ const { rows } = await db.query(`SELECT count(*) AS n FROM managed_schema_version WHERE version BETWEEN 1 AND ${SCHEMA_VERSIONS}`)
47
+ return Number(rows[0]?.['n']) === SCHEMA_VERSIONS
48
+ } catch (error) {
49
+ if ((error as { code?: unknown })?.code === '42P01') return false
50
+ throw error
51
+ }
52
+ }
53
+
54
+ // Whether migration `version` is recorded, in the bootstrap's transaction.
55
+ async function recorded(db: PgConnection, version: number): Promise<boolean> {
56
+ return (await db.query(`SELECT version FROM managed_schema_version WHERE version = ${version}`)).rows.length > 0
57
+ }
58
+
59
+ // An ALTER TABLE's clauses adding each of `columns` it lacks.
60
+ const addColumns = (columns: readonly (readonly [string, string])[]) =>
61
+ columns.map(([column, type]) => `ADD COLUMN IF NOT EXISTS ${column} ${type}`).join(', ')
62
+
63
+ // Migration `version`, unless it is recorded: its `statements` in order,
64
+ // then its record.
65
+ async function migration(db: PgConnection, version: number, ...statements: string[]): Promise<void> {
66
+ if (await recorded(db, version)) return
67
+ for (const statement of statements) await db.query(statement)
68
+ await db.query(`INSERT INTO managed_schema_version VALUES (${version})`)
69
+ }
70
+
71
+ async function migrateGithubMetadata(db: PgConnection): Promise<void> {
72
+ await db.query(postgresSchema(GITHUB_METADATA_SCHEMA + MANAGED_ISSUE_SCHEMA))
73
+ await db.query(`ALTER TABLE managed_github_metadata ADD COLUMN IF NOT EXISTS state_reason ${GITHUB_STATE_REASON_COLUMN}`)
74
+ await db.query('ALTER TABLE managed_github_metadata ADD COLUMN IF NOT EXISTS attempted_at BIGINT')
75
+ await db.query('INSERT INTO managed_schema_version VALUES (14) ON CONFLICT DO NOTHING')
76
+ }
77
+
78
+ async function migrateLinkReports(db: PgConnection): Promise<void> {
79
+ await db.query(postgresSchema(revisionSchema(true)))
80
+ await db.query('INSERT INTO managed_schema_version VALUES (16) ON CONFLICT DO NOTHING')
81
+ }
82
+
83
+ async function migrateRepositoryAliases(db: PgConnection): Promise<void> {
84
+ await db.query(postgresSchema(REPOSITORY_ALIAS_SCHEMA))
85
+ await db.query('INSERT INTO managed_schema_version VALUES (17) ON CONFLICT DO NOTHING')
86
+ }
87
+
88
+ // Existing rows stay NULL (unknown): some may have been built on the server.
89
+ async function migrateBundleProvenance(db: PgConnection): Promise<void> {
90
+ if (await recorded(db, 20)) return
91
+ await db.query('ALTER TABLE managed_bundle ADD COLUMN IF NOT EXISTS provenance TEXT')
92
+ await createUploadTrigger(db, 'bundle', false)
93
+ await db.query('INSERT INTO managed_schema_version VALUES (20)')
94
+ }
95
+
96
+ // The migrations from 12 on, in order.
97
+ async function migrateFrom12(db: PgConnection): Promise<void> {
98
+ await migration(db, 12, 'ALTER TABLE managed_selected_repo ADD COLUMN IF NOT EXISTS cached_default_branch TEXT')
99
+ await migration(db, 13, postgresSchema(BUNDLE_BUILD_LEASE_SCHEMA))
100
+ await migration(db, 15, 'ALTER TABLE managed_bundle ADD COLUMN IF NOT EXISTS visible INTEGER NOT NULL DEFAULT 1')
101
+ await migrateLinkReports(db)
102
+ await migrateRepositoryAliases(db)
103
+ await migration(db, 18, 'ALTER TABLE managed_team ADD COLUMN IF NOT EXISTS hidden INTEGER NOT NULL DEFAULT 0')
104
+ await migration(db, 19, 'ALTER TABLE managed_finding_issue ADD COLUMN IF NOT EXISTS auto_fix_url TEXT, ADD COLUMN IF NOT EXISTS auto_fix_checked_at BIGINT',
105
+ postgresSchema(revisionSchema(true)))
106
+ await migrateBundleProvenance(db)
107
+ await migration(db, 21, postgresSchema(UPSTREAM_CACHE_SCHEMA))
108
+ // Existing builds stay NULL: their conditions were never recorded.
109
+ await migration(db, 22, 'ALTER TABLE managed_bundle ADD COLUMN IF NOT EXISTS build_conditions TEXT')
110
+ // Existing sessions create their upload key on first use.
111
+ await migration(db, 23, 'ALTER TABLE managed_session ADD COLUMN IF NOT EXISTS upload_key TEXT')
112
+ await migration(db, 24, 'ALTER TABLE managed_session ADD COLUMN IF NOT EXISTS viewer_session TEXT REFERENCES managed_session(id) ON DELETE CASCADE',
113
+ VIEW_SESSION_INDEX)
114
+ await migration(db, 25, postgresSchema(GITHUB_COMMIT_SCHEMA))
115
+ await migration(db, 26, postgresSchema(TEAM_NPM_SCOPE_SCHEMA))
116
+ await migration(db, 27, 'ALTER TABLE managed_team ADD COLUMN IF NOT EXISTS dependency_review INTEGER NOT NULL DEFAULT 0',
117
+ postgresSchema(DEPENDENCY_REVIEW_SCHEMA))
118
+ // Existing names are the sign-in accounts' own: none was chosen yet.
119
+ await migration(db, 28, postgresSchema(GITHUB_LINK_SCHEMA), `ALTER TABLE managed_user ${addColumns(GITHUB_LINK_USER_COLUMNS)}`,
120
+ 'UPDATE managed_user SET github_name = name')
121
+ await migration(db, 29, `ALTER TABLE managed_selected_repo ${addColumns(REPOSITORY_DEPENDENCY_REVIEW_COLUMNS)}`)
122
+ // The lockfiles a repository's dependency review holds to, its columns
123
+ // added since 29 added there too; and a team's published reviews, listed by
124
+ // it, indexed so.
125
+ await migration(db, 30, `ALTER TABLE managed_selected_repo ${addColumns(REPOSITORY_DEPENDENCY_REVIEW_COLUMNS)}`,
126
+ 'CREATE INDEX IF NOT EXISTS managed_dependency_review_team_idx ON managed_dependency_review_team(team_id, review_id)')
127
+ await migration(db, 31, REPO_UPLOAD_INDEXES)
128
+ // The shasums of the tarballs a dependency review reads, none known of
129
+ // those written before.
130
+ await migration(db, 32, `ALTER TABLE managed_dependency_review ${addColumns(DEPENDENCY_REVIEW_COLUMNS)}`)
131
+ // The patch a dependency review is of, and where it was read, none of
132
+ // those written before; each author's one draft of a comparison held to its
133
+ // patch too.
134
+ await migration(db, 33, `ALTER TABLE managed_dependency_review ${addColumns(DEPENDENCY_REVIEW_COLUMNS)}`, DEPENDENCY_REVIEW_INDEXES)
135
+ await migration(db, 34, postgresSchema(TEAM_APP_SUMMARY_SCHEMA))
136
+ // The issue a saved one was closed as a duplicate of, none known of those
137
+ // checked before.
138
+ await migration(db, 35, 'ALTER TABLE managed_finding_issue ADD COLUMN IF NOT EXISTS duplicate_of_url TEXT')
139
+ }
140
+
141
+ async function initialize(db: PgConnection): Promise<void> {
142
+ if (await currentSchema(db)) return
143
+ await db.query('BEGIN')
144
+ try {
145
+ await db.query(LOCK)
146
+ await db.query('CREATE TABLE IF NOT EXISTS managed_schema_version (version INTEGER PRIMARY KEY)')
147
+ const initialized = await recorded(db, 1)
148
+ const prefixed = await recorded(db, 3)
149
+ if (initialized && !prefixed) {
150
+ const { rows } = await db.query("SELECT relname AS name FROM pg_class WHERE relkind IN ('r', 'p') AND pg_table_is_visible(oid)")
151
+ for (const [from, to] of managedTableRenames(new Set(rows.map(row => String(row['name']))))) {
152
+ await db.query(`ALTER TABLE ${from} RENAME TO ${to}`)
153
+ }
154
+ // PL/pgSQL function bodies retain literal table names after ALTER TABLE.
155
+ for (const type of ['report', 'bundle']) await createUploadTrigger(db, type, false)
156
+ }
157
+ if (!initialized) {
158
+ await db.query(postgresSchema(MANAGED_SCHEMA + COMMENT_SCHEMA + ACTIVITY_SCHEMA))
159
+ await db.query(`ALTER TABLE managed_finding_triage_event ADD COLUMN report_id TEXT, ADD COLUMN report TEXT, ADD COLUMN repo TEXT;
160
+ CREATE UNIQUE INDEX managed_team_slug_idx ON managed_team(slug);
161
+ CREATE UNIQUE INDEX managed_report_slug_idx ON managed_report(slug);
162
+ CREATE INDEX managed_activity_actor_at_idx ON managed_activity(actor_id, at);`)
163
+ for (const type of ['report', 'bundle']) await createUploadTrigger(db, type)
164
+ await db.query('INSERT INTO managed_schema_version VALUES (1)')
165
+ }
166
+ await migration(db, 2, 'CREATE INDEX IF NOT EXISTS managed_report_bundle_hash_idx ON managed_report(bundle_id, sha256)')
167
+ if (!prefixed) await db.query('INSERT INTO managed_schema_version VALUES (3)')
168
+ await migration(db, 4, postgresSchema(WORKSPACE_SHARE_SCHEMA))
169
+ await migrateGithubMetadata(db)
170
+ await migration(db, 5, `ALTER TABLE managed_workspace_share ADD COLUMN IF NOT EXISTS dependencies INTEGER NOT NULL DEFAULT 0,
171
+ ADD COLUMN IF NOT EXISTS security INTEGER NOT NULL DEFAULT 0`)
172
+ if (!await recorded(db, 6)) {
173
+ await db.query('ALTER TABLE managed_bundle ADD COLUMN IF NOT EXISTS slug TEXT')
174
+ const { rows } = await db.query('SELECT id, slug FROM managed_bundle ORDER BY id')
175
+ for (const row of allocateMissingSlugs(rows as { id: string; slug: string | null }[])) {
176
+ await db.query('UPDATE managed_bundle SET slug = $1 WHERE id = $2', [row.slug, row.id])
177
+ }
178
+ await db.query(`ALTER TABLE managed_bundle ALTER COLUMN slug SET NOT NULL;
179
+ CREATE UNIQUE INDEX IF NOT EXISTS managed_bundle_slug_idx ON managed_bundle(slug);
180
+ INSERT INTO managed_schema_version VALUES (6)`)
181
+ }
182
+ await migration(db, 7, "ALTER TABLE managed_bundle ADD COLUMN IF NOT EXISTS repo_directory TEXT NOT NULL DEFAULT ''")
183
+ await migration(db, 8, 'CREATE INDEX IF NOT EXISTS managed_report_hash_idx ON managed_report(sha256, uploaded_at, id)')
184
+ await migration(db, 9, postgresSchema(STORAGE_SCHEMA),
185
+ ...['managed_report', 'managed_bundle'].map(table => `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS data_key TEXT, ADD COLUMN IF NOT EXISTS storage_encrypted INTEGER NOT NULL DEFAULT 0`),
186
+ 'ALTER TABLE managed_user ADD COLUMN IF NOT EXISTS gh_tokens_encrypted INTEGER NOT NULL DEFAULT 0')
187
+ await db.query(postgresSchema(LINK_REPORT_SCHEMA))
188
+ if (!await recorded(db, 10)) {
189
+ await db.query(postgresSchema(revisionSchema(true)) + '; INSERT INTO managed_schema_version VALUES (10)')
190
+ }
191
+ if (!await recorded(db, 11)) {
192
+ await db.query(postgresSchema(revisionSchema(true)) + '; INSERT INTO managed_schema_version VALUES (11)')
193
+ }
194
+ await migrateFrom12(db)
195
+ await db.query('COMMIT')
196
+ } catch (err) {
197
+ await db.query('ROLLBACK')
198
+ throw err
199
+ }
200
+ }
201
+
202
+ async function createUploadTrigger(db: PgConnection, type: string, createTrigger = true): Promise<void> {
203
+ await db.query(`CREATE OR REPLACE FUNCTION managed_${type}_activity_insert() RETURNS trigger LANGUAGE plpgsql AS $$
204
+ BEGIN
205
+ INSERT INTO managed_activity (id, kind, actor, action, repo, report_id, report, at, bundle_id, actor_id)
206
+ VALUES ('${type}-upload:' || NEW.id, 'upload',
207
+ COALESCE(NEW.uploaded_by_login, (SELECT login FROM managed_user WHERE id = NEW.uploaded_by)),
208
+ ${uploadAction(type, 'NEW')}, (SELECT full_name FROM managed_selected_repo WHERE repo_id = NEW.repo_id),
209
+ ${type === 'report' ? 'NEW.id' : 'NULL'}, NEW.filename, NEW.uploaded_at,
210
+ ${type === 'bundle' ? 'NEW.id' : 'NULL'}, NEW.uploaded_by);
211
+ RETURN NEW;
212
+ END $$;`)
213
+ if (createTrigger) {
214
+ await db.query(`CREATE TRIGGER managed_${type}_activity AFTER INSERT ON managed_${type}
215
+ FOR EACH ROW EXECUTE FUNCTION managed_${type}_activity_insert();`)
216
+ }
217
+ }
218
+
219
+ type RequestConnection = { connection?: PgConnection; queue: Promise<unknown>; ended: boolean }
220
+ // A connection whose state is unknown, discarded; a failure to release it
221
+ // too changes nothing.
222
+ const discardConnection = (connection?: PgConnection) => connection?.release(true).catch(() => {})
223
+
224
+ function requestConnections(connect: PgConnect) {
225
+ const requests = new AsyncLocalStorage<RequestConnection>()
226
+ async function withConnection<T>(work: (db: PgConnection) => Promise<T>): Promise<T> {
227
+ const request = requests.getStore()
228
+ if (!request || request.ended) {
229
+ const connection = await connect()
230
+ let result: T
231
+ try { result = await work(connection) }
232
+ catch (error) { await discardConnection(connection); throw error }
233
+ await connection.release()
234
+ return result
235
+ }
236
+ // Serialize transactions on the leased connection, never interleave BEGINs
237
+ // from concurrent Blob/catalog tasks. Remote Blob reads remain concurrent.
238
+ const result = request.queue.then(async () => {
239
+ const connection = request.connection ??= await connect()
240
+ try { return await work(connection) }
241
+ catch (error) {
242
+ delete request.connection
243
+ await discardConnection(connection)
244
+ throw error
245
+ }
246
+ })
247
+ request.queue = result.catch(() => {})
248
+ return result
249
+ }
250
+ async function withRequest<T>(work: () => Promise<T>): Promise<T> {
251
+ if (requests.getStore()) return work()
252
+ const request: RequestConnection = { queue: Promise.resolve(), ended: false }
253
+ let failed = false
254
+ try { return await requests.run(request, work) }
255
+ catch (error) { failed = true; throw error }
256
+ finally {
257
+ request.ended = true
258
+ await request.queue
259
+ if (failed) await discardConnection(request.connection)
260
+ else await request.connection?.release()
261
+ }
262
+ }
263
+ return { withConnection, withRequest }
264
+ }
265
+
266
+ // Exposed for parity tests against real PostgreSQL semantics via PGlite.
267
+ export async function openPostgresManagedDb(leased: PgConnect, options: ManagedDbOptions = {}, reuseConnections = false): Promise<ManagedDb> {
268
+ // Each statement told in its request's Server-Timing (request-timing.ts).
269
+ const connect: PgConnect = async () => {
270
+ const connection = await leased()
271
+ return { query: (sql, params) => { countStatement(); return connection.query(sql, params) }, release: discard => connection.release(discard) }
272
+ }
273
+ const initial = await connect()
274
+ try { await initialize(initial) } catch (err) { await discardConnection(initial); throw err }
275
+ await initial.release()
276
+ const { withConnection, withRequest } = requestConnections(connect)
277
+ const context = new AsyncLocalStorage<PgConnection>()
278
+ let closed = false
279
+ const driver: ManagedSqlDriver = {
280
+ prepare(source) {
281
+ const { sql, names } = postgresSql(source)
282
+ async function query(args: unknown[]) {
283
+ const db = context.getStore()
284
+ if (!db) throw new Error('Managed query outside transaction')
285
+ const values = names.length > 0 ? names.map(name => (args[0] as Record<string, unknown>)[name])
286
+ : args.length === 1 && typeof args[0] === 'object' && args[0] !== null ? [] : args
287
+ const result = await db.query(sql, values)
288
+ // Postgres int8 is returned as text by node-postgres/Neon. All store
289
+ // numbers are JS safe integers (timestamps, IDs, sizes and sequences).
290
+ for (const field of result.fields ?? []) {
291
+ if (field.dataTypeID !== 20) continue
292
+ for (const row of result.rows) {
293
+ if (row[field.name] == null) continue
294
+ const value = Number(row[field.name])
295
+ if (!Number.isSafeInteger(value)) throw new Error('Managed integer exceeds safe range')
296
+ row[field.name] = value
297
+ }
298
+ }
299
+ return result
300
+ }
301
+ return {
302
+ get: async (...args) => (await query(args)).rows[0],
303
+ all: async (...args) => (await query(args)).rows,
304
+ run: async (...args) => ({ changes: (await query(args)).rowCount ?? 0 }),
305
+ }
306
+ },
307
+ async scope(write, work, { lock = write, statement = false } = {}) {
308
+ if (closed) throw new Error('Managed database is closed')
309
+ let committed = false
310
+ try { return await withConnection(async db => {
311
+ if (statement) return context.run(db, work)
312
+ let commitAttempted = false
313
+ try {
314
+ await db.query(write ? 'BEGIN' : 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY')
315
+ if (lock) await db.query(LOCK)
316
+ const result = await context.run(db, work)
317
+ commitAttempted = true
318
+ await db.query('COMMIT')
319
+ committed = true
320
+ return result
321
+ } catch (err) {
322
+ await db.query('ROLLBACK').catch(() => {})
323
+ if (write && commitAttempted) throw new Error('Managed commit outcome is uncertain', { cause: err })
324
+ throw err
325
+ }
326
+ }) } catch (error) {
327
+ if (write && committed) throw new Error('Managed commit outcome is uncertain', { cause: error })
328
+ throw error
329
+ }
330
+ },
331
+ close() { closed = true },
332
+ }
333
+ const methods = scopeManagedMethods(createManagedMethods(driver, options), driver)
334
+ if (reuseConnections) methods.withRequest = withRequest
335
+ return methods
336
+ }
337
+
338
+ // Idle connections stay open this long between leases, so a warm instance's
339
+ // requests and feed polls (three seconds apart) skip the TLS, WebSocket and
340
+ // Postgres handshake a new connection repeats.
341
+ const NEON_POOL_IDLE_MS = 5_000
342
+
343
+ type NeonPoolClient = {
344
+ query: PgConnection['query']
345
+ release(discard?: boolean): void
346
+ on(event: string, listener: (...args: unknown[]) => void): void
347
+ }
348
+ export type NeonPool = {
349
+ connect(): Promise<NeonPoolClient>
350
+ end(): Promise<void>
351
+ on(event: string, listener: (...args: unknown[]) => void): void
352
+ }
353
+
354
+ // `attachPool` is Vercel's attachDatabasePool on serverless instances: each
355
+ // release keeps the invocation alive until idle connections have closed, so
356
+ // no socket survives a frozen instance.
357
+ export async function openNeonManagedDb(url: string, options: ManagedDbOptions = {}, attachPool?: (pool: NeonPool) => void): Promise<ManagedDb> {
358
+ // Reuse the e2e optional-driver boundary.
359
+ const { Pool, neonConfig } = await import('../server-e2e/neon-driver.ts') as unknown as {
360
+ Pool: new (config: { connectionString: string; max: number; idleTimeoutMillis: number }) => NeonPool
361
+ neonConfig: { webSocketConstructor: typeof WebSocket }
362
+ }
363
+ neonConfig.webSocketConstructor = WebSocket
364
+ // Leases stay unbounded, one per request or operation as before: a cap would
365
+ // stall a request that holds one while it awaits work needing another.
366
+ const pool = new Pool({ connectionString: url, max: Infinity, idleTimeoutMillis: NEON_POOL_IDLE_MS })
367
+ // The pool evicts an idle connection the server closed. Neither that nor a
368
+ // remote disconnect while leased may become an unhandled EventEmitter error;
369
+ // a leased one must instead reject its next query, and is then discarded.
370
+ pool.on('error', () => {})
371
+ attachPool?.(pool)
372
+ const failed = new WeakSet<NeonPoolClient>(), watched = new WeakSet<NeonPoolClient>()
373
+ let ending: Promise<void> | undefined
374
+ const end = () => ending ??= pool.end()
375
+ let db: ManagedDb
376
+ try {
377
+ db = await openPostgresManagedDb(async () => {
378
+ // A lease's wait told in its request's Server-Timing: a new connection's
379
+ // TLS, WebSocket and Postgres handshake, where the pool had none idle.
380
+ const client = await timed('conn', () => pool.connect())
381
+ if (!watched.has(client)) { watched.add(client); client.on('error', () => { failed.add(client) }) }
382
+ return { query: (sql, params) => client.query(sql, params),
383
+ release: discard => Promise.try(() => client.release(discard === true || failed.has(client))) }
384
+ }, options, true)
385
+ } catch (err) { await end().catch(() => {}); throw err }
386
+ const close = db.close
387
+ return { ...db, async close() { try { await close() } finally { await end() } } }
388
+ }
@@ -0,0 +1,253 @@
1
+ import { DEPENDENCY_REVIEW_SCHEMA } from './dependency-reviews.ts'
2
+ import { LINK_REPORT_SCHEMA } from './link-reports.ts'
3
+ import { REPOSITORY_ALIAS_SCHEMA } from './repository-aliases.ts'
4
+ import { WORKSPACE_SHARE_SCHEMA } from './workspace-shares.ts'
5
+ import { TEAM_NPM_SCOPE_SCHEMA } from './team-npm-scopes.ts'
6
+ import { GITHUB_LINK_SCHEMA } from './github-links.ts'
7
+
8
+ // Created after the column migration, which predates it on older databases.
9
+ export const VIEW_SESSION_INDEX = 'CREATE INDEX IF NOT EXISTS managed_session_viewer_idx ON managed_session(viewer_session);'
10
+ // What a team's scopes join reports and bundles on: their repository, and the
11
+ // directory in it. Created after the column migrations, as above.
12
+ export const REPO_UPLOAD_INDEXES = `CREATE INDEX IF NOT EXISTS managed_report_repo_idx ON managed_report(repo_id, repo_directory);
13
+ CREATE INDEX IF NOT EXISTS managed_bundle_repo_idx ON managed_bundle(repo_id, repo_directory);`
14
+
15
+ // Shared by listing, access checks, and permission aggregation. A team sees
16
+ // reports rooted at its path or below it. Literal substring comparison keeps
17
+ // separators, case, and SQL wildcard characters significant.
18
+ export const withinTeamPath = (path: string) => `(tr.path IS NULL OR tr.path = ''
19
+ OR ${path} = tr.path
20
+ OR substr(${path}, 1, length(tr.path) + 1) = tr.path || '/')`
21
+
22
+ // Whether a scope of a non-hidden team of `user` (a placeholder, or a column)
23
+ // holds the repository directory of `row`, the alias of a row with repo_id
24
+ // and repo_directory (withinTeamPath).
25
+ export const inUserTeamScope = (user: string, row: string) => `EXISTS (SELECT 1 FROM managed_team_repo tr
26
+ JOIN managed_team_user tu ON tu.team_id = tr.team_id
27
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
28
+ WHERE tu.user_id = ${user} AND tr.repo_id = ${row}.repo_id AND ${withinTeamPath(`${row}.repo_directory`)})`
29
+
30
+ export const MANAGED_SCHEMA = `
31
+ CREATE TABLE IF NOT EXISTS managed_user (
32
+ id TEXT PRIMARY KEY,
33
+ github_user_id INTEGER NOT NULL UNIQUE,
34
+ login TEXT NOT NULL,
35
+ name TEXT,
36
+ avatar_url TEXT,
37
+ role TEXT NOT NULL DEFAULT 'none',
38
+ -- GitHub user-to-server token, persisted so the repositories page can list
39
+ -- the user's repos (GET /user/repos) on demand. Refresh token + expiry are
40
+ -- null for non-expiring tokens (GitHub App with expiring tokens disabled).
41
+ gh_access_token TEXT,
42
+ gh_refresh_token TEXT,
43
+ gh_token_expires_at INTEGER,
44
+ created_at INTEGER NOT NULL,
45
+ updated_at INTEGER NOT NULL,
46
+ -- Presence is independent of admin edits and background token refreshes.
47
+ -- NULL for legacy accounts until a known session authenticates them.
48
+ last_seen_at INTEGER
49
+ ) STRICT;
50
+
51
+ CREATE TABLE IF NOT EXISTS managed_session (
52
+ id TEXT PRIMARY KEY,
53
+ user_id TEXT NOT NULL REFERENCES managed_user(id) ON DELETE CASCADE,
54
+ csrf_token TEXT NOT NULL,
55
+ created_at INTEGER NOT NULL,
56
+ expires_at INTEGER NOT NULL,
57
+ -- Private X25519 JWK that this session's uploads are sealed to (see
58
+ -- common/managed/upload-seal.ts). Created on first use.
59
+ upload_key TEXT,
60
+ -- An administrator's read-only view as user_id: the admin's own session,
61
+ -- which must stay valid. Ending that session ends the view.
62
+ viewer_session TEXT REFERENCES managed_session(id) ON DELETE CASCADE
63
+ ) STRICT;
64
+
65
+ CREATE INDEX IF NOT EXISTS managed_session_user_idx ON managed_session(user_id);
66
+ CREATE INDEX IF NOT EXISTS managed_session_expires_idx ON managed_session(expires_at);
67
+
68
+ -- Repositories selected to operate on. Keyed by GitHub's numeric repo id
69
+ -- (stable across renames). The row carries everything needed to read the repo's
70
+ -- contents server-side later: installation_id mints an App installation token
71
+ -- (Contents: Read) for PRIVATE repos — NULL means a PUBLIC repo readable without
72
+ -- the App — and full_name + default_branch locate the contents. added_by is the
73
+ -- selector, nulled (not cascaded) if that user is removed so the selection
74
+ -- survives.
75
+ CREATE TABLE IF NOT EXISTS managed_selected_repo (
76
+ repo_id INTEGER PRIMARY KEY,
77
+ full_name TEXT NOT NULL,
78
+ is_private INTEGER NOT NULL,
79
+ installation_id INTEGER,
80
+ default_branch TEXT NOT NULL,
81
+ -- Live browser hint; independent of the default discovered at selection.
82
+ cached_default_branch TEXT,
83
+ html_url TEXT NOT NULL,
84
+ added_by TEXT REFERENCES managed_user(id) ON DELETE SET NULL,
85
+ added_at INTEGER NOT NULL,
86
+ updated_at INTEGER NOT NULL,
87
+ active INTEGER NOT NULL DEFAULT 1,
88
+ -- Its pull requests' dependencies reviewed (repository-dependency-reviews.ts):
89
+ -- as many published reviews required of each version, and the commit at
90
+ -- whose lockfiles' versions none is (null for none).
91
+ dependency_review INTEGER NOT NULL DEFAULT 0,
92
+ dependency_reviews_required INTEGER NOT NULL DEFAULT 1,
93
+ dependency_review_since TEXT
94
+ ) STRICT;
95
+
96
+ CREATE INDEX IF NOT EXISTS selected_repo_full_name_idx ON managed_selected_repo(full_name);
97
+
98
+ -- Bundles uploaded to the server (the "Manage bundles" page). Like reports, the
99
+ -- bytes are stored in the clear (blob-store, keyed by this opaque uuid id) for
100
+ -- the server to operate on. integrity is the content hash (sha512-<base64>,
101
+ -- byte-identical to the client's) so re-uploading the same bytes dedupes (UNIQUE);
102
+ -- it is also the key a report's bundleHashes match to auto-link.
103
+ -- uploaded_by / repo_id are the (nullable) user + repo links, both nulled (not
104
+ -- cascaded) when the referenced user / selected repo goes away.
105
+ CREATE TABLE IF NOT EXISTS managed_bundle (
106
+ id TEXT PRIMARY KEY,
107
+ slug TEXT NOT NULL,
108
+ integrity TEXT NOT NULL UNIQUE,
109
+ filename TEXT NOT NULL,
110
+ kind TEXT,
111
+ byte_size INTEGER NOT NULL,
112
+ uploaded_by TEXT REFERENCES managed_user(id) ON DELETE SET NULL,
113
+ -- Durable snapshot of the uploader's login at upload time, so "who uploaded
114
+ -- this" survives the uploader being removed (when uploaded_by nulls out).
115
+ uploaded_by_login TEXT,
116
+ repo_id INTEGER REFERENCES managed_selected_repo(repo_id) ON DELETE SET NULL,
117
+ repo_directory TEXT NOT NULL DEFAULT '',
118
+ visible INTEGER NOT NULL DEFAULT 1,
119
+ uploaded_at INTEGER NOT NULL,
120
+ -- 'upload' or 'build' (generated on this server). A server build of bytes
121
+ -- already stored promotes the row to 'build'; NULL predates the column.
122
+ provenance TEXT,
123
+ -- JSON {preset, conditions, platforms} of a JS/TS server build; NULL otherwise.
124
+ build_conditions TEXT
125
+ ) STRICT;
126
+
127
+ CREATE INDEX IF NOT EXISTS managed_bundle_uploaded_at_idx ON managed_bundle(uploaded_at);
128
+
129
+ -- Reports uploaded to the server (the "Manage reports" page). A managed server
130
+ -- is TRUSTED, so the bytes are stored in the clear (blob-store, keyed by this
131
+ -- opaque uuid id) for the server to operate on later; this row carries the
132
+ -- metadata + attribution. uploaded_by / repo_id are the (nullable) user + repo
133
+ -- links, nulled (not cascaded) when the user / selected repo goes away. bundle_id
134
+ -- is the (nullable) auto-resolved link to a stored bundle; bundle_integrity is
135
+ -- the report's declared primary bundle (from its bundleHashes), kept so a later
136
+ -- bundle upload of that integrity can re-link.
137
+ CREATE TABLE IF NOT EXISTS managed_report (
138
+ id TEXT PRIMARY KEY,
139
+ slug TEXT NOT NULL,
140
+ filename TEXT NOT NULL,
141
+ content_type TEXT NOT NULL,
142
+ byte_size INTEGER NOT NULL,
143
+ sha256 TEXT NOT NULL,
144
+ uploaded_by TEXT REFERENCES managed_user(id) ON DELETE SET NULL,
145
+ -- Durable snapshot of the uploader's login (see managed_bundle).
146
+ uploaded_by_login TEXT,
147
+ repo_id INTEGER REFERENCES managed_selected_repo(repo_id) ON DELETE SET NULL,
148
+ repo_directory TEXT NOT NULL DEFAULT '',
149
+ repo_embedded INTEGER NOT NULL DEFAULT 0,
150
+ analyzer TEXT,
151
+ visible INTEGER NOT NULL DEFAULT 0,
152
+ bundle_id TEXT REFERENCES managed_bundle(id) ON DELETE SET NULL,
153
+ bundle_integrity TEXT,
154
+ uploaded_at INTEGER NOT NULL
155
+ ) STRICT;
156
+
157
+ CREATE INDEX IF NOT EXISTS managed_report_uploaded_at_idx ON managed_report(uploaded_at);
158
+ CREATE INDEX IF NOT EXISTS managed_report_hash_idx ON managed_report(sha256, uploaded_at, id);
159
+ CREATE INDEX IF NOT EXISTS managed_report_bundle_integrity_idx ON managed_report(bundle_integrity);
160
+ CREATE INDEX IF NOT EXISTS managed_report_bundle_hash_idx ON managed_report(bundle_id, sha256);
161
+
162
+ -- Per-finding triage annotations — the managed (trusted-plaintext) counterpart
163
+ -- of the client's localStorage triage map, keyed the same way: by finding id
164
+ -- alone, not by report. Reports mostly repeat one another (a re-scan of the
165
+ -- same code carries the same finding ids) and a finding's triage is shared by
166
+ -- every report that carries it; which ids a viewer may read or write is
167
+ -- decided per report at the endpoint, not here. The wire shape lives in
168
+ -- common/managed/triage.ts. Whole-entry replace, NULL columns are unset;
169
+ -- flagged is tri-state: NULL unset / 1 flagged / 0 an explicit un-flag
170
+ -- tombstone. A cleared entry keeps its row with every field NULL — a
171
+ -- tombstone a reader adopts as "cleared", where a missing row means "never
172
+ -- annotated" (so a stale client copy can't resurrect a teammate's clear).
173
+ -- updated_by is the last writer (nulled when that user is removed);
174
+ -- updated_by_login is the durable login snapshot (see managed_bundle).
175
+ CREATE TABLE IF NOT EXISTS managed_finding_triage (
176
+ finding_id TEXT PRIMARY KEY,
177
+ color TEXT,
178
+ triage TEXT,
179
+ comment TEXT,
180
+ fix TEXT,
181
+ flagged INTEGER,
182
+ updated_by TEXT REFERENCES managed_user(id) ON DELETE SET NULL,
183
+ updated_by_login TEXT,
184
+ updated_at INTEGER NOT NULL
185
+ ) STRICT;
186
+
187
+ -- The trail behind managed_finding_triage: one row per write that CHANGED an entry,
188
+ -- holding the entry as written (every field NULL = a clear), who wrote it and
189
+ -- when. managed_finding_triage stays the current-state projection reads hit; this is
190
+ -- walked only for a finding's history. The wire is whole-entry replace, so a
191
+ -- snapshot per write is exactly what arrived and "what changed" is the diff
192
+ -- against the previous row for the same id, computed on read. batch_id groups
193
+ -- the rows of one request. seq is the rowid: a total order that breaks ties
194
+ -- on at. actor_id / actor_login follow the uploaded_by / uploaded_by_login
195
+ -- convention (live account, durable login snapshot). Everything is kept by
196
+ -- default — the trail is the record; an operator may bound it per finding
197
+ -- (TRIAGE_HISTORY_LIMIT), in which case a finding's older events are trimmed
198
+ -- as new ones land. An id no report carries any more is the tombstone GC's
199
+ -- concern.
200
+ CREATE TABLE IF NOT EXISTS managed_finding_triage_event (
201
+ seq INTEGER PRIMARY KEY,
202
+ finding_id TEXT NOT NULL,
203
+ batch_id TEXT NOT NULL,
204
+ color TEXT,
205
+ triage TEXT,
206
+ comment TEXT,
207
+ fix TEXT,
208
+ flagged INTEGER,
209
+ actor_id TEXT REFERENCES managed_user(id) ON DELETE SET NULL,
210
+ actor_login TEXT,
211
+ at INTEGER NOT NULL
212
+ ) STRICT;
213
+ CREATE INDEX IF NOT EXISTS finding_triage_event_finding_idx ON managed_finding_triage_event(finding_id, seq);
214
+ CREATE INDEX IF NOT EXISTS finding_triage_event_actor_at_idx ON managed_finding_triage_event(actor_id, at);
215
+
216
+ -- Teams group users + repos for access scoping. Hidden teams grant no access;
217
+ -- the two link tables below carry the many-many relations.
218
+ CREATE TABLE IF NOT EXISTS managed_team (
219
+ id TEXT PRIMARY KEY,
220
+ slug TEXT NOT NULL,
221
+ name TEXT NOT NULL UNIQUE,
222
+ hidden INTEGER NOT NULL DEFAULT 0,
223
+ dependency_review INTEGER NOT NULL DEFAULT 0,
224
+ created_at INTEGER NOT NULL,
225
+ updated_at INTEGER NOT NULL
226
+ ) STRICT;
227
+
228
+ -- Team <-> repo, many-many, with an OPTIONAL path (a subpath of the repo the
229
+ -- team is scoped to; empty path = the whole repo). Distinct paths can coexist;
230
+ -- adding the whole repo replaces them. CASCADE removes links with either side. repo_id
231
+ -- references the selected (operate-on) repos.
232
+ CREATE TABLE IF NOT EXISTS managed_team_repo (
233
+ team_id TEXT NOT NULL REFERENCES managed_team(id) ON DELETE CASCADE,
234
+ repo_id INTEGER NOT NULL REFERENCES managed_selected_repo(repo_id) ON DELETE CASCADE,
235
+ path TEXT NOT NULL DEFAULT '',
236
+ PRIMARY KEY (team_id, repo_id, path)
237
+ ) STRICT;
238
+
239
+ CREATE INDEX IF NOT EXISTS team_repo_repo_idx ON managed_team_repo(repo_id);
240
+
241
+ -- Team <-> user, many-many, with per-membership visibility permissions (see
242
+ -- common/managed/permissions.ts) — view_dependencies / view_security, both
243
+ -- default 0 (off). CASCADE so the membership dies with either side.
244
+ CREATE TABLE IF NOT EXISTS managed_team_user (
245
+ team_id TEXT NOT NULL REFERENCES managed_team(id) ON DELETE CASCADE,
246
+ user_id TEXT NOT NULL REFERENCES managed_user(id) ON DELETE CASCADE,
247
+ view_dependencies INTEGER NOT NULL DEFAULT 0,
248
+ view_security INTEGER NOT NULL DEFAULT 0,
249
+ PRIMARY KEY (team_id, user_id)
250
+ ) STRICT;
251
+
252
+ CREATE INDEX IF NOT EXISTS team_user_user_idx ON managed_team_user(user_id);
253
+ ` + WORKSPACE_SHARE_SCHEMA + LINK_REPORT_SCHEMA + REPOSITORY_ALIAS_SCHEMA + TEAM_NPM_SCOPE_SCHEMA + DEPENDENCY_REVIEW_SCHEMA + GITHUB_LINK_SCHEMA
@@ -0,0 +1,22 @@
1
+ // Table identifiers are code constants. Renames retain rows and foreign keys;
2
+ // an ambiguous old/new pair must be resolved before the server can start.
3
+ const MANAGED_TABLE_RENAMES = [
4
+ ['selected_repo', 'managed_selected_repo'],
5
+ ['team_repo', 'managed_team_repo'],
6
+ ['team_user', 'managed_team_user'],
7
+ ['finding_triage', 'managed_finding_triage'],
8
+ ['finding_triage_event', 'managed_finding_triage_event'],
9
+ ['finding_comment', 'managed_finding_comment'],
10
+ ['finding_comment_event', 'managed_finding_comment_event'],
11
+ ] as const
12
+
13
+ export function managedTableRenames(tables: Set<string>) {
14
+ // A fresh installation must not claim similarly named unrelated tables in
15
+ // a shared database. managed_user anchors an existing managed installation.
16
+ if (!tables.has('managed_user')) return []
17
+ const renames = MANAGED_TABLE_RENAMES.filter(([from]) => tables.has(from))
18
+ for (const [from, to] of renames) {
19
+ if (tables.has(to)) throw new Error(`Cannot migrate managed tables: both ${from} and ${to} exist`)
20
+ }
21
+ return renames
22
+ }