@preventive/triage 1.0.0-alpha.53 → 1.0.0-alpha.55

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 (114) hide show
  1. package/common/bundle-compare-diff.js +28 -9
  2. package/common/bundle-compare-inputs.d.ts +1 -0
  3. package/common/bundle-compare-inputs.js +91 -15
  4. package/common/bundle-comparison.js +14 -7
  5. package/common/default-scan-models.ts +3 -0
  6. package/common/dependency-reviews.d.ts +1 -1
  7. package/common/dependency-reviews.js +1 -1
  8. package/common/managed/finding-detail.d.ts +1 -1
  9. package/common/managed/finding-detail.js +7 -7
  10. package/common/managed/routes.js +6 -2
  11. package/common/managed/team-app.d.ts +7 -0
  12. package/common/managed/team-app.js +31 -7
  13. package/common/managed/team-filters.js +26 -0
  14. package/common/workspace-app.js +19 -7
  15. package/out/activity.js +4 -4
  16. package/out/{chunk-NE2UGKRJ.js → chunk-3TFOB75M.js} +4 -3
  17. package/out/chunk-4EMM6UCD.js +1 -0
  18. package/out/chunk-4ISO5F7Y.js +7 -0
  19. package/out/chunk-4XIH7YTX.js +1 -0
  20. package/out/chunk-5PKS6FVK.js +2 -0
  21. package/out/chunk-6GAPL5ZA.js +42 -0
  22. package/out/chunk-6W5BMATD.js +1 -0
  23. package/out/{chunk-WFYLMF6Z.js → chunk-74AEKRES.js} +1 -1
  24. package/out/{chunk-YA4ETCFU.js → chunk-ATTKQVZH.js} +1 -1
  25. package/out/chunk-CGKPGHST.js +6 -0
  26. package/out/chunk-DEVAORP2.js +1 -0
  27. package/out/chunk-E3LFSUDJ.js +9 -0
  28. package/out/chunk-G3LY2FV4.js +1 -0
  29. package/out/chunk-HAZKDK4M.js +4 -0
  30. package/out/chunk-HOB3YPS5.js +1 -0
  31. package/out/{chunk-2K6UN3PC.js → chunk-IZ6MYRYB.js} +1 -1
  32. package/out/{chunk-KOGNQDSJ.js → chunk-J2FWBXFV.js} +1 -1
  33. package/out/{chunk-MYGJBYYJ.js → chunk-J4CLTPOR.js} +1 -1
  34. package/out/chunk-JFL7WLRV.js +1 -0
  35. package/out/chunk-JMG5DXII.js +2 -0
  36. package/out/chunk-JOXLZXMI.js +1 -0
  37. package/out/chunk-M37X4LCF.js +14 -0
  38. package/out/chunk-M3Y6SLC4.js +1 -0
  39. package/out/chunk-NXATZJQ2.js +1 -0
  40. package/out/chunk-PAD2JHZT.js +1 -0
  41. package/out/chunk-PKQBEPZU.js +244 -0
  42. package/out/chunk-PTFQKLKO.js +1 -0
  43. package/out/chunk-QMVOEBWC.js +13 -0
  44. package/out/{chunk-SXV2T5C4.js → chunk-QRKFPLA4.js} +1 -1
  45. package/out/chunk-RRBIJL2B.js +1 -0
  46. package/out/{chunk-GDPCLSOS.js → chunk-SYXT3SFP.js} +1 -1
  47. package/out/chunk-TOXMUOIW.js +5 -0
  48. package/out/chunk-UCP3JRE2.js +1 -0
  49. package/out/chunk-VRX2APNA.js +9 -0
  50. package/out/chunk-WMFDQS2L.js +11 -0
  51. package/out/chunk-WREU7JAG.js +1 -0
  52. package/out/chunk-WST3LUUL.js +1 -0
  53. package/out/{chunk-JEFZTVNX.js → chunk-X655SAHV.js} +1 -1
  54. package/out/chunk-Y5ZHFNBD.js +2 -0
  55. package/out/chunk-YF4M5OCI.js +1 -0
  56. package/out/chunk-Z667U2UJ.js +1 -0
  57. package/out/chunk-ZFXCWNXC.js +52 -0
  58. package/out/chunk-ZQHLECTI.js +1 -0
  59. package/out/client-managed-import.js +1 -1
  60. package/out/client-managed.js +27 -26
  61. package/out/compare.js +14 -14
  62. package/out/dialogs.js +36 -51
  63. package/out/graph.js +17 -15
  64. package/out/index.html +28 -12
  65. package/out/prism.js +1 -1
  66. package/out/scan.js +2 -2
  67. package/out/terminal.js +232 -232
  68. package/out/view.css +1 -1
  69. package/out/view.js +15 -15
  70. package/package.json +12 -7
  71. package/risk/actions/resolve.js +36 -5
  72. package/risk/index.d.ts +20 -2
  73. package/risk/npm/malware.js +6 -4
  74. package/risk/npm/registry.js +8 -6
  75. package/server-managed/bundle-advisories.ts +56 -74
  76. package/server-managed/bundle-build-worker.js +85 -21
  77. package/server-managed/bundle-build.ts +13 -4
  78. package/server-managed/bundle-dependency-reviews.ts +74 -0
  79. package/server-managed/bundle-validation.ts +32 -0
  80. package/server-managed/db-methods.ts +51 -16
  81. package/server-managed/db-neon.ts +18 -2
  82. package/server-managed/db.ts +11 -2
  83. package/server-managed/github-issue-links.ts +151 -47
  84. package/server-managed/github-pulls.ts +34 -15
  85. package/server-managed/http.ts +227 -12
  86. package/server-managed/index.ts +13 -1
  87. package/server-managed/managed-issues.ts +29 -15
  88. package/server-managed/npm-insights.ts +4 -3
  89. package/server-managed/npm-kept.ts +4 -0
  90. package/server-managed/package-entry-points.ts +37 -9
  91. package/server-managed/pretty-print.ts +7 -5
  92. package/server-managed/public-workspace.ts +2 -2
  93. package/server-managed/repository-actions.ts +7 -4
  94. package/server-managed/repository-browser.ts +11 -4
  95. package/server-managed/repository-risk-audit.ts +4 -5
  96. package/server-managed/repository-risk.ts +4 -4
  97. package/server-managed/sql.ts +2 -1
  98. package/server-managed/stasis-config.ts +55 -0
  99. package/server-managed/team-app-summaries.ts +54 -0
  100. package/server-managed/team-app.ts +52 -31
  101. package/server-managed/team-reports.ts +27 -7
  102. package/server-managed/upstream-cache.ts +41 -32
  103. package/server-managed/workspace-shares.ts +3 -1
  104. package/out/chunk-2ZDZWLFY.js +0 -1
  105. package/out/chunk-7VAWINQF.js +0 -6
  106. package/out/chunk-FMXWXDR4.js +0 -36
  107. package/out/chunk-HT2SSA3V.js +0 -1
  108. package/out/chunk-IZ7POWI3.js +0 -18
  109. package/out/chunk-LJ7XRXFU.js +0 -52
  110. package/out/chunk-QB4CBOX2.js +0 -1
  111. package/out/chunk-TQJDYHVE.js +0 -2
  112. package/out/chunk-TSIFIFBX.js +0 -232
  113. package/out/chunk-VH4XMZIW.js +0 -2
  114. package/out/chunk-WYLQWYLA.js +0 -1
@@ -0,0 +1,74 @@
1
+ // What a bundle's npm dependencies want of review, in a repository that
2
+ // reviews dependencies (repository-dependency-reviews.ts), as its Overview
3
+ // tells it: the package versions it bundles (bundle-advisory-inventory.ts),
4
+ // each as the lockfiles that install it lock it at the commit it was built
5
+ // from, whence their integrities, sources and patches, which reviews are held
6
+ // to (pull-dependency-reviews.ts), judged as the other versions a pull
7
+ // request's lockfiles lock are: by reviews of them whole or compared with any
8
+ // version of their package, else passed by the commit it is reviewed since
9
+ // or the host's reviewed dependencies.
10
+ //
11
+ // Its lockfiles are those its review holds to (lockfile-scope.ts) in its
12
+ // directory or a directory above it, as an install of it reads one there, a
13
+ // workspace's at its root; each version as the nearest of their directories
14
+ // that locks it locks it, every integrity and patch it locks it with. One no
15
+ // lockfile there locks (`unlocked`) can't be reviewed, as there is nothing to
16
+ // hold its reviews to: it fails the review, as one that can't be reviewed
17
+ // does. Where its review holds to none of the lockfiles there, but there are
18
+ // some, its dependencies aren't reviewed (`reviewedIn`).
19
+ import { type CommitLockfiles, lockedIn } from './commit-lockfiles.ts'
20
+ import type { LockedPackage } from './locked-packages.ts'
21
+ import { MAX_LOCKED, type PullDependencies, lockedWith, lockfileFormat } from './pull-dependencies.ts'
22
+ import { MAX_UNREVIEWED } from './pull-dependency-reviews.ts'
23
+
24
+ // A version a bundle holds: its package's name and its version.
25
+ export interface BundledVersion { name: string; version: string }
26
+
27
+ // The directory a lockfile at `path` is in, '' for the repository's root.
28
+ const directoryOf = (path: string) => path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''
29
+ // A bundle's directory as one is compared: without the slashes either end.
30
+ const bundleDirectory = (directory: string) => directory.replaceAll(/^\/+|\/+$/gu, '')
31
+ const depth = (dir: string) => dir === '' ? 0 : dir.split('/').length
32
+
33
+ // Whether the lockfile at `path` may install the bundle in `directory`: one
34
+ // in it, or in a directory above it.
35
+ export function installsBundle(path: string, directory: string): boolean {
36
+ const at = bundleDirectory(directory), dir = directoryOf(path)
37
+ return dir === '' || at === dir || at.startsWith(`${dir}/`)
38
+ }
39
+
40
+ // The versions `bundled` as `read`'s lockfiles (those installing the bundle,
41
+ // read at `commit`) lock them, as one directory of a pull request's
42
+ // lockfiles (pull-dependencies.ts) whose versions it adds none of, each as
43
+ // the nearest of their directories locking it locks it, those past
44
+ // MAX_LOCKED counted (`moreLocked`), and each lockfile left unread a
45
+ // directory of its own failing the review; with those none lock
46
+ // (`unlocked`, as many as MAX_UNREVIEWED, how many more `moreUnlocked`) and
47
+ // how many versions it bundles (`versions`), each once.
48
+ export function bundleDependencies(bundled: BundledVersion[], read: CommitLockfiles, commit: string) {
49
+ const versions = [...new Map(bundled.map(one => [`${one.name}@${one.version}`, one])).values()]
50
+ const byDirectory = new Map<string, string[]>()
51
+ for (const { path } of read.lockfiles) byDirectory.set(directoryOf(path), [...byDirectory.get(directoryOf(path)) ?? [], path])
52
+ // Each directory's versions by their name and version, the nearest first.
53
+ const nearest = [...byDirectory].toSorted(([a], [b]) => depth(b) - depth(a)).map(([dir, paths]) => {
54
+ const locked = new Map<string, LockedPackage[]>()
55
+ for (const pkg of lockedIn(read, path => directoryOf(path) === dir).packages) {
56
+ const key = `${pkg.name}@${pkg.version ?? ''}`
57
+ locked.set(key, [...locked.get(key) ?? [], pkg])
58
+ }
59
+ return { paths, locked }
60
+ })
61
+ const found = new Map<string, LockedPackage>()
62
+ const unlocked: BundledVersion[] = []
63
+ for (const one of versions) {
64
+ const variants = nearest.find(({ locked }) => locked.has(`${one.name}@${one.version}`))?.locked.get(`${one.name}@${one.version}`)
65
+ if (!variants) { unlocked.push(one); continue }
66
+ for (const pkg of variants) if (!found.has(lockedWith(pkg))) found.set(lockedWith(pkg), pkg)
67
+ }
68
+ const locked = [...found.values()]
69
+ const told: PullDependencies = { base: commit, head: commit, cut: false, lockfiles: [
70
+ { paths: nearest.flatMap(({ paths }) => paths), added: [], more: 0, locked: locked.slice(0, MAX_LOCKED), moreLocked: Math.max(0, locked.length - MAX_LOCKED) },
71
+ ...read.unread.map(path => ({ paths: [path], error: lockfileFormat(path) === 'bun' ? 'lockfile-unsupported' : 'lockfile-unreadable' })),
72
+ ] }
73
+ return { told, versions: versions.length, unlocked: unlocked.slice(0, MAX_UNREVIEWED), moreUnlocked: Math.max(0, unlocked.length - MAX_UNREVIEWED) }
74
+ }
@@ -0,0 +1,32 @@
1
+ // A Stasis bundle validated (GET and POST /api/bundles/:id/validation) by
2
+ // Stasis's own validation (`@exodus/stasis/validate`; its rules are in
3
+ // Stasis's doc/validate.md), the repository read the app's way: with its
4
+ // reader's GitHub access, own code by git's blob ids of the commit's listing.
5
+ import { type BundleValidation, type ValidationPlan, followingMoves, validateBundle, validateRepository } from '@exodus/stasis/validate'
6
+ import { createClient } from '@preventive/upstream/github.js'
7
+ import { upstreamGithub } from './github-errors.ts'
8
+
9
+ export { type BundleValidation, type PlannedBundle, validationPlan } from '@exodus/stasis/validate'
10
+
11
+ // The rules a validation was made by, kept with it: one made by others is made again.
12
+ export const BUNDLE_VALIDATION_READ = 3
13
+
14
+ type Options = { deadline?: number }
15
+
16
+ // The bundle `plan`'s dependencies alone, held to their registry, own code unverified for `reason`.
17
+ export const validateDependencies = (plan: ValidationPlan, reason: string, options: Options = {}): Promise<BundleValidation> =>
18
+ validateBundle(plan, { reason }, options)
19
+
20
+ // The bundle `plan` validated at `commit` of `fullName`, read with `token`,
21
+ // built in `directory`: own code held to git's blob ids of the commit's tree
22
+ // as upstream lists it (each listing held to its tree's id), the commit to the
23
+ // repository's own history, the dependencies to the lockfiles installing it;
24
+ // what can't be held to told in the report (own code's `reason`,
25
+ // `lockfileError`), not thrown.
26
+ export function validateAtCommit(plan: ValidationPlan, { fullName, token, commit, directory }: { fullName: string; token: string; commit: string; directory: string },
27
+ options: Options = {}): Promise<BundleValidation> {
28
+ const client = createClient({ token, userAgent: 'deepview-triage' })
29
+ const repository = followingMoves(client, fullName)
30
+ return upstreamGithub(() => validateRepository(plan, { repository, commit, directory },
31
+ { ...options, strict: false, listTree: paths => client.listRepoTree({ repo: repository.name(), sha: commit, paths }) }))
32
+ }
@@ -17,6 +17,7 @@ import { type ManagedIssue, type ManagedIssueStore, managedIssueMethods } from '
17
17
  import type { IssueFixUpdate } from './github-issue-links.ts'
18
18
  import { type BundleBuildLeaseStore, bundleBuildLeaseMethods } from './bundle-build-leases.ts'
19
19
  import { type UpstreamCacheStore, upstreamCacheMethods } from './upstream-cache.ts'
20
+ import { type TeamAppSummaryStore, teamAppSummaryMethods } from './team-app-summaries.ts'
20
21
  import { type ImportTriageStore, importTriageMethods } from './import-triage.ts'
21
22
  import type { ManagedSql } from './sql.ts'
22
23
  import { type WorkspaceShareStore, workspaceShareMethods } from './workspace-shares.ts'
@@ -147,6 +148,9 @@ export interface TeamReportAccessSnapshot extends ReportAccessSnapshot {
147
148
  reportId?: string | null
148
149
  hiddenReportId?: string | null
149
150
  repositories: { repoId: number; github: string; path: string | null }[]
151
+ // By report ID, the content key its catalog entry has (UserTeamReport
152
+ // cacheKey) as read with the rest.
153
+ catalogKeys?: Readonly<Record<string, string>>
150
154
  }
151
155
  export interface ReportAccessSnapshot {
152
156
  user: StoredUser
@@ -206,6 +210,11 @@ export interface RepoDataItem {
206
210
 
207
211
  export type RepoReportItem = Pick<ReportRecord, 'id' | 'filename' | 'sha256' | 'bundleId'>
208
212
 
213
+ // A report that names a bundle: linked to it (bundleId is that bundle's), or
214
+ // declaring its integrity as the bundle it was made from without the link.
215
+ // `readable`: whether the manager asking may read it (as getReportView tells).
216
+ export type BundleReportItem = Pick<ReportRecord, 'id' | 'filename' | 'bundleId'> & { readable: boolean }
217
+
209
218
  // A stored per-finding triage row, with the last writer's login resolved like
210
219
  // listReports (live login, falling back to the durable snapshot). `flagged`
211
220
  // maps the tri-state column: null unset, true/false set. Every field null =
@@ -368,7 +377,7 @@ export interface UserTeam {
368
377
  }
369
378
 
370
379
  // Backend-agnostic store surface (SQLite + PostgreSQL implementations).
371
- export interface ManagedDb extends DependencyReviewStore, RepositoryDependencyReviewStore, ActivityStore, CommentStore, GithubMetadataStore, GithubCommitStore, ManagedIssueStore, BundleBuildLeaseStore, UpstreamCacheStore, WorkspaceShareStore, ImportTriageStore, ManagementStore, ManagementCatalogStore, StorageDb, LinkReportStore, RepositoryAliasStore, TeamNpmScopeStore, GithubLinkStore {
380
+ export interface ManagedDb extends DependencyReviewStore, RepositoryDependencyReviewStore, ActivityStore, CommentStore, GithubMetadataStore, GithubCommitStore, ManagedIssueStore, BundleBuildLeaseStore, UpstreamCacheStore, TeamAppSummaryStore, WorkspaceShareStore, ImportTriageStore, ManagementStore, ManagementCatalogStore, StorageDb, LinkReportStore, RepositoryAliasStore, TeamNpmScopeStore, GithubLinkStore {
372
381
  claimMaintenanceLease(owner: string, now: number, until: number, migration?: boolean): Promise<boolean>
373
382
  finishMaintenanceLease(owner: string, until: number): Promise<void>
374
383
  getFeedState(sessionId: string, now: number): Promise<{ user: Pick<StoredUser, 'id' | 'role'>; catalog: number; annotations: number } | null>
@@ -451,6 +460,10 @@ export interface ManagedDb extends DependencyReviewStore, RepositoryDependencyRe
451
460
  getTeamReportAccessSnapshot(sessionId: string, now: number, teamId: string, reportId?: string | null): Promise<TeamReportAccessSnapshot | null>
452
461
  getReportAccessSnapshot(sessionId: string, now: number, ids: readonly string[]): Promise<ReportAccessSnapshot | null>
453
462
  listReportFilenamesWithBundleHash(bundleId: string, sha256: string): Promise<string[]>
463
+ // The reports linked to a bundle, or whose bundleHashes declared its integrity
464
+ // (bundle_integrity), newest first: what deleting it leaves without code.
465
+ // Each says whether the manager `userId` (none: an admin) may read it.
466
+ listReportsForBundle(bundleId: string, integrity: string, userId?: string): Promise<BundleReportItem[]>
454
467
  deleteReport(id: string): Promise<boolean>
455
468
  // Attach / detach a report's repo + directory link (repoId null = detach);
456
469
  // resolves true iff the report exists. The caller validates repoId and the
@@ -641,15 +654,23 @@ type UserTeamRows = {
641
654
  bundles: (Omit<UserTeamBundle, 'visible'> & { teamId: string; visible: number })[]
642
655
  }
643
656
 
657
+ // A catalog report's content key: its content, where it is, and what its
658
+ // reader may see of it (their grants and role) under the link reports'
659
+ // revision `links`. A team snapshot names it of each report it reads.
660
+ type CatalogReportRow = Pick<UserTeamRows['reports'][number], 'sha256' | 'bundleId' | 'filename' | 'repoId' | 'repoDirectory' | 'repoFullName' | 'dependencies' | 'security'>
661
+ function reportCatalogKey(r: CatalogReportRow, role: string, links: string): string {
662
+ return createHash('sha256').update(JSON.stringify([
663
+ r.sha256, r.bundleId, r.filename, r.repoId, r.repoDirectory, r.repoFullName, r.dependencies, r.security, role, links,
664
+ ])).digest('base64url')
665
+ }
666
+
644
667
  // A user's team catalog from its rows, `links` the link reports' revision.
645
668
  function userTeams(teams: UserTeamRows['teams'], scopes: UserTeamRows['scopes'], links: string, reports: UserTeamRows['reports'], bundles: UserTeamRows['bundles']): UserTeam[] {
646
669
  const reportsByTeam = new Map<string, UserTeamReport[]>()
647
670
  for (const r of reports) {
648
671
  const list = reportsByTeam.get(r.teamId) ?? []
649
- const cacheKey = createHash('sha256').update(JSON.stringify([
650
- r.sha256, r.bundleId, r.filename, r.repoId, r.repoDirectory, r.repoFullName, r.dependencies, r.security, r.role, links,
651
- ])).digest('base64url')
652
- list.push({ id: r.id, slug: r.slug, filename: r.filename, visible: r.visible === 1, analyzer: r.analyzer, repoFullName: r.repoFullName, repoDirectory: r.repoDirectory, cacheKey })
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) })
653
674
  reportsByTeam.set(r.teamId, list)
654
675
  }
655
676
  const bundlesByTeam = new Map<string, UserTeamBundle[]>()
@@ -899,10 +920,10 @@ function prepareStatements(db: ManagedSql) {
899
920
  EXISTS(SELECT 1 FROM managed_team_user tu JOIN managed_team t ON t.id = tu.team_id
900
921
  WHERE tu.user_id = v.uid AND tu.team_id = ? AND t.hidden = 0) AS member,
901
922
  (SELECT json_group_array(json_object('id', x.id, 'filename', x.filename, 'byteSize', x.byteSize, 'sha256', x.sha256,
902
- 'visible', x.visible, 'repoDirectory', x.repoDirectory, 'repoFullName', x.repoFullName,
923
+ 'visible', x.visible, 'bundleId', x.bundleId, 'repoId', x.repoId, 'repoDirectory', x.repoDirectory, 'repoFullName', x.repoFullName,
903
924
  'dependencies', x.dependencies, 'security', x.security) ORDER BY x.id)
904
925
  FROM (SELECT DISTINCT r.id AS id, r.filename AS filename, r.byte_size AS byteSize, r.sha256 AS sha256, r.visible AS visible,
905
- r.repo_directory AS repoDirectory, sr.full_name AS repoFullName,
926
+ r.bundle_id AS bundleId, r.repo_id AS repoId, r.repo_directory AS repoDirectory, sr.full_name AS repoFullName,
906
927
  tu.view_dependencies AS dependencies, tu.view_security AS security
907
928
  FROM managed_team_user tu
908
929
  JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
@@ -917,6 +938,15 @@ function prepareStatements(db: ManagedSql) {
917
938
  FROM viewer v`,
918
939
  ),
919
940
  reportFilenamesWithBundleHashStmt: db.prepare(`SELECT DISTINCT filename FROM managed_report WHERE bundle_id = ? AND sha256 = ?`),
941
+ reportsForBundleStmt: db.prepare(
942
+ `SELECT r.id AS id, r.filename AS filename, r.bundle_id AS bundleId,
943
+ (? IS NULL OR r.uploaded_by = ? OR EXISTS(SELECT 1 FROM managed_team_repo tr
944
+ JOIN managed_team_user tu ON tu.team_id = tr.team_id
945
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
946
+ WHERE tr.repo_id = r.repo_id AND ${REPORT_IN_TEAM_PATH_SQL} AND tu.user_id = ?)) AS readable
947
+ FROM managed_report r WHERE r.bundle_id = ? OR r.bundle_integrity = ?
948
+ ORDER BY r.uploaded_at DESC, r.filename ASC, r.id ASC`,
949
+ ),
920
950
  deleteReportStmt: db.prepare(`DELETE FROM managed_report WHERE id = ?`),
921
951
  setReportRepoStmt: db.prepare(`UPDATE managed_report SET repo_id = ?, repo_directory = ? WHERE id = ?`),
922
952
  setReportVisibleStmt: db.prepare(`UPDATE managed_report SET visible = ? WHERE id = ?`),
@@ -982,7 +1012,7 @@ function prepareStatements(db: ManagedSql) {
982
1012
  WHERE c.finding_id IN (SELECT id FROM requested)) AS comments,
983
1013
  (SELECT json_group_array(json_object('findingId', i.finding_id, 'repoId', i.repo_id, 'repository', i.repository, 'requestId', i.request_id,
984
1014
  'issueUrl', i.issue_url, 'autoFixUrl', i.auto_fix_url, 'autoFixCheckedAt', i.auto_fix_checked_at,
985
- 'createdBy', i.created_by, 'createdAt', i.created_at) ORDER BY i.finding_id)
1015
+ 'duplicateOfUrl', i.duplicate_of_url, 'createdBy', i.created_by, 'createdAt', i.created_at) ORDER BY i.finding_id)
986
1016
  FROM managed_finding_issue i WHERE i.finding_id IN (SELECT id FROM requested)) AS issues`,
987
1017
  ),
988
1018
  selectTriageFixesStmt: db.prepare(`SELECT DISTINCT fix FROM managed_finding_triage
@@ -996,7 +1026,8 @@ function prepareStatements(db: ManagedSql) {
996
1026
  FROM managed_finding_triage t WHERE t.finding_id IN (SELECT id FROM requested)) AS triage,
997
1027
  (SELECT json_group_array(json_object('id', c.id, 'version', c.version) ORDER BY c.id)
998
1028
  FROM managed_finding_comment c WHERE c.finding_id IN (SELECT id FROM requested)) AS comments,
999
- (SELECT json_group_array(json_object('findingId', i.finding_id, 'issueUrl', i.issue_url, 'autoFixUrl', i.auto_fix_url) ORDER BY i.finding_id)
1029
+ (SELECT json_group_array(json_object('findingId', i.finding_id, 'issueUrl', i.issue_url, 'autoFixUrl', i.auto_fix_url,
1030
+ 'duplicateOfUrl', i.duplicate_of_url) ORDER BY i.finding_id)
1000
1031
  FROM managed_finding_issue i WHERE i.finding_id IN (SELECT id FROM requested) AND i.issue_url IS NOT NULL) AS issues`,
1001
1032
  ),
1002
1033
  insertBundleStmt: db.prepare(
@@ -1368,21 +1399,19 @@ function reportMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedS
1368
1399
  const user: StoredUser = { id: session.uid, login: session.login, name: session.name, avatarUrl: session.avatar, role: session.role }
1369
1400
  if (user.role === 'none' || !session.member) return { user, teamId: null, reports: [], repositories: [] }
1370
1401
  const whole = user.role === 'admin' || user.role === 'manage'
1371
- const rows = jsonRows<{
1372
- id: string; filename: string; byteSize: number; sha256: string; repoDirectory: string
1373
- repoFullName: string | null; dependencies: number; security: number; visible: number
1374
- }>(session.reports)
1402
+ const rows = jsonRows<CatalogReportRow & { id: string; byteSize: number; visible: number }>(session.reports)
1375
1403
  // Only privileged callers can receive a hidden row from this query. Give
1376
1404
  // that individual preview its own capacity; published report selections
1377
1405
  // still use the complete workspace for cross-report classification.
1378
1406
  const hidden = rows.find(row => row.id === reportId && row.visible === 0)
1379
1407
  const selected = hidden ? [hidden] : rows
1380
1408
  const repositories = jsonRows<TeamReportAccessSnapshot['repositories'][number]>(session.repositories)
1381
- return { user, teamId, reportId, hiddenReportId: hidden?.id ?? null, repositories, linkRevision: linkRevisionOf(jsonRows(session.links)), reports: selected.map(row => ({
1409
+ const links = linkRevisionOf(jsonRows(session.links))
1410
+ return { user, teamId, reportId, hiddenReportId: hidden?.id ?? null, repositories, linkRevision: links, reports: selected.map(row => ({
1382
1411
  id: row.id, filename: row.filename, byteSize: row.byteSize, sha256: row.sha256,
1383
1412
  repo: { github: row.repoFullName, directory: row.repoDirectory },
1384
1413
  permissions: { dependencies: whole || row.dependencies === 1, security: whole || row.security === 1 },
1385
- })) }
1414
+ })), catalogKeys: Object.fromEntries(selected.map(row => [row.id, reportCatalogKey(row, user.role, links)])) }
1386
1415
  },
1387
1416
  async getReportAccessSnapshot(sessionId: string, now: number, ids: readonly string[]): Promise<ReportAccessSnapshot | null> {
1388
1417
  const session = await stmts.selectReportSnapshotStmt.get(sessionId, now, JSON.stringify([...new Set(ids)])) as
@@ -1405,6 +1434,11 @@ function reportMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedS
1405
1434
  const rows = (await stmts.reportFilenamesWithBundleHashStmt.all(bundleId, sha256)) as { filename: string }[]
1406
1435
  return rows.map(row => row.filename)
1407
1436
  },
1437
+ async listReportsForBundle(bundleId: string, integrity: string, userId?: string): Promise<BundleReportItem[]> {
1438
+ const rows = await stmts.reportsForBundleStmt.all(userId ?? null, userId ?? null, userId ?? null, bundleId, integrity) as
1439
+ (Omit<BundleReportItem, 'readable'> & { readable: unknown })[]
1440
+ return rows.map(row => ({ id: row.id, filename: row.filename, bundleId: row.bundleId, readable: Boolean(row.readable) }))
1441
+ },
1408
1442
  async deleteReport(id: string): Promise<boolean> {
1409
1443
  return Number((await deleteReportStmt.run(id)).changes) > 0
1410
1444
  },
@@ -1800,6 +1834,7 @@ export function createManagedMethods(db: ManagedSql, options: ManagedDbOptions =
1800
1834
  ...repositoryDependencyReviewMethods(db),
1801
1835
  ...bundleBuildLeaseMethods(db),
1802
1836
  ...upstreamCacheMethods(db),
1837
+ ...teamAppSummaryMethods(db),
1803
1838
  async claimMaintenanceLease(owner, now, until, migration = false) {
1804
1839
  return !!await claimLeaseStmt.get(migration ? 2 : 1, owner, until, now)
1805
1840
  },
@@ -1906,7 +1941,7 @@ export function createManagedMethods(db: ManagedSql, options: ManagedDbOptions =
1906
1941
  // Recheck access inside the same write transaction as the derived field.
1907
1942
  const current = await methods.getTeamReportAccessSnapshot(sessionId, Date.now(), snapshot.teamId!, snapshot.reportId)
1908
1943
  if (!current?.teamId || JSON.stringify(current) !== JSON.stringify(snapshot)) return false
1909
- for (const update of updates) await methods.setManagedIssueAutoFix(update.findingId, update.issueUrl, update.previous, update.next, update.checkedAt)
1944
+ for (const update of updates) await methods.setManagedIssueTracking(update.findingId, update.issueUrl, update.previous, update.next, update.checkedAt)
1910
1945
  return true
1911
1946
  },
1912
1947
  ...workspaceShareMethods(db),
@@ -14,6 +14,7 @@ import { GITHUB_COMMIT_SCHEMA, GITHUB_METADATA_SCHEMA, GITHUB_STATE_REASON_COLUM
14
14
  import { MANAGED_ISSUE_SCHEMA } from './managed-issues.ts'
15
15
  import { BUNDLE_BUILD_LEASE_SCHEMA } from './bundle-build-leases.ts'
16
16
  import { UPSTREAM_CACHE_SCHEMA } from './upstream-cache.ts'
17
+ import { TEAM_APP_SUMMARY_SCHEMA } from './team-app-summaries.ts'
17
18
  import { COMMENT_SCHEMA } from './comments.ts'
18
19
  import { ACTIVITY_SCHEMA, uploadAction } from './activity.ts'
19
20
  import { type ManagedSqlDriver, scopeManagedMethods } from './sql.ts'
@@ -39,7 +40,7 @@ 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
40
41
  // a cold start: a database with no versions table yet (undefined_table) has
41
42
  // none. Outside a transaction, so the failed read aborts nothing.
42
- const SCHEMA_VERSIONS = 33
43
+ const SCHEMA_VERSIONS = 35
43
44
  async function currentSchema(db: PgConnection): Promise<boolean> {
44
45
  try {
45
46
  const { rows } = await db.query(`SELECT count(*) AS n FROM managed_schema_version WHERE version BETWEEN 1 AND ${SCHEMA_VERSIONS}`)
@@ -202,6 +203,20 @@ async function migrateDependencyReviewPatches(db: PgConnection): Promise<void> {
202
203
  await db.query('INSERT INTO managed_schema_version VALUES (33)')
203
204
  }
204
205
 
206
+ async function migrateTeamAppSummaries(db: PgConnection): Promise<void> {
207
+ if ((await db.query('SELECT version FROM managed_schema_version WHERE version = 34')).rows.length > 0) return
208
+ await db.query(postgresSchema(TEAM_APP_SUMMARY_SCHEMA))
209
+ await db.query('INSERT INTO managed_schema_version VALUES (34)')
210
+ }
211
+
212
+ // The issue a saved one was closed as a duplicate of, none known of those
213
+ // checked before.
214
+ async function migrateIssueDuplicates(db: PgConnection): Promise<void> {
215
+ if ((await db.query('SELECT version FROM managed_schema_version WHERE version = 35')).rows.length > 0) return
216
+ await db.query('ALTER TABLE managed_finding_issue ADD COLUMN IF NOT EXISTS duplicate_of_url TEXT')
217
+ await db.query('INSERT INTO managed_schema_version VALUES (35)')
218
+ }
219
+
205
220
  async function initialize(db: PgConnection): Promise<void> {
206
221
  if (await currentSchema(db)) return
207
222
  await db.query('BEGIN')
@@ -276,7 +291,8 @@ async function initialize(db: PgConnection): Promise<void> {
276
291
  await db.query(postgresSchema(revisionSchema(true)) + '; INSERT INTO managed_schema_version VALUES (11)')
277
292
  }
278
293
  for (const migrate of [migrateRepositoryDefaultCache, migrateBundleBuildLeases, migrateBundleVisibility, migrateLinkReports, migrateRepositoryAliases, migrateHiddenTeams, migrateIssueFixes, migrateBundleProvenance, migrateUpstreamCache, migrateBundleBuildConditions, migrateSessionUploadKeys, migrateViewSessions, migrateGithubCommits, migrateTeamNpmScopes, migrateDependencyReviews, migrateGithubLinks, migrateRepositoryDependencyReviews,
279
- migrateRepositoryDependencyReviewLockfiles, migrateRepoUploadIndexes, migrateDependencyReviewShasums, migrateDependencyReviewPatches]) await migrate(db)
294
+ migrateRepositoryDependencyReviewLockfiles, migrateRepoUploadIndexes, migrateDependencyReviewShasums, migrateDependencyReviewPatches, migrateTeamAppSummaries,
295
+ migrateIssueDuplicates]) await migrate(db)
280
296
  await db.query('COMMIT')
281
297
  } catch (err) {
282
298
  await db.query('ROLLBACK')
@@ -16,6 +16,7 @@ import { GITHUB_COMMIT_SCHEMA, GITHUB_METADATA_SCHEMA, GITHUB_STATE_REASON_COLUM
16
16
  import { MANAGED_ISSUE_SCHEMA } from './managed-issues.ts'
17
17
  import { BUNDLE_BUILD_LEASE_SCHEMA } from './bundle-build-leases.ts'
18
18
  import { UPSTREAM_CACHE_SCHEMA } from './upstream-cache.ts'
19
+ import { TEAM_APP_SUMMARY_SCHEMA } from './team-app-summaries.ts'
19
20
  import { managedTableRenames } from './db-table-names.ts'
20
21
  import { type ManagedDb, type ManagedDbOptions, createManagedMethods } from './db-methods.ts'
21
22
  import { createSqliteDriver, scopeManagedMethods } from './sql.ts'
@@ -69,10 +70,16 @@ export function openSqliteManagedDb(path: string, options: ManagedDbOptions = {}
69
70
  const db = new DatabaseSync(path)
70
71
  try {
71
72
  db.exec('PRAGMA journal_mode = WAL;')
72
- db.exec('PRAGMA synchronous = FULL;')
73
+ // The bootstrap below commits each schema statement on its own: under
74
+ // FULL, ~120 fsyncs on a new file. Each step checks the schema before
75
+ // changing it and only reads outside the database, so a step lost to a
76
+ // power failure reruns on the next open, and WAL stays consistent under
77
+ // NORMAL. FULL is restored after it; the next commit's fsync of the WAL
78
+ // persists the bootstrap's frames too.
79
+ db.exec('PRAGMA synchronous = NORMAL;')
73
80
  db.exec('PRAGMA foreign_keys = ON;')
74
81
  migrateManagedTableNames(db)
75
- db.exec(MANAGED_SCHEMA + GITHUB_METADATA_SCHEMA + GITHUB_COMMIT_SCHEMA + MANAGED_ISSUE_SCHEMA + STORAGE_SCHEMA + BUNDLE_BUILD_LEASE_SCHEMA + UPSTREAM_CACHE_SCHEMA)
82
+ db.exec(MANAGED_SCHEMA + GITHUB_METADATA_SCHEMA + GITHUB_COMMIT_SCHEMA + MANAGED_ISSUE_SCHEMA + STORAGE_SCHEMA + BUNDLE_BUILD_LEASE_SCHEMA + UPSTREAM_CACHE_SCHEMA + TEAM_APP_SUMMARY_SCHEMA)
76
83
  ensureColumn(db, 'managed_selected_repo', 'cached_default_branch', 'TEXT')
77
84
  ensureColumn(db, 'managed_session', 'upload_key', 'TEXT')
78
85
  ensureColumn(db, 'managed_session', 'viewer_session', 'TEXT REFERENCES managed_session(id) ON DELETE CASCADE')
@@ -123,6 +130,7 @@ export function openSqliteManagedDb(path: string, options: ManagedDbOptions = {}
123
130
  ensureColumn(db, 'managed_team', 'dependency_review', 'INTEGER NOT NULL DEFAULT 0')
124
131
  ensureColumn(db, 'managed_finding_issue', 'auto_fix_url', 'TEXT')
125
132
  ensureColumn(db, 'managed_finding_issue', 'auto_fix_checked_at', 'INTEGER')
133
+ ensureColumn(db, 'managed_finding_issue', 'duplicate_of_url', 'TEXT')
126
134
  ensureColumn(db, 'managed_selected_repo', 'active', 'INTEGER NOT NULL DEFAULT 1')
127
135
  for (const [column, type] of REPOSITORY_DEPENDENCY_REVIEW_COLUMNS) ensureColumn(db, 'managed_selected_repo', column, type)
128
136
  for (const [column, type] of DEPENDENCY_REVIEW_COLUMNS) ensureColumn(db, 'managed_dependency_review', column, type)
@@ -133,6 +141,7 @@ export function openSqliteManagedDb(path: string, options: ManagedDbOptions = {}
133
141
  initCommentMethods(db)
134
142
  initActivityMethods(db)
135
143
  db.exec(revisionSchema())
144
+ db.exec('PRAGMA synchronous = FULL;')
136
145
  } catch (err) {
137
146
  try { db.close() } catch {}
138
147
  throw err