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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/out/activity.js +2 -2
  2. package/out/{chunk-U6JONPTN.js → chunk-3DOSBILK.js} +1 -1
  3. package/out/{chunk-A4HSJCXG.js → chunk-CJVMNJDZ.js} +2 -2
  4. package/out/chunk-HGWFRZNC.js +267 -0
  5. package/out/{chunk-3TJCEPHF.js → chunk-JZAROLQT.js} +1 -1
  6. package/out/{chunk-4GHLPL2P.js → chunk-LRWB6QVO.js} +1 -1
  7. package/out/{chunk-G5JKKNZF.js → chunk-SMNFBOLO.js} +1 -1
  8. package/out/{chunk-ZPIUN4FW.js → chunk-SZTCJVZJ.js} +1 -1
  9. package/out/{chunk-VRFGZ6MV.js → chunk-UTYWTUTC.js} +1 -1
  10. package/out/client-managed.js +28 -28
  11. package/out/compare.js +13 -13
  12. package/out/dialogs.js +15 -15
  13. package/out/graph.js +1 -1
  14. package/out/index.html +5 -5
  15. package/out/prism.js +1 -1
  16. package/out/scan.js +2 -2
  17. package/out/view.css +1 -1
  18. package/out/view.js +7 -7
  19. package/package.json +3 -1
  20. package/risk/index.d.ts +15 -0
  21. package/risk/index.js +1 -1
  22. package/risk/npm/assess.js +21 -3
  23. package/risk/npm/registry.js +16 -7
  24. package/server-managed/bundle-advisories.ts +97 -0
  25. package/server-managed/config.ts +1 -1
  26. package/server-managed/github-issue-links.ts +1 -1
  27. package/server-managed/github-metadata.ts +6 -1
  28. package/server-managed/github-pulls.ts +43 -10
  29. package/server-managed/http.ts +170 -52
  30. package/server-managed/known-listings.ts +112 -0
  31. package/server-managed/npm-packages.ts +10 -2
  32. package/server-managed/npm-risk.ts +31 -8
  33. package/server-managed/public-workspace.ts +6 -7
  34. package/server-managed/pull-dependency-reviews.ts +64 -13
  35. package/server-managed/queue.ts +1 -1
  36. package/server-managed/repository-dependency-reviews.ts +38 -0
  37. package/server-managed/repository-risk-audit.ts +83 -16
  38. package/server-managed/repository-risk.ts +33 -12
  39. package/server-managed/team-app.ts +1 -1
  40. package/server-managed/team-progress.ts +77 -0
  41. package/server-managed/upstream-cache.ts +42 -23
  42. package/out/chunk-7KUZQB6S.js +0 -267
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.89",
3
+ "version": "1.0.0-alpha.90",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -163,6 +163,7 @@
163
163
  "server-managed/npm-provenance.ts",
164
164
  "server-managed/kept.ts",
165
165
  "server-managed/kept-briefly.ts",
166
+ "server-managed/known-listings.ts",
166
167
  "server-managed/npm-kept.ts",
167
168
  "server-managed/npm-loads.ts",
168
169
  "server-managed/npm-delta.ts",
@@ -243,6 +244,7 @@
243
244
  "server-managed/team-icons.ts",
244
245
  "server-managed/team-app.ts",
245
246
  "server-managed/team-app-summaries.ts",
247
+ "server-managed/team-progress.ts",
246
248
  "server-managed/team-reports.ts",
247
249
  "server-managed/triage-response.ts",
248
250
  "server-managed/type-only.ts",
package/risk/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  // Hand-written against index.js; a change to either belongs with the other.
2
2
  import type { CacheStore } from '@preventive/upstream/npm.js'
3
+ import type { Client } from '@preventive/upstream/github.js'
3
4
  import type { Entry } from '@preventive/archive/tar.js'
4
5
 
5
6
  // How severe a stamp or a finding is, the most first: `critical` red, `high`
@@ -73,6 +74,11 @@ export interface AssessNpmOptions {
73
74
  // to be sent, as upstream sends it none npm's registry doesn't serve
74
75
  // anyone. True unless given.
75
76
  osv?: boolean
77
+ // A client of upstream's (its github.js createClient): with `advisories`,
78
+ // those the version's GitHub repository publishes count too, its listing
79
+ // kept in `cache` (`github/advisories`, and `npm/public`, upstream's own).
80
+ // Where GitHub fails to give it, npm's alone. None unless given.
81
+ github?: Client | null
76
82
  // Whether a package is the caller's own, as its own scopes take: a new
77
83
  // dependency on one is told no tier nor age, nor is npm asked of it. None
78
84
  // unless given.
@@ -159,6 +165,15 @@ export interface NpmAssessment {
159
165
 
160
166
  export function assessNpm(name: string, version: string, options?: AssessNpmOptions): Promise<NpmAssessment>
161
167
 
168
+ // The `malware` finding of a version alone, as assessNpm finds it: its
169
+ // package taken down by npm, and npm's advisories of malware naming it,
170
+ // OSV's too where `osv` is (true unless given false), and with `github` its
171
+ // repository's, read and kept as assessNpm reads and keeps them, none of its
172
+ // files nor its dependencies read; null where neither tells of any. Throws
173
+ // an NpmRiskError as assessNpm does where npm has no such package or version
174
+ // (nor malware explaining one removed), or can't be asked.
175
+ export function npmMalware(name: string, version: string, options?: Pick<AssessNpmOptions, 'cache' | 'packument' | 'now' | 'signal' | 'osv' | 'github'>): Promise<Finding | null>
176
+
162
177
  // Readies, at once, the downloads assessNpm asks of each of these packages
163
178
  // that can be, kept in `cache` as it keeps them, so that their assessments
164
179
  // ask npm none: those kept within a week, and unscoped ones, asked of npm 128
package/risk/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // What calls for a look at a package version, or a repository's GitHub
2
2
  // Actions, for a reviewer: risk's heuristics, apart from any view of them.
3
3
  // See README.md.
4
- export { assessNpm } from './npm/assess.js'
4
+ export { assessNpm, npmMalware } from './npm/assess.js'
5
5
  export { npmMalwareAdvisory } from './npm/malware.js'
6
6
  export { DEFAULT_MINIMUM_RELEASE_AGE } from './npm/release.js'
7
7
  export { NpmRiskError, npmReadyDownload, npmReadyDownloads } from './npm/registry.js'
@@ -166,11 +166,29 @@ async function addedDependencies(added, published, context, owned, unusedKeys =
166
166
  return told
167
167
  }
168
168
 
169
+ // The malware finding of `version` of package `name` alone, as assessNpm
170
+ // finds it (npmMalwareFinding): its package taken down by npm, and npm's
171
+ // advisories of malware naming it, OSV's too where `osv` is (true unless
172
+ // given false), and with `github` its repository's, read and kept as
173
+ // assessNpm reads and keeps them (`cache`, `packument`, `now`, `signal`),
174
+ // none of its files nor its dependencies read; null where neither tells of
175
+ // any. Throws as assessNpm does where npm has no such package or version
176
+ // (nor malware explaining one removed), or can't be asked.
177
+ export async function npmMalware(name, version, { cache, packument, now = Date.now(), signal, osv = true, github = null } = {}) {
178
+ const context = { cache, packument, now, signal }
179
+ const facts = await npmPackageFacts(name, version, null, context)
180
+ const advised = await npmVersionAdvisories(name, version, osv, context, facts.versions.get(version)?.repo ?? null, github)
181
+ const malware = npmMalwareFinding({ takenDown: facts.takenDown, advisories: advised })
182
+ if (!malware && !facts.versions.has(version)) throw new NpmRiskError('version-not-found', `npm has no ${name}@${version}`)
183
+ return malware
184
+ }
185
+
169
186
  // What calls for a look at `version` of package `name`, as JSON holds it:
170
187
  // malware first (malware.js npmMalwareFinding: its package taken down by
171
188
  // npm, and npm's advisories of malware naming it where `advisories`, true
172
189
  // unless given false, has them asked, OSV's too where `osv` is, true unless
173
- // given false, as a private package's name is never sent it); against `oldVersion` where given,
190
+ // given false, as a private package's name is never sent it, and with
191
+ // `github`, its repository's, registry.js npmVersionAdvisories); against `oldVersion` where given,
174
192
  // true for the one of its versions most likely free of what an attack
175
193
  // injects, as risk picks it by npm's document (old-version.js npmOldVersion;
176
194
  // none where none is below it), the one it picked said as `oldVersion`
@@ -192,7 +210,7 @@ async function addedDependencies(added, published, context, owned, unusedKeys =
192
210
  // to read. Throws an NpmRiskError (registry.js), its `code` saying why, where
193
211
  // npm has no such package or version (nor malware explaining one removed),
194
212
  // answers past risk's bounds, or can't be asked.
195
- export async function assessNpm(name, version, { oldVersion = null, fromEmpty = false, minimumReleaseAge = DEFAULT_MINIMUM_RELEASE_AGE, popularity = true, cache, packument, tarball, now = Date.now(), signal, downloads = true, dependencies = true, advisories = true, osv = true, owned = () => false } = {}) {
213
+ export async function assessNpm(name, version, { oldVersion = null, fromEmpty = false, minimumReleaseAge = DEFAULT_MINIMUM_RELEASE_AGE, popularity = true, cache, packument, tarball, now = Date.now(), signal, downloads = true, dependencies = true, advisories = true, osv = true, github = null, owned = () => false } = {}) {
196
214
  const context = { cache, packument, tarball, now, signal }
197
215
  const facts = await npmPackageFacts(name, version, oldVersion, context)
198
216
  const old = facts.oldVersion
@@ -201,7 +219,7 @@ export async function assessNpm(name, version, { oldVersion = null, fromEmpty =
201
219
  // other, so all are asked at once, and waited on in this order, so that a
202
220
  // failure fails it as the first of them failing would.
203
221
  const listed = facts.versions.has(version)
204
- const advised = settledLater(advisories ? npmVersionAdvisories(name, version, osv, context) : Promise.resolve([]))
222
+ const advised = settledLater(advisories ? npmVersionAdvisories(name, version, osv, context, facts.versions.get(version)?.repo ?? null, github) : Promise.resolve([]))
205
223
  const keeping = listed ? settledLater(lasting(name, version, old, facts, context, fromEmpty)) : null
206
224
  const counting = listed && downloads && popularity ? settledLater(npmDownloads(name, context)) : null
207
225
  const malware = npmMalwareFinding({ takenDown: facts.takenDown, advisories: await advised })
@@ -35,6 +35,7 @@
35
35
  // is `tarball-conflict`.
36
36
  import { advisories } from '@preventive/upstream/advisories.js'
37
37
  import { getTarball } from '@preventive/upstream/npm.js'
38
+ import { getRepo } from '@preventive/upstream/package.js'
38
39
  import { compareVersions, satisfies, validRange } from '@preventive/upstream/semver.js'
39
40
  import { npmTokenFor } from '../../common/npm-token.js'
40
41
  import { npmVersionManifest } from './manifest.js'
@@ -155,7 +156,8 @@ const releasesOf = (doc, deprecated = {}) => versionsOf(doc).map(version => {
155
156
  // What risk reads of `version` of a package, of the one it is compared with
156
157
  // (`oldVersion`: one, null for none, or true for the one old-version.js
157
158
  // npmOldVersion picks of its versions, by its document), and of the package:
158
- // `versions`, each one's `{ manifest, published, dist }`, those of them npm
159
+ // `versions`, each one's `{ manifest, published, dist, repo }` (`repo` the
160
+ // GitHub repository it names, as upstream reads one), those of them npm
159
161
  // removed since they were published (`removed`, each one's when), none
160
162
  // picked to compare a removed one with, `deprecated`, by version, whether
161
163
  // npm's security team took the package down (`takenDown`, its latest version
@@ -190,7 +192,9 @@ export async function npmPackageFacts(name, version, oldVersion, context) {
190
192
  if (!json && isTime(doc.time?.[at])) { removed.set(at, doc.time[at]); return null }
191
193
  if (!json) throw new NpmRiskError('version-not-found', `npm has no ${name}@${at}`)
192
194
  const { deprecated: _, ...manifest } = npmVersionManifest(json)
193
- return { manifest, published: isTime(doc.time?.[at]) ? doc.time[at] : null, dist: { tarball: json.dist?.tarball, integrity: json.dist?.integrity } }
195
+ let repo = null
196
+ try { repo = getRepo(json).github ?? null } catch {}
197
+ return { manifest, published: isTime(doc.time?.[at]) ? doc.time[at] : null, dist: { tarball: json.dist?.tarball, integrity: json.dist?.integrity }, repo }
194
198
  }
195
199
  const opened = factsOf(version)
196
200
  const deprecated = Object.fromEntries(Object.entries(doc.versions ?? {}).filter(([, json]) => typeof json?.deprecated === 'string' && json.deprecated !== '').map(([at, json]) => [at, json.deprecated]))
@@ -217,16 +221,21 @@ export async function npmPackageFacts(name, version, oldVersion, context) {
217
221
  // url?, title?, malware }`, whether it is of malware as upstream tells it, an
218
222
  // advisory of npm's an OSV record of malware names among them; kept
219
223
  // ADVISORIES_MS, those kept with no `malware` asked again, and given up on
220
- // once `signal` aborts.
221
- export async function npmVersionAdvisories(name, version, osv, context) {
224
+ // once `signal` aborts. With `github`, a client of upstream's, those `repo`
225
+ // (npmPackageFacts's) publishes too, as upstream's `repoAdvisories` reads
226
+ // them, its listing kept in the cache: where that fails, npm's alone.
227
+ export async function npmVersionAdvisories(name, version, osv, context, repo = null, github = null) {
222
228
  const what = `${name}@${version}`
229
+ const repository = repo !== null && github !== null
223
230
  const { rows } = await kept(context, 'risk/npm/advisories', what, async () => {
224
231
  context.signal?.throwIfAborted()
225
- const asked = await untilAborted(advisories([{ ecosystem: 'npm', name, versions: [version] }], { cache: false, osv }), context.signal).catch(error => {
232
+ const ask = withRepository => untilAborted(advisories([{ ecosystem: 'npm', name, versions: [version], ...withRepository ? { github: repo } : {} }],
233
+ withRepository ? { cache: context.cache || false, osv, github, repoAdvisories: true } : { cache: false, osv }), context.signal)
234
+ const asked = await (repository ? ask(true).catch(() => { context.signal?.throwIfAborted(); return ask(false) }) : ask(false)).catch(error => {
226
235
  throw context.signal?.aborted ? error : new NpmRiskError(error?.status === 429 ? 'upstream-busy' : 'upstream-unavailable', `advisories of ${what} couldn't be had: ${error.message}`)
227
236
  })
228
- return { at: context.now, osv, rows: asked.map(({ id, url, title, malware }) => ({ id, ...url ? { url } : {}, ...title ? { title } : {}, malware: malware === true })) }
229
- }, hit => context.now - hit.at < ADVISORIES_MS && hit.osv === osv && hit.rows.every(row => typeof row.malware === 'boolean'))
237
+ return { at: context.now, osv, repository, rows: asked.map(({ id, url, title, malware }) => ({ id, ...url ? { url } : {}, ...title ? { title } : {}, malware: malware === true })) }
238
+ }, hit => context.now - hit.at < ADVISORIES_MS && hit.osv === osv && Boolean(hit.repository) === repository && hit.rows.every(row => typeof row.malware === 'boolean'))
230
239
  return rows
231
240
  }
232
241
 
@@ -1,6 +1,11 @@
1
1
  import { type Advisory, type CacheStore, type Package, advisories } from '@preventive/upstream/advisories.js'
2
2
  import { type Client, HttpError, createClient } from '@preventive/upstream/github.js'
3
+ import { getRepo } from '@preventive/upstream/package.js'
3
4
  import { USER_AGENT } from './github-requests.ts'
5
+ import { knownListings } from './known-listings.ts'
6
+ import { lru } from './lru.ts'
7
+ import type { NpmVersionStore } from './npm-packages.ts'
8
+ import { LISTINGS, type UpstreamCacheStore, auditedKeys } from './upstream-cache.ts'
4
9
 
5
10
  export const ADVISORIES_TIMEOUT_MS = 30_000
6
11
 
@@ -77,3 +82,95 @@ export async function fetchBundleAdvisories(packages: Package[], signal: AbortSi
77
82
  if (onAbort) signal.removeEventListener('abort', onAbort)
78
83
  }
79
84
  }
85
+
86
+ // advisoryGithubClient with the token `token` gives, asked for once as it is
87
+ // first needed (none where that fails), so that an answer asking GitHub only
88
+ // behind it asks for none before it.
89
+ export function lazyGithubClient(token: () => Promise<string | null>): Client {
90
+ let client: Promise<Client> | undefined
91
+ const ready = () => client ??= token().catch(() => null).then(value => advisoryGithubClient(value, new AbortController().signal))
92
+ return Object.fromEntries(Object.keys(createClient({ token: null })).map(name => [name, async (...args: unknown[]) =>
93
+ await ((await ready()) as unknown as Record<string, (...args: unknown[]) => Promise<unknown>>)[name]!(...args)])) as unknown as Client
94
+ }
95
+
96
+ // As upstream orders advisories: by ecosystem, then package.
97
+ const order = (a: string, b: string) => Number(a > b) - Number(a < b)
98
+ const byPackage = (a: Advisory, b: Advisory) => order(a.ecosystem, b.ecosystem) || order(a.name, b.name)
99
+
100
+ // A bundle's advisories, as fetchBundleAdvisories asks them, with those its
101
+ // packages' repositories publish as known (known-listings.ts): each listing
102
+ // as kept, however old, none asked of GitHub before the answer, nor any
103
+ // package's repository looked up where it names none. With `recheck`, each
104
+ // listing is asked of GitHub first, waited on for half the audit's time at
105
+ // most, and each package's repository looked up where it names none, as
106
+ // upstream's `repoAdvisories` does; those not had by then `unchecked`, and
107
+ // answered as known. GitHub is asked with the token `githubToken` gives.
108
+ export async function fetchKnownBundleAdvisories(packages: Package[], signal: AbortSignal, { recheck = false, details = false, debug = false, githubToken = () => Promise.resolve(null), db, behind }: {
109
+ recheck?: boolean; details?: boolean; debug?: boolean; githubToken?: () => Promise<string | null>; db: UpstreamCacheStore; behind: (work: Promise<unknown>) => void
110
+ }): Promise<{ status: 200; body: Advisory[]; unchecked?: string[] } | { status: 502; body: { error: string } }> {
111
+ const github = lazyGithubClient(githubToken)
112
+ const cache = knownListings(db, signal, { github, behind, keys: auditedKeys(packages, true),
113
+ recheck: recheck ? AbortSignal.any([signal, AbortSignal.timeout(ADVISORIES_TIMEOUT_MS / 2)]) : undefined })
114
+ const named = (pkg: Package) => recheck || pkg.github !== undefined
115
+ const audit = (part: Package[], repoAdvisories: boolean) => fetchBundleAdvisories(part, signal, { debug, repoAdvisories, details, github, cache })
116
+ const [repositories, rest] = await Promise.all([audit(packages.filter(named), true), audit(packages.filter(pkg => !named(pkg)), false)])
117
+ if (repositories.status !== 200) return repositories
118
+ if (rest.status !== 200) return rest
119
+ const unchecked = recheck ? [...cache.unchecked].toSorted() : []
120
+ return { status: 200, body: [...repositories.body, ...rest.body].toSorted(byPackage), ...unchecked.length > 0 ? { unchecked } : {} }
121
+ }
122
+
123
+ // Those `asked` by the GitHub repository each version names, as its document
124
+ // kept (npm-kept.ts) does, as a scan keeps them assessing each: a package's
125
+ // versions naming one repository together, and those naming another apart;
126
+ // and whether any version's document isn't kept, its repository unknown. A
127
+ // version's never changes once published, so each is held here too (null
128
+ // where it names none).
129
+ const versionRepositories = lru<string | null>(50_000)
130
+ export async function versionsRepositories(store: NpmVersionStore, asked: { name: string; versions: string[] }[]): Promise<{ packages: { name: string; versions: string[]; github: string }[]; unknown: boolean }> {
131
+ const versions = asked.flatMap(({ name, versions: each }) => each.map(version => ({ name, version })))
132
+ const unread = versions.filter(({ name, version }) => versionRepositories.get(`${name}@${version}`) === undefined)
133
+ const kept = unread.length > 0 ? await store.readMany?.(unread).catch(() => null) : null
134
+ for (const [key, { json }] of kept ?? []) {
135
+ try { versionRepositories.set(key, getRepo(json).github ?? null) } catch {}
136
+ }
137
+ const named = new Map<string, { name: string; versions: string[]; github: string }>()
138
+ let unknown = false
139
+ for (const { name, version } of versions) {
140
+ const github = versionRepositories.get(`${name}@${version}`)
141
+ unknown ||= github === undefined
142
+ if (!github) continue
143
+ const key = `${name}\0${github.toLowerCase()}`
144
+ const pkg = named.get(key)
145
+ if (pkg) pkg.versions.push(version)
146
+ else named.set(key, { name, versions: [version], github })
147
+ }
148
+ return { packages: [...named.values()], unknown }
149
+ }
150
+
151
+ // What packages' repositories (`github`) publish of their versions, as
152
+ // upstream's `repoAdvisories` tells them, their listings as known
153
+ // (known-listings.ts): upstream asked of those a listing names alone, its
154
+ // registry's and OSV's ones left out. GitHub not waited on, but with `wait`,
155
+ // which asks each listing not fresh first, until `wait` aborts: one not had
156
+ // by then as known. `again` where one wasn't had fresh. A name given with
157
+ // more than one repository, its versions naming each, is asked of each.
158
+ export async function fetchKnownRepositoryAdvisories(packages: (Package & { github: string })[], signal: AbortSignal, { db, github, behind, wait, debug = false }: {
159
+ db: UpstreamCacheStore; github: Client; behind: (work: Promise<unknown>) => void; wait?: AbortSignal | undefined; debug?: boolean
160
+ }): Promise<{ advisories: Advisory[]; again: boolean }> {
161
+ const cache = knownListings(db, signal, { github, behind, keys: auditedKeys(packages, true), wait })
162
+ const listed = await Promise.all(packages.map(pkg => cache.read(LISTINGS, pkg.github.toLowerCase()) as Promise<{ advisories: { ranges?: { ecosystem?: string; name?: string }[] }[] }>))
163
+ const named = packages.filter((pkg, at) => listed[at]!.advisories.some(({ ranges }) => ranges?.some(range => range.ecosystem === pkg.ecosystem && range.name === pkg.name)))
164
+ // Upstream takes a name with one repository an audit: one with more in as many.
165
+ const audits: (typeof named)[] = [], seen = new Map<string, number>()
166
+ for (const pkg of named) {
167
+ const key = `${pkg.ecosystem}\0${pkg.name}`
168
+ const at = seen.get(key) ?? 0
169
+ seen.set(key, at + 1)
170
+ ;(audits[at] ??= []).push(pkg)
171
+ }
172
+ const audited = await Promise.all(audits.map(part => fetchBundleAdvisories(part, signal, { debug, repoAdvisories: true, github, cache })))
173
+ const failed = audited.find(each => each.status !== 200)
174
+ if (failed) throw new Error((failed.body as { error: string }).error)
175
+ return { advisories: audited.flatMap(each => (each.body as Advisory[]).filter(row => row.source === 'repository')), again: cache.unchecked.size > 0 }
176
+ }
@@ -21,7 +21,7 @@ export interface ManagedConfig {
21
21
  vercelPreview?: boolean
22
22
  serverless?: boolean
23
23
  // Upstream's disk cache (setCacheDir) for audits and bundle builds: its default
24
- // location, or null for none, as on Vercel, where the database keeps listings.
24
+ // location, or null for none, as on Vercel; the database keeps listings either way.
25
25
  upstreamCacheDir?: string | null
26
26
  debug: boolean
27
27
  allowShare: boolean
@@ -4,6 +4,7 @@ import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
4
4
  import type { IssueTracking, ManagedIssue } from './managed-issues.ts'
5
5
  import { ensureUserAccessToken } from './github-oauth.ts'
6
6
  import { GITHUB_API, USER_AGENT } from './github-requests.ts'
7
+ import { githubFixKey as jobKey } from './github-metadata.ts'
7
8
  import { allowedRepositories, deadlineFetch, lookupFixes } from './github-pulls.ts'
8
9
  import { isId } from './github-values.ts'
9
10
 
@@ -35,7 +36,6 @@ const linkedFields = (cursor: string | null) => 'duplicateOf { number repository
35
36
  // How many issues a saved one is followed through, each closed as a
36
37
  // duplicate of the next: each is another request after the last.
37
38
  const MAX_DUPLICATE_HOPS = 5
38
- const jobKey = (repoId: number, kind: Job['kind'], number: number) => `${repoId}:${kind}:${number}`
39
39
  const issueUrlOf = (repo: Repository, number: number) => `https://github.com/${repo.github}/issues/${number}`
40
40
  // Whether GitHub named a repository as one is: by its stable ID and a name.
41
41
  const isRepositoryReference = (ref: RepositoryReference): ref is { databaseId: number; nameWithOwner: string } =>
@@ -1,4 +1,4 @@
1
- import type { GithubFixStatus, GithubIssueClosedReason } from '../common/github-pr.ts'
1
+ import type { GithubFixRef, GithubFixStatus, GithubIssueClosedReason } from '../common/github-pr.ts'
2
2
  import type { ManagedSql } from './sql.ts'
3
3
 
4
4
  export interface GithubMetadata {
@@ -53,6 +53,11 @@ export function githubCommitKey(repoId: number, sha: string): string {
53
53
  return `${repoId}:${sha}`
54
54
  }
55
55
 
56
+ // An issue's or pull request's metadata key, by its repository's stable ID.
57
+ export function githubFixKey(repoId: number, kind: GithubFixRef['kind'], number: number): string {
58
+ return `${repoId}:${kind}:${number}`
59
+ }
60
+
56
61
  // Successful GitHub reads are shared and retained without eviction. The stable
57
62
  // repository ID in the key survives renames, but is never an access grant.
58
63
  // Callers must verify current user -> team -> repo grants plus either recently
@@ -1,7 +1,8 @@
1
1
  import { type GithubFixRef, type GithubFixResult, type GithubFixStatus, githubIssueClosedReason, isGithubRepoName, parseGithubFixUrl } from '../common/github-pr.ts'
2
2
  import type { ManagedConfig } from './config.ts'
3
3
  import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
4
- import type { GithubMetadata, GithubRepositoryVisibility } from './github-metadata.ts'
4
+ import type { ManagedIssue } from './managed-issues.ts'
5
+ import { type GithubMetadata, type GithubRepositoryVisibility, githubFixKey } from './github-metadata.ts'
5
6
  import { ensureUserAccessToken } from './github-oauth.ts'
6
7
  import { GITHUB_API, githubHeaders, repoApi } from './github-requests.ts'
7
8
 
@@ -182,14 +183,12 @@ function readsOf<Entry extends [string, GithubFixRef]>(entries: Entry[], metadat
182
183
  // including for admins. Only recently verified public repos skip that check.
183
184
  export async function lookupFixes(config: ManagedConfig, db: ManagedDb, snapshot: TeamReportAccessSnapshot, urls: string[], fetchImpl: typeof fetch = globalThis.fetch): Promise<GithubFixResult[]> {
184
185
  const allowed = allowedRepositories(snapshot)
185
- const parsed = urls.map(parseGithubFixUrl)
186
186
  const jobs = new Map<string, GithubFixRef>()
187
- const keys = parsed.map(ref => {
188
- const repo = ref && allowed.get(ref.repo.toLowerCase())
189
- if (!ref || !repo) return null
190
- const key = `${repo.repoId}:${ref.kind}:${ref.number}`
191
- jobs.set(key, { ...ref, repo: repo.github })
192
- return key
187
+ const keys = urls.map(url => {
188
+ const found = allowedFixRef(allowed, url)
189
+ if (!found) return null
190
+ jobs.set(found.key, { ...found.ref, repo: found.repo.github })
191
+ return found.key
193
192
  })
194
193
  if (jobs.size === 0) return []
195
194
  const now = Date.now()
@@ -252,6 +251,40 @@ export async function lookupFixes(config: ManagedConfig, db: ManagedDb, snapshot
252
251
  })
253
252
  }
254
253
 
255
- export function storedFixUrls(fixes: string[]): string[] {
256
- return [...new Set(fixes.filter(fix => parseGithubFixUrl(fix)))].toSorted()
254
+ // The issue or pull request `url` names, where it is one of `allowed`'s, with
255
+ // its metadata key; null for any other URL.
256
+ function allowedFixRef(allowed: Map<string, Repository>, url: string | null) {
257
+ const ref = parseGithubFixUrl(url)
258
+ const repo = ref && allowed.get(ref.repo.toLowerCase())
259
+ return ref && repo ? { ref, repo, key: githubFixKey(repo.repoId, ref.kind, ref.number) } : null
260
+ }
261
+
262
+ export type CachedFixStatus = { kind: GithubFixRef['kind']; status: GithubFixStatus }
263
+
264
+ // The status each of `urls` naming a workspace repository's issue or pull
265
+ // request had when GitHub was last read for it (lookupFixes), by its cache
266
+ // key, so that one item linked by several URLs or teams is one; GitHub is not
267
+ // asked, and an item never read is left out. Only the status is told, never
268
+ // a title or description.
269
+ export async function cachedFixStatuses(db: ManagedDb, snapshot: TeamReportAccessSnapshot, urls: readonly string[]): Promise<Map<string, CachedFixStatus>> {
270
+ const allowed = allowedRepositories(snapshot)
271
+ const kinds = new Map<string, GithubFixRef['kind']>()
272
+ for (const url of urls) {
273
+ const found = allowedFixRef(allowed, url)
274
+ if (found) kinds.set(found.key, found.ref.kind)
275
+ }
276
+ const cached = await db.listGithubMetadata([...kinds.keys()])
277
+ return new Map(cached.map(entry => [entry.key, { kind: kinds.get(entry.key)!, status: entry.status }]))
278
+ }
279
+
280
+ export function storedFixUrls(fixes: readonly (string | null)[]): string[] {
281
+ return [...new Set(fixes.filter((fix): fix is string => parseGithubFixUrl(fix) !== null))].toSorted()
282
+ }
283
+
284
+ // The issue and pull request links a workspace's findings have, each once:
285
+ // their Fix links naming GitHub (storedFixUrls), and their saved issues
286
+ // (visibleManagedIssues) with the pull requests fixing them and the issues
287
+ // they were closed as duplicates of.
288
+ export function workspaceFixUrls(fixes: readonly (string | null)[], issues: readonly ManagedIssue[]): string[] {
289
+ return [...new Set([...storedFixUrls(fixes), ...issues.flatMap(issue => [issue.issueUrl, issue.autoFixUrl, issue.duplicateOfUrl].filter(url => url !== null))])]
257
290
  }