@preventive/triage 1.0.0-alpha.60 → 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 (132) hide show
  1. package/common/default-scan-models.ts +6 -5
  2. package/common/managed/comments.ts +9 -0
  3. package/out/activity.js +1 -1
  4. package/out/chunk-6CCSTJWB.js +1 -0
  5. package/out/{chunk-VZJIHHTQ.js → chunk-B3FNMHOE.js} +1 -1
  6. package/out/chunk-BNH52UHC.js +2 -0
  7. package/out/chunk-BRO77PQY.js +42 -0
  8. package/out/chunk-GRGIZOTP.js +4 -0
  9. package/out/chunk-JJK5OZG2.js +15 -0
  10. package/out/chunk-OFZYEWBH.js +244 -0
  11. package/out/{chunk-YGRRXC2L.js → chunk-OIERSXON.js} +1 -1
  12. package/out/{chunk-TZS7KERJ.js → chunk-QCOGVL37.js} +1 -1
  13. package/out/{chunk-6VDDCFHT.js → chunk-W3QFV4SP.js} +1 -1
  14. package/out/chunk-W6VOKW2N.js +12 -0
  15. package/out/chunk-ZQNEWVGG.js +1 -0
  16. package/out/client-managed.js +2 -2
  17. package/out/compare.js +19 -14
  18. package/out/dialogs.js +38 -38
  19. package/out/graph.js +12 -12
  20. package/out/index.html +5 -5
  21. package/out/scan.js +1 -1
  22. package/out/terminal.js +12 -12
  23. package/out/view.css +1 -1
  24. package/out/view.js +4 -4
  25. package/package.json +9 -6
  26. package/server-managed/activity.ts +23 -43
  27. package/server-managed/agent-merges.ts +2 -2
  28. package/server-managed/blob-store.ts +10 -1
  29. package/server-managed/bundle-advisories.ts +3 -2
  30. package/server-managed/bundle-advisory-inventory.ts +1 -1
  31. package/server-managed/bundle-build-worker.js +41 -6
  32. package/server-managed/bundle-build.ts +18 -10
  33. package/server-managed/bundle-cache.ts +29 -41
  34. package/server-managed/bundle-catalog.ts +11 -11
  35. package/server-managed/bundle-commits.ts +9 -16
  36. package/server-managed/bundle-dependency-reviews.ts +5 -11
  37. package/server-managed/bundle-summary-cache.ts +23 -14
  38. package/server-managed/bundle-validation.ts +2 -1
  39. package/server-managed/combined.ts +1 -5
  40. package/server-managed/comments.ts +15 -28
  41. package/server-managed/commit-coauthors.ts +4 -5
  42. package/server-managed/commit-lockfiles.ts +6 -5
  43. package/server-managed/comparison.ts +3 -5
  44. package/server-managed/config.ts +1 -2
  45. package/server-managed/db-methods.ts +163 -244
  46. package/server-managed/db-neon.ts +82 -178
  47. package/server-managed/db-schema.ts +15 -0
  48. package/server-managed/db.ts +5 -11
  49. package/server-managed/dependabot-access.ts +2 -1
  50. package/server-managed/dependabot-alerts.ts +7 -12
  51. package/server-managed/dependency-review-comments.ts +7 -13
  52. package/server-managed/dependency-reviews.ts +14 -15
  53. package/server-managed/github-accounts.ts +4 -5
  54. package/server-managed/github-actions.ts +6 -6
  55. package/server-managed/github-app.ts +19 -48
  56. package/server-managed/github-graphql.ts +5 -2
  57. package/server-managed/github-issue-links.ts +62 -42
  58. package/server-managed/github-issue-oauth.ts +7 -24
  59. package/server-managed/github-issues.ts +9 -7
  60. package/server-managed/github-link-oauth.ts +7 -20
  61. package/server-managed/github-oauth.ts +38 -12
  62. package/server-managed/github-pulls.ts +37 -26
  63. package/server-managed/github-requests.ts +21 -8
  64. package/server-managed/github-values.ts +26 -0
  65. package/server-managed/history-windows.ts +7 -7
  66. package/server-managed/http.ts +495 -554
  67. package/server-managed/index.ts +6 -6
  68. package/server-managed/link-reports.ts +6 -19
  69. package/server-managed/lockfile-scope.ts +1 -1
  70. package/server-managed/management.ts +14 -3
  71. package/server-managed/npm-delta.ts +22 -57
  72. package/server-managed/npm-insights.ts +31 -26
  73. package/server-managed/npm-kept.ts +9 -8
  74. package/server-managed/npm-loads.ts +2 -7
  75. package/server-managed/npm-manifest.ts +6 -4
  76. package/server-managed/npm-packages.ts +17 -9
  77. package/server-managed/npm-patch.ts +8 -16
  78. package/server-managed/npm-provenance.ts +12 -8
  79. package/server-managed/npm-risk.ts +9 -7
  80. package/server-managed/object-storage-disk.ts +2 -3
  81. package/server-managed/object-storage-vercel.ts +15 -11
  82. package/server-managed/object-storage.ts +7 -0
  83. package/server-managed/pretty-print.ts +8 -19
  84. package/server-managed/public-workspace.ts +50 -46
  85. package/server-managed/pull-comment-reviews.ts +2 -2
  86. package/server-managed/pull-dependencies.ts +20 -31
  87. package/server-managed/pull-dependency-reviews.ts +17 -24
  88. package/server-managed/pull-reviews.ts +4 -7
  89. package/server-managed/queue.ts +14 -0
  90. package/server-managed/release-commits.ts +9 -8
  91. package/server-managed/rename-diff.ts +17 -60
  92. package/server-managed/report-migration.ts +5 -8
  93. package/server-managed/report-sources.ts +6 -10
  94. package/server-managed/report-store.ts +2 -10
  95. package/server-managed/repository-actions.ts +7 -8
  96. package/server-managed/repository-agents.ts +31 -57
  97. package/server-managed/repository-aliases.ts +3 -9
  98. package/server-managed/repository-browser.ts +18 -16
  99. package/server-managed/repository-changes.ts +33 -37
  100. package/server-managed/repository-code.ts +5 -5
  101. package/server-managed/repository-dependency-reviews.ts +6 -13
  102. package/server-managed/repository-discovery.ts +2 -1
  103. package/server-managed/repository-history.ts +47 -51
  104. package/server-managed/repository-issues.ts +59 -30
  105. package/server-managed/repository-pulls.ts +7 -12
  106. package/server-managed/repository-pulse.ts +51 -45
  107. package/server-managed/repository-risk-assess.ts +5 -2
  108. package/server-managed/repository-risk-audit.ts +1 -1
  109. package/server-managed/repository-risk-read.ts +6 -6
  110. package/server-managed/repository-risk.ts +32 -40
  111. package/server-managed/repository-squashes.ts +7 -15
  112. package/server-managed/request-timing.ts +1 -1
  113. package/server-managed/sql.ts +18 -0
  114. package/server-managed/storage-encryption.ts +5 -7
  115. package/server-managed/team-app.ts +4 -7
  116. package/server-managed/team-npm-scopes.ts +5 -8
  117. package/server-managed/team-reports.ts +15 -15
  118. package/server-managed/type-only-proof.js +108 -0
  119. package/server-managed/type-only-worker.js +26 -14
  120. package/server-managed/type-only.ts +72 -62
  121. package/server-managed/uploads.ts +3 -3
  122. package/server-managed/upstream-cache.ts +5 -7
  123. package/server-managed/worker-turns.ts +76 -0
  124. package/server-managed/workspace-shares.ts +1 -2
  125. package/out/chunk-2SY4PYUQ.js +0 -4
  126. package/out/chunk-4HI2MSAV.js +0 -17
  127. package/out/chunk-4TQKM3JC.js +0 -42
  128. package/out/chunk-EEQHVKR3.js +0 -1
  129. package/out/chunk-HNQNDNIE.js +0 -12
  130. package/out/chunk-OFPDMZJF.js +0 -244
  131. package/out/chunk-OQRSIBSC.js +0 -1
  132. package/out/chunk-YTO6AQZM.js +0 -2
@@ -19,12 +19,13 @@ import { type BundleBuildLeaseStore, bundleBuildLeaseMethods } from './bundle-bu
19
19
  import { type UpstreamCacheStore, upstreamCacheMethods } from './upstream-cache.ts'
20
20
  import { type TeamAppSummaryStore, teamAppSummaryMethods } from './team-app-summaries.ts'
21
21
  import { type ImportTriageStore, importTriageMethods } from './import-triage.ts'
22
- import type { ManagedSql } from './sql.ts'
22
+ import { type ManagedSql, jsonRows } from './sql.ts'
23
23
  import { type WorkspaceShareStore, workspaceShareMethods } from './workspace-shares.ts'
24
24
  import { ManagedMutationError, type ManagementStore, managementMethods } from './management.ts'
25
25
  import { type ManagementCatalogStore, managementCatalogMethods } from './management-catalog.ts'
26
26
  import { type StorageKey } from '../server-common/storage-crypto.ts'
27
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'
28
29
 
29
30
  // A managed user identity (the subset of GitHub's `GET /user` we keep). Input
30
31
  // to the upsert; `githubUserId` is the provider lookup key, never exposed to
@@ -570,30 +571,24 @@ type SessionRow = {
570
571
  uid: string; login: string; name: string | null; avatar: string | null; role: Role
571
572
  }
572
573
  type ViewSessionRow = SessionRow & { viewerId: string; viewerLogin: string; viewerName: string | null }
574
+ const storedUser = (row: Pick<SessionRow, 'uid' | 'login' | 'name' | 'avatar' | 'role'>): StoredUser =>
575
+ ({ id: row.uid, login: row.login, name: row.name, avatarUrl: row.avatar, role: row.role })
573
576
  const ownSession = (row: SessionRow) => ({
574
577
  session: { id: row.id, userId: row.uid, csrfToken: row.csrf, expiresAt: row.exp, uploadKey: row.uploadKey },
575
- user: { id: row.uid, login: row.login, name: row.name, avatarUrl: row.avatar, role: row.role },
576
- })
577
- const viewSession = (row: ViewSessionRow) => ({
578
- session: { id: row.id, userId: row.uid, csrfToken: row.csrf, expiresAt: row.exp, uploadKey: row.uploadKey,
579
- viewer: { id: row.viewerId, login: row.viewerLogin, name: row.viewerName } },
580
- user: { id: row.uid, login: row.login, name: row.name, avatarUrl: row.avatar, role: row.role },
578
+ user: storedUser(row),
581
579
  })
580
+ const viewSession = (row: ViewSessionRow) => {
581
+ const { session, user } = ownSession(row)
582
+ return { session: { ...session, viewer: { id: row.viewerId, login: row.viewerLogin, name: row.viewerName } }, user }
583
+ }
582
584
 
583
585
  type UserRow = { id: string; login: string; name: string | null; role: Role; created: number; lastSeen: number | null; lastActivity: number | null }
584
586
 
585
- // Rows a statement gathered into one JSON array value (json_group_array): its
586
- // text on SQLite, parsed already on Postgres, where none gather as NULL.
587
- const jsonRows = <T>(value: unknown): T[] => value == null ? [] : (typeof value === 'string' ? JSON.parse(value) : value) as T[]
588
-
589
- // Shared by listing, access checks, and permission aggregation. A team sees
590
- // reports rooted at its path or below it. Literal substring comparison keeps
591
- // separators, case, and SQL wildcard characters significant.
592
- const REPORT_IN_TEAM_PATH_SQL = `(tr.path IS NULL OR tr.path = ''
593
- OR r.repo_directory = tr.path
594
- OR substr(r.repo_directory, 1, length(tr.path) + 1) = tr.path || '/')`
587
+ // Whether a write changed any row.
588
+ const anyChanged = (result: { changes: number | bigint }) => Number(result.changes) > 0
595
589
 
596
- const BUNDLE_IN_TEAM_PATH_SQL = REPORT_IN_TEAM_PATH_SQL.replaceAll('r.repo_directory', 'b.repo_directory')
590
+ const REPORT_IN_TEAM_PATH_SQL = withinTeamPath('r.repo_directory')
591
+ const BUNDLE_IN_TEAM_PATH_SQL = withinTeamPath('b.repo_directory')
597
592
 
598
593
  // What a user's team catalog reads (listTeamsForUser), for `user`: a
599
594
  // placeholder, or a column of a statement reading it with more. Their teams,
@@ -666,36 +661,60 @@ function reportCatalogKey(r: CatalogReportRow, role: string, links: string): str
666
661
 
667
662
  // A user's team catalog from its rows, `links` the link reports' revision.
668
663
  function userTeams(teams: UserTeamRows['teams'], scopes: UserTeamRows['scopes'], links: string, reports: UserTeamRows['reports'], bundles: UserTeamRows['bundles']): UserTeam[] {
669
- const reportsByTeam = new Map<string, UserTeamReport[]>()
670
- for (const r of reports) {
671
- const list = reportsByTeam.get(r.teamId) ?? []
672
- list.push({ id: r.id, slug: r.slug, filename: r.filename, visible: r.visible === 1, analyzer: r.analyzer, repoFullName: r.repoFullName, repoDirectory: r.repoDirectory,
673
- cacheKey: reportCatalogKey(r, r.role, links) })
674
- reportsByTeam.set(r.teamId, list)
675
- }
676
- const bundlesByTeam = new Map<string, UserTeamBundle[]>()
677
- for (const b of bundles) {
678
- const list = bundlesByTeam.get(b.teamId) ?? []
679
- list.push({ id: b.id, slug: b.slug, integrity: b.integrity, filename: b.filename, visible: b.visible === 1,
680
- kind: b.kind, byteSize: b.byteSize, repoId: b.repoId, repoDirectory: b.repoDirectory, repoFullName: b.repoFullName, provenance: b.provenance })
681
- bundlesByTeam.set(b.teamId, list)
682
- }
683
- return teams.map((t) => ({
684
- id: t.id, slug: t.slug, name: t.name,
685
- ...(t.dependencyReview === 1 ? { dependencyReview: true } : {}),
686
- permissions: { dependencies: t.dependencies === 1, security: t.security === 1 },
687
- cacheKey: createHash('sha256').update(JSON.stringify([
688
- t.dependencies, t.security, links, scopes.filter(scope => scope.teamId === t.id),
689
- ])).digest('base64url'),
690
- repos: scopes.filter(scope => scope.teamId === t.id).map(scope => ({ repoId: scope.repoId, fullName: scope.fullName, path: scope.path || null }))
691
- .toSorted((a, b) => a.fullName.localeCompare(b.fullName) || (a.path ?? '').localeCompare(b.path ?? '')),
692
- reports: reportsByTeam.get(t.id) ?? [],
693
- bundles: bundlesByTeam.get(t.id) ?? [],
694
- }))
664
+ const reportsByTeam = Map.groupBy(reports, r => r.teamId)
665
+ const bundlesByTeam = Map.groupBy(bundles, b => b.teamId)
666
+ return teams.map((t) => {
667
+ const teamScopes = scopes.filter(scope => scope.teamId === t.id)
668
+ return {
669
+ id: t.id, slug: t.slug, name: t.name,
670
+ ...(t.dependencyReview === 1 ? { dependencyReview: true } : {}),
671
+ permissions: { dependencies: t.dependencies === 1, security: t.security === 1 },
672
+ cacheKey: createHash('sha256').update(JSON.stringify([t.dependencies, t.security, links, teamScopes])).digest('base64url'),
673
+ repos: teamScopes.map(scope => ({ repoId: scope.repoId, fullName: scope.fullName, path: scope.path || null }))
674
+ .toSorted((a, b) => a.fullName.localeCompare(b.fullName) || (a.path ?? '').localeCompare(b.path ?? '')),
675
+ reports: (reportsByTeam.get(t.id) ?? []).map(r => ({ id: r.id, slug: r.slug, filename: r.filename, visible: r.visible === 1,
676
+ analyzer: r.analyzer, repoFullName: r.repoFullName, repoDirectory: r.repoDirectory, cacheKey: reportCatalogKey(r, r.role, links) })),
677
+ bundles: (bundlesByTeam.get(t.id) ?? []).map(b => ({ id: b.id, slug: b.slug, integrity: b.integrity, filename: b.filename, visible: b.visible === 1,
678
+ kind: b.kind, byteSize: b.byteSize, repoId: b.repoId, repoDirectory: b.repoDirectory, repoFullName: b.repoFullName, provenance: b.provenance })),
679
+ }
680
+ })
695
681
  }
696
682
 
683
+ // A selected repository's row (RepoRow), and a bundle's (BundleRow) of `b`.
684
+ const REPO_COLUMNS = `repo_id AS repoId, full_name AS fullName, is_private AS priv,
685
+ installation_id AS installId, default_branch AS branch, cached_default_branch AS cachedDefaultBranch, html_url AS htmlUrl,
686
+ added_by AS addedBy, added_at AS addedAt, active AS active`
687
+ const bundleColumns = (b: string) => `${b}.id AS id, ${b}.slug AS slug, ${b}.integrity AS integrity, ${b}.filename AS filename,
688
+ ${b}.kind AS kind, ${b}.byte_size AS byteSize, ${b}.uploaded_by AS uploadedBy, ${b}.repo_id AS repoId, ${b}.repo_directory AS repoDirectory,
689
+ ${b}.visible AS visible, ${b}.uploaded_at AS uploadedAt, ${b}.provenance AS provenance, ${b}.build_conditions AS buildConditions`
690
+
691
+ // What storedUser reads of `u`, a session's user (SessionRow); and a
692
+ // snapshot's `viewer`, the user of the live session `?` at `?` read so.
693
+ const SESSION_USER_COLUMNS = 'u.id AS uid, u.login AS login, u.name AS name, u.avatar_url AS avatar, u.role AS role'
694
+ const VIEWER_SQL = `viewer AS (SELECT ${SESSION_USER_COLUMNS}
695
+ FROM managed_session s JOIN managed_user u ON u.id = s.user_id WHERE s.id = ? AND s.expires_at > ?)`
696
+ // The enabled link reports' rows, as linkRevisionOf reads them.
697
+ const ENABLED_LINKS_SQL = `(SELECT json_group_array(json_object('id', id, 'sha256', sha256) ORDER BY id) FROM managed_link_report WHERE enabled = 1)`
698
+
699
+ // Whether the manager `?` may read `row`, a report or bundle: their own
700
+ // upload, or one a scope of theirs holds. Both placeholders take the user.
701
+ const uploadedOrInScope = (row: string) => `(${row}.uploaded_by = ? OR ${inUserTeamScope('?', row)})`
702
+ // The same, of the user its first placeholder takes too, any row where that
703
+ // is NULL (an admin): its three placeholders as asManager gives them.
704
+ const managerReads = (row: string) => `(? IS NULL OR ${uploadedOrInScope(row)})`
705
+ const asManager = (userId?: string) => [userId ?? null, userId ?? null, userId ?? null]
706
+
707
+ // Whether a scope of a non-hidden team of `user` holding bundle `b` shows
708
+ // them its advisories, in the team `?` (any, where NULL; both placeholders
709
+ // take it).
710
+ const bundleAdvisories = (user: string) => `EXISTS (SELECT 1 FROM managed_team_repo tr
711
+ JOIN managed_team_user tu ON tu.team_id = tr.team_id
712
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
713
+ WHERE tr.repo_id = b.repo_id AND ${BUNDLE_IN_TEAM_PATH_SQL} AND tu.user_id = ${user} AND tu.view_security = 1
714
+ AND (? IS NULL OR tr.team_id = ?))`
715
+
697
716
  // Prepare every statement the store uses, returned as a bag the factory
698
- // destructures — keeps openSqliteManagedDb itself small (one place per query).
717
+ // destructures — keeps createManagedMethods itself small (one place per query).
699
718
  function prepareStatements(db: ManagedSql) {
700
719
  return {
701
720
  // Identity refreshes preserve roles. Login can separately bootstrap the
@@ -719,8 +738,7 @@ function prepareStatements(db: ManagedSql) {
719
738
  `INSERT INTO managed_session (id, user_id, csrf_token, created_at, expires_at) VALUES (?, ?, ?, ?, ?)`,
720
739
  ),
721
740
  selectOwnSessionStmt: db.prepare(
722
- `SELECT s.id AS id, s.csrf_token AS csrf, s.expires_at AS exp, s.upload_key AS uploadKey,
723
- u.id AS uid, u.login AS login, u.name AS name, u.avatar_url AS avatar, u.role AS role
741
+ `SELECT s.id AS id, s.csrf_token AS csrf, s.expires_at AS exp, s.upload_key AS uploadKey, ${SESSION_USER_COLUMNS}
724
742
  FROM managed_session s
725
743
  JOIN managed_user u ON u.id = s.user_id
726
744
  WHERE s.id = ? AND s.expires_at > ? AND s.viewer_session IS NULL`,
@@ -735,8 +753,7 @@ function prepareStatements(db: ManagedSql) {
735
753
  id AS uid, login AS login, name AS name, avatar_url AS avatar, role AS role`,
736
754
  ),
737
755
  selectViewSessionStmt: db.prepare(
738
- `SELECT s.id AS id, s.csrf_token AS csrf, s.expires_at AS exp, s.upload_key AS uploadKey,
739
- u.id AS uid, u.login AS login, u.name AS name, u.avatar_url AS avatar, u.role AS role,
756
+ `SELECT s.id AS id, s.csrf_token AS csrf, s.expires_at AS exp, s.upload_key AS uploadKey, ${SESSION_USER_COLUMNS},
740
757
  a.id AS viewerId, a.login AS viewerLogin, a.name AS viewerName
741
758
  FROM managed_session s
742
759
  JOIN managed_user u ON u.id = s.user_id
@@ -823,19 +840,9 @@ function prepareStatements(db: ManagedSql) {
823
840
  SELECT finding_id FROM managed_finding_triage WHERE finding_id IN (SELECT value FROM json_each(?))
824
841
  UNION SELECT finding_id FROM managed_finding_comment WHERE finding_id IN (SELECT value FROM json_each(?))
825
842
  UNION SELECT finding_id FROM managed_finding_comment_event WHERE finding_id IN (SELECT value FROM json_each(?))) AS annotations`),
826
- selectReposStmt: db.prepare(
827
- `SELECT repo_id AS repoId, full_name AS fullName, is_private AS priv,
828
- installation_id AS installId, default_branch AS branch, cached_default_branch AS cachedDefaultBranch, html_url AS htmlUrl,
829
- added_by AS addedBy, added_at AS addedAt, active AS active
830
- FROM managed_selected_repo WHERE active = 1 ORDER BY full_name ASC`,
831
- ),
843
+ selectReposStmt: db.prepare(`SELECT ${REPO_COLUMNS} FROM managed_selected_repo WHERE active = 1 ORDER BY full_name ASC`),
832
844
  selectRepoFullNameStmt: db.prepare(`SELECT full_name AS fullName FROM managed_selected_repo WHERE repo_id = ?`),
833
- selectAllReposStmt: db.prepare(
834
- `SELECT repo_id AS repoId, full_name AS fullName, is_private AS priv,
835
- installation_id AS installId, default_branch AS branch, cached_default_branch AS cachedDefaultBranch, html_url AS htmlUrl,
836
- added_by AS addedBy, added_at AS addedAt, active AS active
837
- FROM managed_selected_repo ORDER BY full_name ASC`,
838
- ),
845
+ selectAllReposStmt: db.prepare(`SELECT ${REPO_COLUMNS} FROM managed_selected_repo ORDER BY full_name ASC`),
839
846
  insertReportStmt: db.prepare(
840
847
  `WITH candidate(id, slug) AS (VALUES (?, ?))
841
848
  INSERT INTO managed_report (id, slug, filename, content_type, byte_size, sha256, uploaded_by, uploaded_by_login, repo_id, repo_directory, repo_embedded, analyzer, visible, bundle_id, bundle_integrity, uploaded_at, data_key, storage_encrypted)
@@ -856,10 +863,7 @@ function prepareStatements(db: ManagedSql) {
856
863
  LEFT JOIN managed_user u ON u.id = r.uploaded_by
857
864
  LEFT JOIN managed_selected_repo sr ON sr.repo_id = r.repo_id
858
865
  LEFT JOIN managed_bundle b ON b.id = r.bundle_id
859
- WHERE (? IS NULL OR r.uploaded_by = ? OR EXISTS (
860
- SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
861
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
862
- WHERE tr.repo_id = r.repo_id AND tu.user_id = ? AND ${REPORT_IN_TEAM_PATH_SQL}))
866
+ WHERE ${managerReads('r')}
863
867
  ORDER BY r.uploaded_at DESC, r.filename ASC`,
864
868
  ),
865
869
  findingCatalogReportsStmt: db.prepare(`SELECT id, byte_size AS byteSize FROM managed_report WHERE id > ? ORDER BY id LIMIT ?`),
@@ -880,11 +884,7 @@ function prepareStatements(db: ManagedSql) {
880
884
  // grants their teams give them (a JSON array); and the enabled link
881
885
  // reports (linkRevision).
882
886
  selectReportSnapshotStmt: db.prepare(
883
- `WITH viewer AS (
884
- SELECT u.id AS uid, u.login AS login, u.name AS name, u.avatar_url AS avatar, u.role AS role
885
- FROM managed_session s JOIN managed_user u ON u.id = s.user_id
886
- WHERE s.id = ? AND s.expires_at > ?
887
- ), requested AS (SELECT value AS id FROM json_each(?)), report_grants AS (
887
+ `WITH ${VIEWER_SQL}, requested AS (SELECT value AS id FROM json_each(?)), report_grants AS (
888
888
  SELECT r.id AS id, MAX(tu.view_dependencies) AS dependencies, MAX(tu.view_security) AS security
889
889
  FROM managed_report r JOIN requested q ON q.id = r.id
890
890
  JOIN managed_team_repo tr ON tr.repo_id = r.repo_id AND ${REPORT_IN_TEAM_PATH_SQL}
@@ -901,7 +901,7 @@ function prepareStatements(db: ManagedSql) {
901
901
  LEFT JOIN report_grants g ON g.id = r.id
902
902
  WHERE v.role = 'admin' OR (v.role = 'manage' AND r.uploaded_by = v.uid)
903
903
  OR (g.id IS NOT NULL AND (v.role = 'manage' OR r.visible = 1))) AS reports,
904
- (SELECT json_group_array(json_object('id', id, 'sha256', sha256) ORDER BY id) FROM managed_link_report WHERE enabled = 1) AS links
904
+ ${ENABLED_LINKS_SQL} AS links
905
905
  FROM viewer v`,
906
906
  ),
907
907
  // A team snapshot's reads in one statement, so one snapshot of the
@@ -911,11 +911,7 @@ function prepareStatements(db: ManagedSql) {
911
911
  // the team's repositories (each a JSON array); and the enabled link
912
912
  // reports (linkRevision).
913
913
  selectTeamSnapshotStmt: db.prepare(
914
- `WITH viewer AS (
915
- SELECT u.id AS uid, u.login AS login, u.name AS name, u.avatar_url AS avatar, u.role AS role
916
- FROM managed_session s JOIN managed_user u ON u.id = s.user_id
917
- WHERE s.id = ? AND s.expires_at > ?
918
- )
914
+ `WITH ${VIEWER_SQL}
919
915
  SELECT v.uid AS uid, v.login AS login, v.name AS name, v.avatar AS avatar, v.role AS role,
920
916
  EXISTS(SELECT 1 FROM managed_team_user tu JOIN managed_team t ON t.id = tu.team_id
921
917
  WHERE tu.user_id = v.uid AND tu.team_id = ? AND t.hidden = 0) AS member,
@@ -934,16 +930,13 @@ function prepareStatements(db: ManagedSql) {
934
930
  (SELECT json_group_array(json_object('repoId', tr.repo_id, 'github', sr.full_name, 'path', tr.path) ORDER BY tr.repo_id, tr.path)
935
931
  FROM managed_team_repo tr JOIN managed_selected_repo sr ON sr.repo_id = tr.repo_id
936
932
  WHERE tr.team_id = ?) AS repositories,
937
- (SELECT json_group_array(json_object('id', id, 'sha256', sha256) ORDER BY id) FROM managed_link_report WHERE enabled = 1) AS links
933
+ ${ENABLED_LINKS_SQL} AS links
938
934
  FROM viewer v`,
939
935
  ),
940
936
  reportFilenamesWithBundleHashStmt: db.prepare(`SELECT DISTINCT filename FROM managed_report WHERE bundle_id = ? AND sha256 = ?`),
941
937
  reportsForBundleStmt: db.prepare(
942
938
  `SELECT r.id AS id, r.filename AS filename, r.bundle_id AS bundleId,
943
- (? IS NULL OR r.uploaded_by = ? OR EXISTS(SELECT 1 FROM managed_team_repo tr
944
- JOIN managed_team_user tu ON tu.team_id = tr.team_id
945
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
946
- WHERE tr.repo_id = r.repo_id AND ${REPORT_IN_TEAM_PATH_SQL} AND tu.user_id = ?)) AS readable
939
+ ${managerReads('r')} AS readable
947
940
  FROM managed_report r WHERE r.bundle_id = ? OR r.bundle_integrity = ?
948
941
  ORDER BY r.uploaded_at DESC, r.filename ASC, r.id ASC`,
949
942
  ),
@@ -1006,7 +999,8 @@ function prepareStatements(db: ManagedSql) {
1006
999
  FROM managed_finding_triage t LEFT JOIN managed_user u ON u.id = t.updated_by
1007
1000
  WHERE t.finding_id IN (SELECT id FROM requested)) AS triage,
1008
1001
  (SELECT json_group_array(json_object('id', c.id, 'findingId', c.finding_id, 'body', c.body, 'authorId', c.author_id,
1009
- 'authorLogin', COALESCE(u.login, c.author_login), 'createdAt', c.created_at, 'updatedAt', c.updated_at, 'version', c.version)
1002
+ 'authorLogin', COALESCE(u.login, c.author_login), 'authorName', u.name,
1003
+ 'createdAt', c.created_at, 'updatedAt', c.updated_at, 'version', c.version)
1010
1004
  ORDER BY c.created_at NULLS FIRST, c.id)
1011
1005
  FROM managed_finding_comment c LEFT JOIN managed_user u ON u.id = c.author_id
1012
1006
  WHERE c.finding_id IN (SELECT id FROM requested)) AS comments,
@@ -1048,18 +1042,8 @@ function prepareStatements(db: ManagedSql) {
1048
1042
  WHERE id = :id AND (${BUNDLE_RENAMED_SQL} OR (:provenance = 'build' AND (provenance IS DISTINCT FROM 'build'
1049
1043
  OR build_conditions IS DISTINCT FROM COALESCE(build_conditions, :buildConditions))))`,
1050
1044
  ),
1051
- selectBundleByIntegrityStmt: db.prepare(
1052
- `SELECT id, slug, integrity, filename, kind, byte_size AS byteSize,
1053
- uploaded_by AS uploadedBy, repo_id AS repoId, repo_directory AS repoDirectory, visible, uploaded_at AS uploadedAt, provenance,
1054
- build_conditions AS buildConditions
1055
- FROM managed_bundle WHERE integrity = ?`,
1056
- ),
1057
- selectBundleStmt: db.prepare(
1058
- `SELECT id, slug, integrity, filename, kind, byte_size AS byteSize,
1059
- uploaded_by AS uploadedBy, repo_id AS repoId, repo_directory AS repoDirectory, visible, uploaded_at AS uploadedAt, provenance,
1060
- build_conditions AS buildConditions
1061
- FROM managed_bundle WHERE id = ?`,
1062
- ),
1045
+ selectBundleByIntegrityStmt: db.prepare(`SELECT ${bundleColumns('b')} FROM managed_bundle b WHERE b.integrity = ?`),
1046
+ selectBundleStmt: db.prepare(`SELECT ${bundleColumns('b')} FROM managed_bundle b WHERE b.id = ?`),
1063
1047
  selectBundlesStmt: db.prepare(
1064
1048
  `SELECT b.id AS id, b.slug AS slug, b.integrity AS integrity, b.filename AS filename, b.kind AS kind,
1065
1049
  b.byte_size AS byteSize, COALESCE(u.login, b.uploaded_by_login) AS uploadedByLogin,
@@ -1067,23 +1051,14 @@ function prepareStatements(db: ManagedSql) {
1067
1051
  FROM managed_bundle b
1068
1052
  LEFT JOIN managed_user u ON u.id = b.uploaded_by
1069
1053
  LEFT JOIN managed_selected_repo sr ON sr.repo_id = b.repo_id
1070
- WHERE (? IS NULL OR (b.uploaded_by = ? OR EXISTS (
1071
- SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
1072
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1073
- WHERE tr.repo_id = b.repo_id AND ${BUNDLE_IN_TEAM_PATH_SQL} AND tu.user_id = ?)))
1054
+ WHERE ${managerReads('b')}
1074
1055
  ORDER BY b.uploaded_at DESC, b.filename ASC`,
1075
1056
  ),
1076
1057
  selectBundleReadableStmt: db.prepare(
1077
- `SELECT 1 FROM managed_bundle b WHERE b.id = ? AND (b.uploaded_by = ? OR EXISTS (
1078
- SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
1079
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1080
- WHERE tr.repo_id = b.repo_id AND ${BUNDLE_IN_TEAM_PATH_SQL} AND tu.user_id = ?))`,
1058
+ `SELECT 1 FROM managed_bundle b WHERE b.id = ? AND ${uploadedOrInScope('b')}`,
1081
1059
  ),
1082
1060
  selectReadableBundleIdsStmt: db.prepare(
1083
- `SELECT b.id FROM managed_bundle b WHERE b.id IN (SELECT value FROM json_each(?)) AND (b.uploaded_by = ? OR EXISTS (
1084
- SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
1085
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1086
- WHERE tr.repo_id = b.repo_id AND ${BUNDLE_IN_TEAM_PATH_SQL} AND tu.user_id = ?))`,
1061
+ `SELECT b.id FROM managed_bundle b WHERE b.id IN (SELECT value FROM json_each(?)) AND ${uploadedOrInScope('b')}`,
1087
1062
  ),
1088
1063
  selectRepoReadableStmt: db.prepare(
1089
1064
  `SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
@@ -1104,9 +1079,7 @@ function prepareStatements(db: ManagedSql) {
1104
1079
  // but haven't been linked yet (bundle uploaded after the report).
1105
1080
  linkReportsToBundleStmt: db.prepare(
1106
1081
  `UPDATE managed_report AS r SET bundle_id = ? WHERE bundle_integrity = ? AND bundle_id IS NULL
1107
- AND (? IS NULL OR r.uploaded_by = ? OR EXISTS (SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
1108
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1109
- WHERE tu.user_id = ? AND tr.repo_id = r.repo_id AND ${REPORT_IN_TEAM_PATH_SQL}))`,
1082
+ AND ${managerReads('r')}`,
1110
1083
  ),
1111
1084
  // OR IGNORE: a duplicate name (UNIQUE) is the "taken" signal (0 changes); the
1112
1085
  // uuid PK never collides.
@@ -1141,7 +1114,7 @@ function prepareStatements(db: ManagedSql) {
1141
1114
  (SELECT json_group_array(json_object('teamId', x.teamId, 'repoId', x.repoId, 'path', x.path, 'fullName', x.fullName)
1142
1115
  ORDER BY x.teamId, x.repoId, x.path)
1143
1116
  FROM (${USER_TEAM_SCOPES_SQL('v.id')}) AS x) AS scopes,
1144
- (SELECT json_group_array(json_object('id', id, 'sha256', sha256) ORDER BY id) FROM managed_link_report WHERE enabled = 1) AS links,
1117
+ ${ENABLED_LINKS_SQL} AS links,
1145
1118
  (SELECT json_group_array(json_object('teamId', x.teamId, 'id', x.id, 'slug', x.slug, 'filename', x.filename, 'analyzer', x.analyzer,
1146
1119
  'visible', x.visible, 'sha256', x.sha256, 'bundleId', x.bundleId, 'repoId', x.repoId, 'repoDirectory', x.repoDirectory,
1147
1120
  'repoFullName', x.repoFullName, 'dependencies', x.dependencies, 'security', x.security, 'role', x.role)
@@ -1161,29 +1134,12 @@ function prepareStatements(db: ManagedSql) {
1161
1134
  WHERE tu.user_id = ?`,
1162
1135
  ),
1163
1136
  // A report is readable iff one of the user's team scopes contains it.
1164
- selectReportReadableStmt: db.prepare(
1165
- `SELECT 1 FROM managed_report r
1166
- JOIN managed_team_repo tr ON tr.repo_id = r.repo_id AND ${REPORT_IN_TEAM_PATH_SQL}
1167
- JOIN managed_team_user tu ON tu.team_id = tr.team_id
1168
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1169
- WHERE r.id = ? AND tu.user_id = ? LIMIT 1`,
1170
- ),
1137
+ selectReportReadableStmt: db.prepare(`SELECT 1 FROM managed_report r WHERE r.id = ? AND ${inUserTeamScope('?', 'r')}`),
1171
1138
  selectReportViewStmt: db.prepare(
1172
- `SELECT r.uploaded_by AS uploadedBy, r.visible AS visible,
1173
- EXISTS(SELECT 1 FROM managed_team_repo tr
1174
- JOIN managed_team_user tu ON tu.team_id = tr.team_id
1175
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1176
- WHERE tr.repo_id = r.repo_id AND ${REPORT_IN_TEAM_PATH_SQL} AND tu.user_id = ?) AS readable
1139
+ `SELECT r.uploaded_by AS uploadedBy, r.visible AS visible, ${inUserTeamScope('?', 'r')} AS readable
1177
1140
  FROM managed_report r WHERE r.id = ?`,
1178
1141
  ),
1179
- selectBundleSecurityStmt: db.prepare(
1180
- `SELECT 1 FROM managed_bundle b
1181
- JOIN managed_team_repo tr ON tr.repo_id = b.repo_id AND ${BUNDLE_IN_TEAM_PATH_SQL}
1182
- JOIN managed_team_user tu ON tu.team_id = tr.team_id
1183
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1184
- WHERE b.id = ? AND tu.user_id = ? AND tu.view_security = 1
1185
- AND (? IS NULL OR tr.team_id = ?) LIMIT 1`,
1186
- ),
1142
+ selectBundleSecurityStmt: db.prepare(`SELECT 1 FROM managed_bundle b WHERE b.id = ? AND ${bundleAdvisories('?')}`),
1187
1143
  // A bundle access snapshot's reads in one statement, so one snapshot of
1188
1144
  // the database answers them all: the session's user, view sessions
1189
1145
  // included; the bundle, NULL where there is none; whether one of the
@@ -1193,21 +1149,9 @@ function prepareStatements(db: ManagedSql) {
1193
1149
  // asks, whether one in the team (any, where NULL) shows them its
1194
1150
  // advisories (selectBundleSecurityStmt).
1195
1151
  selectBundleAccessStmt: db.prepare(
1196
- `WITH viewer AS (
1197
- SELECT u.id AS uid, u.role AS role
1198
- FROM managed_session s JOIN managed_user u ON u.id = s.user_id
1199
- WHERE s.id = ? AND s.expires_at > ?
1200
- )
1201
- SELECT v.uid AS uid, v.role AS role, b.id AS id, b.slug AS slug, b.integrity AS integrity, b.filename AS filename, b.kind AS kind,
1202
- b.byte_size AS byteSize, b.uploaded_by AS uploadedBy, b.repo_id AS repoId, b.repo_directory AS repoDirectory, b.visible AS visible,
1203
- b.uploaded_at AS uploadedAt, b.provenance AS provenance, b.build_conditions AS buildConditions,
1204
- EXISTS(SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
1205
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1206
- WHERE tr.repo_id = b.repo_id AND ${BUNDLE_IN_TEAM_PATH_SQL} AND tu.user_id = v.uid) AS granted,
1207
- (? = 1 AND EXISTS(SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
1208
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1209
- WHERE tr.repo_id = b.repo_id AND ${BUNDLE_IN_TEAM_PATH_SQL} AND tu.user_id = v.uid AND tu.view_security = 1
1210
- AND (? IS NULL OR tr.team_id = ?))) AS security
1152
+ `WITH ${VIEWER_SQL}
1153
+ SELECT v.uid AS uid, v.role AS role, ${bundleColumns('b')},
1154
+ ${inUserTeamScope('v.uid', 'b')} AS granted, (? = 1 AND ${bundleAdvisories('v.uid')}) AS security
1211
1155
  FROM viewer v LEFT JOIN managed_bundle b ON b.id = ?`,
1212
1156
  ),
1213
1157
  // The viewer's effective visibility permissions for a report: OR'd (MAX over
@@ -1253,7 +1197,7 @@ type RepoRow = {
1253
1197
  branch: string; cachedDefaultBranch: string | null; htmlUrl: string; addedBy: string | null; addedAt: number; active: number
1254
1198
  }
1255
1199
 
1256
- // The repo-selection slice of ManagedDb, split out to keep openSqliteManagedDb
1200
+ // The repo-selection slice of ManagedDb, split out to keep createManagedMethods
1257
1201
  // within the per-function line budget. Closes over its prepared statements.
1258
1202
  function selectedRepoMethods(stmts: ReturnType<typeof prepareStatements>) {
1259
1203
  const { upsertRepoStmt, deleteRepoStmt, deactivateRepoStmt, reactivateRepoStmt, selectReposStmt, selectAllReposStmt,
@@ -1272,13 +1216,13 @@ function selectedRepoMethods(stmts: ReturnType<typeof prepareStatements>) {
1272
1216
  )
1273
1217
  },
1274
1218
  async cacheRepoDefaultBranch(repo: SelectedRepo, branch: string | null): Promise<boolean> {
1275
- return Number((await stmts.cacheRepoDefaultBranchStmt.run(branch, repo.repoId, repo.fullName, repo.addedAt)).changes) > 0
1219
+ return anyChanged(await stmts.cacheRepoDefaultBranchStmt.run(branch, repo.repoId, repo.fullName, repo.addedAt))
1276
1220
  },
1277
1221
  async deselectRepo(repoId: number): Promise<boolean> {
1278
- return Number((await deleteRepoStmt.run(repoId)).changes) > 0
1222
+ return anyChanged(await deleteRepoStmt.run(repoId))
1279
1223
  },
1280
1224
  async connectRepoInstallation(repo: SelectedRepo, installationId: number, sessionId: string, now: number): Promise<boolean> {
1281
- return Number((await stmts.connectRepoInstallationStmt.run(installationId, now, repo.repoId, repo.fullName, repo.addedAt, sessionId, now)).changes) > 0
1225
+ return anyChanged(await stmts.connectRepoInstallationStmt.run(installationId, now, repo.repoId, repo.fullName, repo.addedAt, sessionId, now))
1282
1226
  },
1283
1227
  async listSelectedRepos(): Promise<SelectedRepo[]> {
1284
1228
  const rows = (await selectReposStmt.all()) as RepoRow[]
@@ -1292,13 +1236,13 @@ function selectedRepoMethods(stmts: ReturnType<typeof prepareStatements>) {
1292
1236
  return ((await stmts.selectRepoFullNameStmt.get(repoId)) as { fullName: string } | undefined)?.fullName ?? null
1293
1237
  },
1294
1238
  async deactivateRepo(repoId: number): Promise<boolean> {
1295
- return Number((await deactivateRepoStmt.run(repoId)).changes) > 0
1239
+ return anyChanged(await deactivateRepoStmt.run(repoId))
1296
1240
  },
1297
1241
  async reactivateRepo(repoId: number): Promise<boolean> {
1298
- return Number((await reactivateRepoStmt.run(repoId)).changes) > 0
1242
+ return anyChanged(await reactivateRepoStmt.run(repoId))
1299
1243
  },
1300
1244
  async deleteRepo(repoId: number): Promise<boolean> {
1301
- return Number((await deleteRepoStmt.run(repoId)).changes) > 0
1245
+ return anyChanged(await deleteRepoStmt.run(repoId))
1302
1246
  },
1303
1247
  async listReportsForRepo(repoId: number): Promise<RepoReportItem[]> {
1304
1248
  return (await selectReportsForRepoStmt.all(repoId)) as unknown as RepoReportItem[]
@@ -1330,6 +1274,17 @@ type ReportRow = {
1330
1274
  bundleId: string | null
1331
1275
  }
1332
1276
 
1277
+ // A report as an access snapshot read it, and as the snapshot gives it: with
1278
+ // every permission where the reader's role sees `whole` reports.
1279
+ type AccessRow = Pick<ReportAccessRecord, 'id' | 'filename' | 'byteSize' | 'sha256'> & {
1280
+ repoDirectory: string; repoFullName: string | null; dependencies: number; security: number
1281
+ }
1282
+ const accessRecord = (row: AccessRow, whole: boolean): ReportAccessRecord => ({
1283
+ id: row.id, filename: row.filename, byteSize: row.byteSize, sha256: row.sha256,
1284
+ repo: { github: row.repoFullName, directory: row.repoDirectory },
1285
+ permissions: { dependencies: whole || row.dependencies === 1, security: whole || row.security === 1 },
1286
+ })
1287
+
1333
1288
  // Byte storage may outlast a logout or grant change. HTTP uploads reauthorize
1334
1289
  // inside the metadata writer transaction after their bytes have been stored.
1335
1290
  async function authorizeUpload(stmts: ReturnType<typeof prepareStatements>, sessionId: string | undefined,
@@ -1360,7 +1315,7 @@ function reportMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedS
1360
1315
  await insertReportStmt.run(
1361
1316
  report.id, preferredSlug(report.id), report.filename, report.contentType, report.byteSize,
1362
1317
  report.sha256, report.uploadedBy, report.uploadedByLogin ?? null, report.repoId,
1363
- report.repoDirectory ?? '', report.repoEmbedded ? 1 : 0, report.analyzer ?? null, report.visible == null ? 0 : report.visible ? 1 : 0, report.bundleId ?? null,
1318
+ report.repoDirectory ?? '', report.repoEmbedded ? 1 : 0, report.analyzer ?? null, report.visible ? 1 : 0, report.bundleId ?? null,
1364
1319
  report.bundleIntegrity ?? null, now, report.dataKey ?? null, report.dataKey ? 1 : 0,
1365
1320
  )
1366
1321
  }
@@ -1379,15 +1334,8 @@ function reportMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedS
1379
1334
  return (await getReport(report.id))!
1380
1335
  },
1381
1336
  async listReports(userId?: string): Promise<AdminReport[]> {
1382
- const rows = (await selectReportsStmt.all(userId ?? null, userId ?? null, userId ?? null)) as ReportListRow[]
1383
- return rows.map((r) => ({
1384
- id: r.id, slug: r.slug, filename: r.filename, contentType: r.contentType, byteSize: r.byteSize,
1385
- sha256: r.sha256, uploadedByLogin: r.uploadedByLogin,
1386
- repoId: r.repoId, repoFullName: r.repoFullName,
1387
- repoDirectory: r.repoDirectory, repoEmbedded: r.repoEmbedded === 1, analyzer: r.analyzer, visible: r.visible === 1,
1388
- bundleId: r.bundleId, bundleFilename: r.bundleFilename, bundleIntegrity: r.bundleIntegrity,
1389
- uploadedAt: r.uploadedAt,
1390
- }))
1337
+ const rows = (await selectReportsStmt.all(...asManager(userId))) as ReportListRow[]
1338
+ return rows.map(r => ({ ...r, repoEmbedded: r.repoEmbedded === 1, visible: r.visible === 1 }))
1391
1339
  },
1392
1340
  async listFindingCatalogReports(after: string, limit: number): Promise<Pick<ReportRecord, 'id' | 'byteSize'>[]> {
1393
1341
  return await stmts.findingCatalogReportsStmt.all(after, limit) as Pick<ReportRecord, 'id' | 'byteSize'>[]
@@ -1396,9 +1344,9 @@ function reportMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedS
1396
1344
  const session = await stmts.selectTeamSnapshotStmt.get(sessionId, now, teamId, teamId, reportId, teamId) as
1397
1345
  SessionRow & { member: unknown; reports: unknown; repositories: unknown; links: unknown } | undefined
1398
1346
  if (!session) return null
1399
- const user: StoredUser = { id: session.uid, login: session.login, name: session.name, avatarUrl: session.avatar, role: session.role }
1347
+ const user = storedUser(session)
1400
1348
  if (user.role === 'none' || !session.member) return { user, teamId: null, reports: [], repositories: [] }
1401
- const whole = user.role === 'admin' || user.role === 'manage'
1349
+ const whole = roleAtLeast(user.role, 'manage')
1402
1350
  const rows = jsonRows<CatalogReportRow & { id: string; byteSize: number; visible: number }>(session.reports)
1403
1351
  // Only privileged callers can receive a hidden row from this query. Give
1404
1352
  // that individual preview its own capacity; published report selections
@@ -1407,46 +1355,37 @@ function reportMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedS
1407
1355
  const selected = hidden ? [hidden] : rows
1408
1356
  const repositories = jsonRows<TeamReportAccessSnapshot['repositories'][number]>(session.repositories)
1409
1357
  const links = linkRevisionOf(jsonRows(session.links))
1410
- return { user, teamId, reportId, hiddenReportId: hidden?.id ?? null, repositories, linkRevision: links, reports: selected.map(row => ({
1411
- id: row.id, filename: row.filename, byteSize: row.byteSize, sha256: row.sha256,
1412
- repo: { github: row.repoFullName, directory: row.repoDirectory },
1413
- permissions: { dependencies: whole || row.dependencies === 1, security: whole || row.security === 1 },
1414
- })), catalogKeys: Object.fromEntries(selected.map(row => [row.id, reportCatalogKey(row, user.role, links)])) }
1358
+ return { user, teamId, reportId, hiddenReportId: hidden?.id ?? null, repositories, linkRevision: links,
1359
+ reports: selected.map(row => accessRecord(row, whole)),
1360
+ catalogKeys: Object.fromEntries(selected.map(row => [row.id, reportCatalogKey(row, user.role, links)])) }
1415
1361
  },
1416
1362
  async getReportAccessSnapshot(sessionId: string, now: number, ids: readonly string[]): Promise<ReportAccessSnapshot | null> {
1417
1363
  const session = await stmts.selectReportSnapshotStmt.get(sessionId, now, JSON.stringify([...new Set(ids)])) as
1418
1364
  SessionRow & { reports: unknown; links: unknown } | undefined
1419
1365
  if (!session) return null
1420
- const user: StoredUser = { id: session.uid, login: session.login, name: session.name, avatarUrl: session.avatar, role: session.role }
1366
+ const user = storedUser(session)
1421
1367
  if (user.role === 'none' || ids.length === 0) return { user, reports: [] }
1422
- const admin = user.role === 'admin', manage = user.role === 'manage'
1423
- const rows = jsonRows<{
1424
- id: string; filename: string; byteSize: number; sha256: string; repoDirectory: string
1425
- repoFullName: string | null; dependencies: number; security: number
1426
- }>(session.reports)
1427
- return { user, linkRevision: linkRevisionOf(jsonRows(session.links)), reports: rows.map(row => ({
1428
- id: row.id, filename: row.filename, byteSize: row.byteSize, sha256: row.sha256,
1429
- repo: { github: row.repoFullName, directory: row.repoDirectory },
1430
- permissions: { dependencies: admin || manage || row.dependencies === 1, security: admin || manage || row.security === 1 },
1431
- })) }
1368
+ const whole = roleAtLeast(user.role, 'manage')
1369
+ const reports = jsonRows<AccessRow>(session.reports).map(row => accessRecord(row, whole))
1370
+ return { user, linkRevision: linkRevisionOf(jsonRows(session.links)), reports }
1432
1371
  },
1433
1372
  async listReportFilenamesWithBundleHash(bundleId: string, sha256: string): Promise<string[]> {
1434
1373
  const rows = (await stmts.reportFilenamesWithBundleHashStmt.all(bundleId, sha256)) as { filename: string }[]
1435
1374
  return rows.map(row => row.filename)
1436
1375
  },
1437
1376
  async listReportsForBundle(bundleId: string, integrity: string, userId?: string): Promise<BundleReportItem[]> {
1438
- const rows = await stmts.reportsForBundleStmt.all(userId ?? null, userId ?? null, userId ?? null, bundleId, integrity) as
1377
+ const rows = await stmts.reportsForBundleStmt.all(...asManager(userId), bundleId, integrity) as
1439
1378
  (Omit<BundleReportItem, 'readable'> & { readable: unknown })[]
1440
1379
  return rows.map(row => ({ id: row.id, filename: row.filename, bundleId: row.bundleId, readable: Boolean(row.readable) }))
1441
1380
  },
1442
1381
  async deleteReport(id: string): Promise<boolean> {
1443
- return Number((await deleteReportStmt.run(id)).changes) > 0
1382
+ return anyChanged(await deleteReportStmt.run(id))
1444
1383
  },
1445
1384
  async setReportRepo(id: string, repoId: number | null, repoDirectory = ''): Promise<boolean> {
1446
- return Number((await setReportRepoStmt.run(repoId, repoId == null ? '' : repoDirectory, id)).changes) > 0
1385
+ return anyChanged(await setReportRepoStmt.run(repoId, repoId == null ? '' : repoDirectory, id))
1447
1386
  },
1448
1387
  async setReportVisible(id: string, visible: boolean): Promise<boolean> {
1449
- return Number((await setReportVisibleStmt.run(visible ? 1 : 0, id)).changes) > 0
1388
+ return anyChanged(await setReportVisibleStmt.run(visible ? 1 : 0, id))
1450
1389
  },
1451
1390
  }
1452
1391
  }
@@ -1456,12 +1395,17 @@ type TriageDbRow = {
1456
1395
  comment: string | null; fix: string | null; flagged: number | null
1457
1396
  updatedByLogin: string | null; updatedAt: number
1458
1397
  }
1459
- const triageRow = (r: TriageDbRow): TriageRow => ({
1460
- findingId: r.findingId, color: r.color, triage: r.triage, comment: r.comment, fix: r.fix,
1461
- flagged: r.flagged == null ? null : r.flagged === 1,
1462
- updatedByLogin: r.updatedByLogin, updatedAt: r.updatedAt,
1463
- })
1398
+ const triageRow = (r: TriageDbRow): TriageRow => ({ ...r, flagged: r.flagged == null ? null : r.flagged === 1 })
1464
1399
  type TriageStateDbRow = { color: string | null; triage: string | null; comment: string | null; fix: string | null; flagged: number | null }
1400
+ // An entry as its row stores it. `flagged: false` is a real value (the
1401
+ // explicit un-flag tombstone), so it is 0 here and only null/absent maps to NULL.
1402
+ function triageState(entry: TriageEntryPatch | null): TriageStateDbRow {
1403
+ const e = entry ?? {}
1404
+ return { color: e.color ?? null, triage: e.triage ?? null, comment: e.comment ?? null,
1405
+ fix: e.fix ?? null, flagged: e.flagged == null ? null : (e.flagged ? 1 : 0) }
1406
+ }
1407
+ const sameTriageState = (a: TriageStateDbRow, b: TriageStateDbRow) =>
1408
+ a.color === b.color && a.triage === b.triage && a.comment === b.comment && a.fix === b.fix && a.flagged === b.flagged
1465
1409
  type TriageEventDbRow = TriageStateDbRow & {
1466
1410
  seq: number; findingId: string; batchId: string; actorId: string | null; actorLogin: string | null; actorName: string | null; at: number
1467
1411
  }
@@ -1478,16 +1422,9 @@ function triageMethods(stmts: ReturnType<typeof prepareStatements>, historyLimit
1478
1422
  const { upsertTriageStmt, selectTriageStmt, selectTriageStateStmt, insertTriageEventStmt, trimTriageEventsStmt, selectTriageHistoryStmt,
1479
1423
  deleteTriageStmt, deleteTriageHistoryStmt, deleteCommentsStmt, deleteCommentHistoryStmt, countAnnotationsStmt } = stmts
1480
1424
  async function writeEntry(findingId: string, entry: TriageEntryPatch | null, batchId: string, updatedBy: string | null, updatedByLogin: string | null, now: number, reportId: string | null = null): Promise<void> {
1481
- const e = entry ?? {}
1482
- // `flagged: false` is a real value (the explicit un-flag tombstone), so it
1483
- // is 0 here and only null/absent maps to NULL.
1484
- const next: TriageStateDbRow = {
1485
- color: e.color ?? null, triage: e.triage ?? null, comment: e.comment ?? null,
1486
- fix: e.fix ?? null, flagged: e.flagged == null ? null : (e.flagged ? 1 : 0),
1487
- }
1425
+ const next = triageState(entry)
1488
1426
  const cur = (await selectTriageStateStmt.get(findingId)) as TriageStateDbRow | undefined
1489
- if (cur != null && cur.color === next.color && cur.triage === next.triage && cur.comment === next.comment
1490
- && cur.fix === next.fix && cur.flagged === next.flagged) return
1427
+ if (cur != null && sameTriageState(cur, next)) return
1491
1428
  await upsertTriageStmt.run(findingId, next.color, next.triage, next.comment, next.fix, next.flagged, updatedBy, updatedByLogin, now)
1492
1429
  await insertTriageEventStmt.run(findingId, batchId, next.color, next.triage, next.comment, next.fix, next.flagged, updatedBy, updatedByLogin, now, reportId, reportId, reportId)
1493
1430
  if (historyLimit > 0) await trimTriageEventsStmt.run(findingId, findingId, historyLimit)
@@ -1512,12 +1449,7 @@ function triageMethods(stmts: ReturnType<typeof prepareStatements>, historyLimit
1512
1449
  },
1513
1450
  async listTriageHistory(findingId: string, limit: number): Promise<TriageEventRow[]> {
1514
1451
  const rows = (await selectTriageHistoryStmt.all(findingId, limit)) as TriageEventDbRow[]
1515
- return rows.map((r) => ({
1516
- seq: r.seq, findingId: r.findingId, batchId: r.batchId,
1517
- color: r.color, triage: r.triage, comment: r.comment, fix: r.fix,
1518
- flagged: r.flagged == null ? null : r.flagged === 1,
1519
- actorId: r.actorId, actorLogin: r.actorLogin, actorName: r.actorName, at: r.at,
1520
- }))
1452
+ return rows.map(r => ({ ...r, flagged: r.flagged == null ? null : r.flagged === 1 }))
1521
1453
  },
1522
1454
  async listTriageFixes(findingIds: readonly string[]): Promise<string[]> {
1523
1455
  if (findingIds.length === 0) return []
@@ -1544,10 +1476,8 @@ function triageMethods(stmts: ReturnType<typeof prepareStatements>, historyLimit
1544
1476
  const current = new Map((await selectTriageStmt.all(JSON.stringify(entries.map(([id]) => id))) as TriageDbRow[])
1545
1477
  .map(row => [row.findingId, row]))
1546
1478
  const changed = entries.flatMap(([id, entry]) => {
1547
- const e = entry ?? {}, previous = current.get(id)
1548
- const next = { color: e.color ?? null, triage: e.triage ?? null, comment: e.comment ?? null,
1549
- fix: e.fix ?? null, flagged: e.flagged == null ? null : e.flagged ? 1 : 0 }
1550
- if (previous && Object.entries(next).every(([key, value]) => previous[key as keyof TriageStateDbRow] === value)) return []
1479
+ const next = triageState(entry), previous = current.get(id)
1480
+ if (previous && sameTriageState(previous, next)) return []
1551
1481
  return [[id, next.color, next.triage, next.comment, next.fix, next.flagged]]
1552
1482
  })
1553
1483
  // Bound SQL parameters while keeping the entire batch/history atomic.
@@ -1619,8 +1549,8 @@ function bundleMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedS
1619
1549
  )
1620
1550
  },
1621
1551
  async reuseBundle(id: string, { provenance, filename, kind, rename, buildConditions }: BundleReuse): Promise<boolean> {
1622
- return Number((await stmts.reuseBundleStmt.run({ id, provenance, filename, kind, rename: rename ? 1 : 0,
1623
- buildConditions: buildConditions == null ? null : JSON.stringify(buildConditions) })).changes) > 0
1552
+ return anyChanged(await stmts.reuseBundleStmt.run({ id, provenance, filename, kind, rename: rename ? 1 : 0,
1553
+ buildConditions: buildConditions == null ? null : JSON.stringify(buildConditions) }))
1624
1554
  },
1625
1555
  getBundleByIntegrity,
1626
1556
  // The distinct method name selects a writer-locked reconciliation scope.
@@ -1645,7 +1575,7 @@ function bundleMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedS
1645
1575
  return { bundle: mapBundle(row), canReadAdvisories: manager || Boolean(row.security) }
1646
1576
  },
1647
1577
  async listBundles(userId?: string): Promise<AdminBundle[]> {
1648
- const rows = (await selectBundlesStmt.all(userId ?? null, userId ?? null, userId ?? null)) as BundleListRow[]
1578
+ const rows = (await selectBundlesStmt.all(...asManager(userId))) as BundleListRow[]
1649
1579
  return rows.map((r) => ({
1650
1580
  id: r.id, slug: r.slug, integrity: r.integrity, filename: r.filename, kind: r.kind, byteSize: r.byteSize,
1651
1581
  uploadedByLogin: r.uploadedByLogin, repoId: r.repoId, repoFullName: r.repoFullName, repoDirectory: r.repoDirectory, visible: r.visible === 1,
@@ -1667,16 +1597,16 @@ function bundleMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedS
1667
1597
  return (await selectRepoPathReadableStmt.get(directory, repoId, userId)) != null
1668
1598
  },
1669
1599
  async deleteBundle(id: string): Promise<boolean> {
1670
- return Number((await deleteBundleStmt.run(id)).changes) > 0
1600
+ return anyChanged(await deleteBundleStmt.run(id))
1671
1601
  },
1672
1602
  async setBundleVisible(id: string, visible: boolean): Promise<boolean> {
1673
- return Number((await stmts.setBundleVisibleStmt.run(visible ? 1 : 0, id)).changes) > 0
1603
+ return anyChanged(await stmts.setBundleVisibleStmt.run(visible ? 1 : 0, id))
1674
1604
  },
1675
1605
  async setBundleRepo(id: string, repoId: number | null, directory?: string): Promise<boolean> {
1676
- return Number((await setBundleRepoStmt.run(repoId, repoId == null ? '' : directory ?? '', id)).changes) > 0
1606
+ return anyChanged(await setBundleRepoStmt.run(repoId, repoId == null ? '' : directory ?? '', id))
1677
1607
  },
1678
1608
  async linkReportsToBundle(integrity: string, bundleId: string, userId?: string): Promise<void> {
1679
- await linkReportsToBundleStmt.run(bundleId, integrity, userId ?? null, userId ?? null, userId ?? null)
1609
+ await linkReportsToBundleStmt.run(bundleId, integrity, ...asManager(userId))
1680
1610
  },
1681
1611
  }
1682
1612
  }
@@ -1695,9 +1625,9 @@ function teamMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql
1695
1625
  selectReportPermsStmt, selectUserOptionsStmt, selectTeamReposStmt, selectTeamMembersStmt,
1696
1626
  upsertTeamRepoStmt, deleteTeamRepoStmt, deleteTeamRepoPathStmt, upsertTeamMemberStmt, deleteTeamMemberStmt,
1697
1627
  } = stmts
1698
- const methods = {
1628
+ return {
1699
1629
  async createTeam(id: string, name: string, now: number): Promise<boolean> {
1700
- return Number((await insertTeamStmt.run(id, preferredSlug(id), name, now, now)).changes) > 0
1630
+ return anyChanged(await insertTeamStmt.run(id, preferredSlug(id), name, now, now))
1701
1631
  },
1702
1632
  async renameTeam(id: string, name: string, now: number): Promise<'ok' | 'name-taken' | 'not-found'> {
1703
1633
  // The operation transaction serializes the existence/name checks and rename.
@@ -1708,10 +1638,10 @@ function teamMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql
1708
1638
  return 'ok'
1709
1639
  },
1710
1640
  async deleteTeam(id: string): Promise<boolean> {
1711
- return Number((await deleteTeamStmt.run(id)).changes) > 0
1641
+ return anyChanged(await deleteTeamStmt.run(id))
1712
1642
  },
1713
1643
  async setTeamHidden(id: string, hidden: boolean, now: number): Promise<boolean> {
1714
- return Number((await setTeamHiddenStmt.run(hidden ? 1 : 0, now, id)).changes) > 0
1644
+ return anyChanged(await setTeamHiddenStmt.run(hidden ? 1 : 0, now, id))
1715
1645
  },
1716
1646
  async getTeam(id: string): Promise<{ id: string; slug: string; name: string; hidden: boolean } | null> {
1717
1647
  const row = (await selectTeamStmt.get(id)) as TeamRow | undefined
@@ -1759,23 +1689,14 @@ function teamMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql
1759
1689
  },
1760
1690
  async listTeams(): Promise<AdminTeam[]> {
1761
1691
  const teams = (await selectTeamsStmt.all()) as TeamRow[]
1762
- const reposByTeam = new Map<string, TeamRepoLink[]>()
1763
- for (const r of (await selectTeamReposStmt.all()) as TeamRepoRow[]) {
1764
- const list = reposByTeam.get(r.teamId) ?? []
1765
- list.push({ repoId: r.repoId, fullName: r.fullName, path: r.path })
1766
- reposByTeam.set(r.teamId, list)
1767
- }
1768
- const membersByTeam = new Map<string, TeamMember[]>()
1769
- for (const m of (await selectTeamMembersStmt.all()) as TeamMemberRow[]) {
1770
- const list = membersByTeam.get(m.teamId) ?? []
1771
- list.push({ userId: m.userId, login: m.login, dependencies: m.viewDependencies === 1, security: m.viewSecurity === 1 })
1772
- membersByTeam.set(m.teamId, list)
1773
- }
1692
+ const reposByTeam = Map.groupBy((await selectTeamReposStmt.all()) as TeamRepoRow[], r => r.teamId)
1693
+ const membersByTeam = Map.groupBy((await selectTeamMembersStmt.all()) as TeamMemberRow[], m => m.teamId)
1774
1694
  return teams.map((t) => ({
1775
1695
  id: t.id, slug: t.slug, name: t.name,
1776
1696
  hidden: t.hidden === 1,
1777
- repos: reposByTeam.get(t.id) ?? [],
1778
- members: membersByTeam.get(t.id) ?? [],
1697
+ repos: (reposByTeam.get(t.id) ?? []).map(r => ({ repoId: r.repoId, fullName: r.fullName, path: r.path })),
1698
+ members: (membersByTeam.get(t.id) ?? []).map(m => ({ userId: m.userId, login: m.login,
1699
+ dependencies: m.viewDependencies === 1, security: m.viewSecurity === 1 })),
1779
1700
  }))
1780
1701
  },
1781
1702
  async setTeamRepo(teamId: string, repoId: number, path: string | null): Promise<void> {
@@ -1786,16 +1707,15 @@ function teamMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql
1786
1707
  },
1787
1708
  async removeTeamRepo(teamId: string, repoId: number, path?: string | null): Promise<boolean> {
1788
1709
  const result = path === undefined ? (await deleteTeamRepoStmt.run(teamId, repoId)) : (await deleteTeamRepoPathStmt.run(teamId, repoId, path ?? ''))
1789
- return Number(result.changes) > 0
1710
+ return anyChanged(result)
1790
1711
  },
1791
1712
  async setTeamMember(teamId: string, userId: string, perms: TeamUserPermissions): Promise<void> {
1792
1713
  await upsertTeamMemberStmt.run(teamId, userId, perms.dependencies ? 1 : 0, perms.security ? 1 : 0)
1793
1714
  },
1794
1715
  async removeTeamMember(teamId: string, userId: string): Promise<boolean> {
1795
- return Number((await deleteTeamMemberStmt.run(teamId, userId)).changes) > 0
1716
+ return anyChanged(await deleteTeamMemberStmt.run(teamId, userId))
1796
1717
  },
1797
1718
  }
1798
- return methods
1799
1719
  }
1800
1720
 
1801
1721
  // `triageHistoryLimit`: events kept per finding in the triage trail; 0 (the
@@ -1868,7 +1788,7 @@ export function createManagedMethods(db: ManagedSql, options: ManagedDbOptions =
1868
1788
  return row == null ? null : ownSession(row)
1869
1789
  },
1870
1790
  async createViewSession(view, now) {
1871
- if (Number((await insertViewSessionStmt.run(view.id, view.csrfToken, now, view.userId, view.viewerSessionId, now)).changes) === 0) return false
1791
+ if (!anyChanged(await insertViewSessionStmt.run(view.id, view.csrfToken, now, view.userId, view.viewerSessionId, now))) return false
1872
1792
  await deleteOtherViewsStmt.run(view.viewerSessionId, view.id)
1873
1793
  return true
1874
1794
  },
@@ -1902,7 +1822,7 @@ export function createManagedMethods(db: ManagedSql, options: ManagedDbOptions =
1902
1822
  },
1903
1823
  async setUserRole(id, role) {
1904
1824
  if (role !== 'admin') await deleteDemotedViewsStmt.run(id)
1905
- return Number((await updateRoleStmt.run(role, Date.now(), id)).changes) > 0
1825
+ return anyChanged(await updateRoleStmt.run(role, Date.now(), id))
1906
1826
  },
1907
1827
  async setUserTokens(id, tokens) {
1908
1828
  const state = await storageState(db, key)
@@ -1914,12 +1834,11 @@ export function createManagedMethods(db: ManagedSql, options: ManagedDbOptions =
1914
1834
  // one read: a user missing reads as no tokens, no encryption row as none.
1915
1835
  const read = (await stmts.selectTokensStateStmt.get(id)) as StoredTokens & Parameters<typeof storageStateOf>[0] & { userId: string | null; stateId: number | null }
1916
1836
  const state = storageStateOf(read.stateId == null ? undefined : read, key)
1917
- const row = read.userId == null ? undefined : read
1918
- if (row == null || row.access == null) return null
1919
- if (row.encrypted && !state) throw new Error('Encrypted tokens without storage encryption state')
1920
- if (!row.encrypted && state?.complete) throw new Error('Unexpected plaintext GitHub tokens')
1921
- const value = row.encrypted ? decodeStorageTokens(key!, id, row) : row
1922
- return { accessToken: value.access!, refreshToken: value.refresh, expiresAt: row.exp }
1837
+ if (read.userId == null || read.access == null) return null
1838
+ if (read.encrypted && !state) throw new Error('Encrypted tokens without storage encryption state')
1839
+ if (!read.encrypted && state?.complete) throw new Error('Unexpected plaintext GitHub tokens')
1840
+ const value = read.encrypted ? decodeStorageTokens(key!, id, read) : read
1841
+ return { accessToken: value.access!, refreshToken: value.refresh, expiresAt: read.exp }
1923
1842
  },
1924
1843
  async getUserGithubId(id) {
1925
1844
  const row = (await selectGithubIdStmt.get(id)) as { githubId: number } | undefined