@preventive/triage 1.0.0-alpha.83 → 1.0.0-alpha.85

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 (37) hide show
  1. package/common/npm-token.d.ts +2 -0
  2. package/common/npm-token.js +14 -0
  3. package/out/activity.js +2 -2
  4. package/out/{chunk-PXHEOOK4.js → chunk-7I6SZIJU.js} +1 -1
  5. package/out/{chunk-L5BLCHQD.js → chunk-EZ62FJ5T.js} +44 -44
  6. package/out/{chunk-LVVIDDT6.js → chunk-YU3IUQY6.js} +1 -1
  7. package/out/{chunk-C27LVCIE.js → chunk-ZJDDTEL2.js} +1 -1
  8. package/out/client-managed.js +28 -30
  9. package/out/compare.js +1 -1
  10. package/out/dialogs.js +1 -1
  11. package/out/graph.js +1 -1
  12. package/out/index.html +3 -3
  13. package/out/scan.js +1 -1
  14. package/out/view.css +1 -1
  15. package/out/view.js +1 -1
  16. package/package.json +6 -2
  17. package/risk/npm/registry.js +4 -5
  18. package/server-managed/bundle-build-worker.js +1 -1
  19. package/server-managed/bundle-build.ts +10 -10
  20. package/server-managed/db-methods.ts +6 -1
  21. package/server-managed/http.ts +62 -16
  22. package/server-managed/npm-kept.ts +9 -0
  23. package/server-managed/npm-loads.ts +6 -6
  24. package/server-managed/npm-packages.ts +6 -6
  25. package/server-managed/pulse-walk.ts +164 -0
  26. package/server-managed/repository-history.ts +18 -2
  27. package/server-managed/repository-pulse.ts +5 -73
  28. package/server-managed/repository-risk-assess.ts +63 -2
  29. package/server-managed/repository-risk-caches.ts +19 -0
  30. package/server-managed/repository-risk-kept.ts +86 -0
  31. package/server-managed/repository-risk-read.ts +45 -9
  32. package/server-managed/repository-risk.ts +59 -68
  33. package/server-managed/stasis-dependencies.ts +66 -16
  34. package/server-managed/team-app-summaries.ts +2 -1
  35. package/server-managed/team-app.ts +12 -6
  36. package/server-managed/team-reports.ts +4 -3
  37. /package/out/{chunk-LFPRRRJE.js → chunk-ULI2BIWN.js} +0 -0
@@ -0,0 +1,164 @@
1
+ // The default branch's year as the Pulse reads it from its commits
2
+ // (repository-pulse.ts): walked from its head as the Commits tab reads and
3
+ // keeps its pages (yearCommits), and what a walk found kept as those pages,
4
+ // for the next to go on from (keptWalk).
5
+ import { windowsOn } from './history-windows.ts'
6
+ import type { KeptStore } from './npm-kept.ts'
7
+ import { type HistoryCommit, type HistoryPages, historyFrom } from './repository-history.ts'
8
+
9
+ const DAY_MS = 24 * 60 * 60_000
10
+ // A year of more commits than this is counted by GitHub's statistics: read a
11
+ // page at a time, it would take a hundred queries. Of those not kept, as
12
+ // many queries are made an answer as YEAR_QUERIES, each reading on from as
13
+ // many commits as YEAR_STARTS.
14
+ export const YEAR_COMMITS = 10_000
15
+ const YEAR_QUERIES = 5
16
+ const YEAR_STARTS = 10
17
+ // Commits are read on from as far as this before the year, a commit's clock
18
+ // not always later than its parents': one dated before the year may have a
19
+ // parent dated in it.
20
+ const YEAR_SKEW_MS = 30 * DAY_MS
21
+
22
+ // The year's commits read so far: all of them, or as far back as asked
23
+ // (`commits`, `from`), else how many (`read`), and whether past
24
+ // YEAR_COMMITS (`tooMany`); and every one walked within it, for the next
25
+ // walk to go on from (`walked`).
26
+ type YearCommits = ({ complete: true; commits: HistoryCommit[]; passed: HistoryCommit[]; from: number | null } | { complete: false; read: number; tooMany: boolean })
27
+ & { walked: HistoryCommit[] }
28
+
29
+ // The commits from `head` made since `since`, as the Commits tab reads and
30
+ // keeps them (`pages`, historyFrom): on from the parents of those since (or
31
+ // as much as YEAR_SKEW_MS before), not yet listed, YEAR_STARTS at a time,
32
+ // till none is left; the pages kept read
33
+ // of the store, those not of GitHub, as many queries of them as
34
+ // YEAR_QUERIES, the rest left for the next to ask (`complete` false, how
35
+ // many are `read`); more than YEAR_COMMITS, too many (`tooMany`). Read
36
+ // whole, those it was read on past besides (`passed`): undated, or dated
37
+ // before it, a clock behind, the branch's commits since beneath them. Read
38
+ // no further than `need` asks, those since it read whole (`complete`, `from`
39
+ // the newest of those read whose parents are not, every commit after it
40
+ // read; null, the year read whole). How many are read so far `told` as they
41
+ // are. Those a walk before found (`known`, from this head or another) taken
42
+ // as they are wherever it reaches one, and every one beneath it found, none
43
+ // read again: a walk cut short goes on where it stopped, and one from a head
44
+ // moved on reads only what is new.
45
+ export async function yearCommits(fullName: string, token: string, head: string, since: number, pages: HistoryPages,
46
+ fetchImpl: typeof fetch = globalThis.fetch, need = since, told: (read: number) => void = () => {},
47
+ known: ReadonlyMap<string, HistoryCommit> = new Map()): Promise<YearCommits> {
48
+ const found = new Map<string, HistoryCommit>()
49
+ const tried = new Set<string>()
50
+ const within = (commit: HistoryCommit) => commit.committedAt === null || commit.committedAt >= since - YEAR_SKEW_MS
51
+ const dated = (commit: HistoryCommit) => commit.committedAt !== null && commit.committedAt >= since
52
+ const read = () => [...found.values()].filter(dated).length
53
+ const passed = () => [...found.values()].filter(commit => !dated(commit) && within(commit))
54
+ // Those within it, and the parents beneath them read past it, where a walk stops.
55
+ const walked = () => onEdge([...found.values()], within)
56
+ const parentsUnread = () => [...new Set([...found.values()].filter(within).flatMap(commit => commit.parents))].filter(sha => !found.has(sha) && !tried.has(sha))
57
+ // Those of `shas` found before taken, and those beneath them as far back
58
+ // as it needs, no further, as a walk reading them stops: whether any was.
59
+ const needed = (commit: HistoryCommit) => within(commit) && (need <= since || commit.committedAt === null || commit.committedAt >= need)
60
+ const take = (shas: string[]) => {
61
+ const waiting = shas.filter(sha => known.has(sha) && !found.has(sha))
62
+ const any = waiting.length > 0
63
+ for (let sha = waiting.pop(); sha !== undefined; sha = waiting.pop()) {
64
+ const commit = known.get(sha)!
65
+ if (found.has(sha)) continue
66
+ found.set(sha, commit)
67
+ if (needed(commit)) for (const parent of commit.parents) if (known.has(parent) && !found.has(parent)) waiting.push(parent)
68
+ }
69
+ return any
70
+ }
71
+ let queries = 0
72
+ let windowed = false
73
+ let starts = [head]
74
+ while (starts.length > 0) {
75
+ // Those not read yet, the head before any, else the parents of those
76
+ // read, no later than the newest of them (but for a clock behind): read
77
+ // whole after it.
78
+ const unread = new Set(starts)
79
+ const from = found.size === 0 ? Number.POSITIVE_INFINITY : Math.max(Number.NEGATIVE_INFINITY, ...[...found.values()]
80
+ .filter(commit => commit.parents.some(sha => unread.has(sha))).map(commit => commit.committedAt ?? Number.POSITIVE_INFINITY))
81
+ if (need > since && from < need) return { complete: true, commits: [...found.values()].filter(dated), passed: passed(), from, walked: walked() }
82
+ if (take(starts)) {
83
+ told(read())
84
+ if (read() > YEAR_COMMITS) return { complete: false, read: read(), tooMany: true, walked: walked() }
85
+ starts = parentsUnread()
86
+ continue
87
+ }
88
+ if (queries >= YEAR_QUERIES) return { complete: false, read: read(), tooMany: false, walked: walked() }
89
+ // The pages kept read first; once past them, the rest read at once by
90
+ // when its commits were made (history-windows.ts windowsOn), as far back
91
+ // as it needs, the year's as far as its commits are followed.
92
+ const next: Awaited<ReturnType<typeof windowsOn>> | null = windowed || found.size === 0 ? null
93
+ : await windowsOn(fullName, token, head, starts, found, need > since ? need : since - YEAR_SKEW_MS, from, pages, fetchImpl, queries)
94
+ windowed ||= next?.windowed === true
95
+ queries += next?.queries ?? 0
96
+ const batch = (next?.batch ?? starts).slice(0, YEAR_STARTS)
97
+ for (const sha of batch) tried.add(sha)
98
+ const got = batch.length > 0 ? await historyFrom(fullName, token, batch, pages, fetchImpl) : { commits: [], read: 0 }
99
+ if (got.read > 0) queries++
100
+ for (const commit of got.commits) if (!found.has(commit.sha)) found.set(commit.sha, commit)
101
+ told(read())
102
+ if (read() > YEAR_COMMITS) return { complete: false, read: read(), tooMany: true, walked: walked() }
103
+ starts = parentsUnread()
104
+ }
105
+ return { complete: true, commits: [...found.values()].filter(dated), passed: passed(), from: null, walked: walked() }
106
+ }
107
+
108
+ // Of `commits`, those `within` a year and the parents of those beneath it.
109
+ function onEdge(commits: HistoryCommit[], within: (commit: HistoryCommit) => boolean) {
110
+ const beneath = new Set(commits.filter(within).flatMap(commit => commit.parents))
111
+ return commits.filter(commit => within(commit) || beneath.has(commit.sha))
112
+ }
113
+
114
+ // What walks of a repository's year found (yearCommits `walked`), kept in
115
+ // `store` by `key`, not as its commits but as the pages of its history that
116
+ // hold them (`tops`), every tab's, read as any reads them (`pages`), and only
117
+ // those none holds as they are (`extra`, read in windows of time and kept as
118
+ // no page): read as a walk begins, for it to go on from (`known`), and kept
119
+ // as one ends with what it found, those before the year read (`since`, and
120
+ // YEAR_SKEW_MS more) let go; none kept past WALK_BYTES. A walk reads and
121
+ // keeps its pages through the `pages` it gives, each told as it is.
122
+ export type KeptWalk = { tops: string[]; extra: HistoryCommit[] }
123
+ const WALK_BYTES = 8 * 1024 * 1024
124
+ const walkedCommit = (commit: Partial<HistoryCommit> | null) => typeof commit?.sha === 'string' && Array.isArray(commit.parents) && Array.isArray(commit.named)
125
+ && commit.additions != null
126
+ export function keptWalk(store: KeptStore<KeptWalk>, key: string, pages: HistoryPages) {
127
+ // The pages read or kept, by their tops, each its commits' ids.
128
+ const held = new Map<string, string[]>()
129
+ const told = (read: Map<string, HistoryCommit[]>) => {
130
+ for (const [top, commits] of read) held.set(top, commits.map(commit => commit.sha))
131
+ return read
132
+ }
133
+ const walking: HistoryPages = {
134
+ read: async tops => told(await pages.read(tops)),
135
+ ...pages.readFirst ? { readFirst: async (first: string[], then: string[]) => {
136
+ const read = await pages.readFirst!(first, then)
137
+ told(read.pages)
138
+ return read
139
+ } } : {},
140
+ write: (top, commits) => {
141
+ told(new Map([[top, commits]]))
142
+ return pages.write(top, commits)
143
+ },
144
+ }
145
+ return {
146
+ pages: walking,
147
+ async read(): Promise<Map<string, HistoryCommit>> {
148
+ const walk = (await store.read(key))?.value
149
+ if (!Array.isArray(walk?.tops) || !Array.isArray(walk.extra)) return new Map()
150
+ const read = await walking.read(walk.tops.filter(top => typeof top === 'string'))
151
+ return new Map([...walk.extra.filter(walkedCommit), ...[...read.values()].flat()].map(commit => [commit.sha, commit]))
152
+ },
153
+ async write(known: ReadonlyMap<string, HistoryCommit>, walked: HistoryCommit[], since: number) {
154
+ if (walked.every(commit => known.has(commit.sha))) return
155
+ const all = new Map(known)
156
+ for (const commit of walked) all.set(commit.sha, commit)
157
+ const commits = new Set(onEdge([...all.values()], commit => commit.committedAt === null || commit.committedAt >= since - YEAR_SKEW_MS).map(commit => commit.sha))
158
+ const tops = [...held].filter(([, shas]) => shas.some(sha => commits.has(sha))).map(([top]) => top)
159
+ const covered = new Set(tops.flatMap(top => held.get(top)!))
160
+ const walk = { tops, extra: [...commits].filter(sha => !covered.has(sha)).map(sha => all.get(sha)!) }
161
+ if (JSON.stringify(walk).length <= WALK_BYTES) await store.write(key, walk, Date.now())
162
+ },
163
+ }
164
+ }
@@ -200,7 +200,7 @@ export const commitsQuery = (count: number, alias: string, fields: string) => `q
200
200
  export const commitIds = (shas: string[]) => Object.fromEntries(shas.map((sha, at) => [`o${at}`, sha]))
201
201
 
202
202
  // The latest commits of each tip, by its id, `b<n>` the `n`th's.
203
- const historiesQuery = (count: number) => `${commitsQuery(count, 'b', `history(first: ${ALL_DEPTH}) { pageInfo { hasNextPage } nodes { ...historyCommit } }`)}
203
+ const historiesQuery = (count: number, depth = ALL_DEPTH) => `${commitsQuery(count, 'b', `history(first: ${depth}) { pageInfo { hasNextPage } nodes { ...historyCommit } }`)}
204
204
  ${COMMIT_FRAGMENT}`
205
205
 
206
206
  export type GraphCommit = { oid?: unknown; message?: unknown; committedDate?: unknown; additions?: unknown; deletions?: unknown
@@ -261,7 +261,8 @@ async function readPages(fullName: string, token: string | null, tops: string[],
261
261
  }
262
262
  const [owner, name] = fullName.split('/') as [string, string]
263
263
  await inBatches(tops, PAGES_PER_QUERY, PAGES_PARALLEL, async batch => {
264
- const data = await githubGraphql(historiesQuery(batch.length), { owner, name, ...commitIds(batch) }, token, fetchImpl) as Histories
264
+ const ask = async (depth: number) => await githubGraphql(historiesQuery(batch.length, depth), { owner, name, ...commitIds(batch) }, token, fetchImpl) as Histories
265
+ const data = batch.length === 1 ? await shorter(ask) : await ask(ALL_DEPTH)
265
266
  const nodes = batch.map((_, at) => data?.repository?.[`b${at}`]?.history?.nodes ?? [])
266
267
  await linkNoreplyUsers(nodes.flat().flatMap(commitActors), token, fetchImpl)
267
268
  await Promise.all(batch.map((top, at) => got(top, nodes[at]!.flatMap(node => graphCommit(node) ?? []))))
@@ -372,6 +373,21 @@ const chunked = <T>(items: T[], size: number) => Array.from({ length: Math.ceil(
372
373
  // GitHub stopping a query past its time: in its answer's errors, or as a 502
373
374
  // or 504 of its own.
374
375
  const SLOW = new Set(['github-timeout', 'github-status-502', 'github-status-504'])
376
+ // A page asked for (`ask`, as deep as it is asked) ALL_DEPTH deep, else,
377
+ // GitHub stopping it past its time though asked alone (inBatches), as deep as
378
+ // each of SHORTER_PAGES in turn: its commits' lines are what GitHub takes
379
+ // long on, as a commit changing many large files makes it. A page read
380
+ // shorter is kept so, those beneath it read on from its last as any are.
381
+ const SHORTER_PAGES = [50, 20, 5, 1]
382
+ async function shorter<T>(ask: (depth: number) => Promise<T>, depths = [ALL_DEPTH, ...SHORTER_PAGES]): Promise<T> {
383
+ try {
384
+ return await ask(depths[0]!)
385
+ } catch (err) {
386
+ if (depths.length === 1 || !(err instanceof GithubApiError && SLOW.has(err.message))) throw err
387
+ return await shorter(ask, depths.slice(1))
388
+ }
389
+ }
390
+
375
391
  // `run` for `items` in batches of `size`, as many at once as `parallel`; a
376
392
  // batch GitHub stops past its time run again in halves, down to one alone,
377
393
  // so that one too slow to read fails alone, the others read. The halves
@@ -4,8 +4,8 @@
4
4
  // remove, those an agent made or co-authored, who made them and when in the
5
5
  // week, counted from its commits as the Commits tab reads and keeps them
6
6
  // (repository-history.ts historyFrom), so that only those not kept yet are
7
- // read of GitHub, a few queries an answer, the client asking again for the
8
- // rest; a year past YEAR_COMMITS is counted by GitHub's statistics instead,
7
+ // read of GitHub, a few queries a part, each going on from what the last
8
+ // walked (pulse-walk.ts); a year past YEAR_COMMITS is counted by GitHub's statistics instead,
9
9
  // which GitHub computes when first asked and again once the default branch
10
10
  // moves, answering 202 till they are (told pending, StatsPending, for the
11
11
  // client to ask again). And, since
@@ -19,10 +19,11 @@ import { githubGraphql } from './github-graphql.ts'
19
19
  import { githubJson, repoApi, shareGithubRead } from './github-requests.ts'
20
20
  import { SHA, count, timeOf } from './github-values.ts'
21
21
  import { coauthorsOf } from './commit-coauthors.ts'
22
- import { windowsOn } from './history-windows.ts'
23
- import { type HistoryCommit, type HistoryPages, historyFrom } from './repository-history.ts'
22
+ import type { HistoryCommit } from './repository-history.ts'
24
23
  import { issueState, itemOf, pullState } from './repository-issues.ts'
25
24
 
25
+ export { YEAR_COMMITS, yearCommits } from './pulse-walk.ts'
26
+
26
27
  export const PULSE_WEEKS = [1, 4, 13, 52]
27
28
  // What a year counted from its commits holds, its version: kept years of
28
29
  // another are counted again.
@@ -36,18 +37,6 @@ export const LISTED = 10
36
37
  // updated, GitHub sorting by no merge or close: as many as this are read, and
37
38
  // the latest merged or closed of them listed.
38
39
  const SEARCHED = 50
39
- // A year of more commits than this is counted by GitHub's statistics: read a
40
- // page at a time, it would take a hundred queries. Of those not kept, as
41
- // many queries are made an answer as YEAR_QUERIES, each reading on from as
42
- // many commits as YEAR_STARTS.
43
- export const YEAR_COMMITS = 10_000
44
- const YEAR_QUERIES = 5
45
- const YEAR_STARTS = 10
46
- // Commits are read on from as far as this before the year, a commit's clock
47
- // not always later than its parents': one dated before the year may have a
48
- // parent dated in it.
49
- const YEAR_SKEW_MS = 30 * DAY_MS
50
-
51
40
  // GitHub still computing a statistic.
52
41
  export class StatsPending extends Error {
53
42
  constructor() { super('github-stats-pending') }
@@ -91,11 +80,6 @@ interface PulseLines { weeks: [number, number, number][]; contributors: { login:
91
80
  // The days (`from`, `to`, both days, UTC; `to` none, on) and the authors (GitHub
92
81
  // logins, any of them) a period's pull requests and issues are narrowed to.
93
82
  export interface PulseNarrowing { from: number; to: number | null; authors: string[] }
94
- // The year's commits read so far: all of them, or as far back as asked
95
- // (`commits`, `from`), else how many (`read`), and whether past
96
- // YEAR_COMMITS (`tooMany`).
97
- type YearCommits = { complete: true; commits: HistoryCommit[]; passed: HistoryCommit[]; from: number | null } | { complete: false; read: number; tooMany: boolean }
98
-
99
83
  const emptyPunch = () => Array.from({ length: 7 }, () => Array.from({ length: 24 }, () => 0))
100
84
 
101
85
  // One statistic: its rows once GitHub has computed it, 'pending' while it
@@ -197,58 +181,6 @@ export async function defaultHead(fullName: string, token: string, fetchImpl: ty
197
181
  return typeof oid === 'string' && SHA.test(oid) ? oid : null
198
182
  }
199
183
 
200
- // The commits from `head` made since `since`, as the Commits tab reads and
201
- // keeps them (`pages`, historyFrom): on from the parents of those since (or
202
- // as much as YEAR_SKEW_MS before), not yet listed, YEAR_STARTS at a time,
203
- // till none is left; the pages kept read
204
- // of the store, those not of GitHub, as many queries of them as
205
- // YEAR_QUERIES, the rest left for the next to ask (`complete` false, how
206
- // many are `read`); more than YEAR_COMMITS, too many (`tooMany`). Read
207
- // whole, those it was read on past besides (`passed`): undated, or dated
208
- // before it, a clock behind, the branch's commits since beneath them. Read
209
- // no further than `need` asks, those since it read whole (`complete`, `from`
210
- // the newest of those read whose parents are not, every commit after it
211
- // read; null, the year read whole). How many are read so far `told` as they
212
- // are.
213
- export async function yearCommits(fullName: string, token: string, head: string, since: number, pages: HistoryPages,
214
- fetchImpl: typeof fetch = globalThis.fetch, need = since, told: (read: number) => void = () => {}): Promise<YearCommits> {
215
- const found = new Map<string, HistoryCommit>()
216
- const tried = new Set<string>()
217
- const within = (commit: HistoryCommit) => commit.committedAt === null || commit.committedAt >= since - YEAR_SKEW_MS
218
- const dated = (commit: HistoryCommit) => commit.committedAt !== null && commit.committedAt >= since
219
- const read = () => [...found.values()].filter(dated).length
220
- const passed = () => [...found.values()].filter(commit => !dated(commit) && within(commit))
221
- let queries = 0
222
- let windowed = false
223
- let starts = [head]
224
- while (starts.length > 0) {
225
- // Those not read yet, the head before any, else the parents of those
226
- // read, no later than the newest of them (but for a clock behind): read
227
- // whole after it.
228
- const unread = new Set(starts)
229
- const from = found.size === 0 ? Number.POSITIVE_INFINITY : Math.max(Number.NEGATIVE_INFINITY, ...[...found.values()]
230
- .filter(commit => commit.parents.some(sha => unread.has(sha))).map(commit => commit.committedAt ?? Number.POSITIVE_INFINITY))
231
- if (need > since && from < need) return { complete: true, commits: [...found.values()].filter(dated), passed: passed(), from }
232
- if (queries >= YEAR_QUERIES) return { complete: false, read: read(), tooMany: false }
233
- // The pages kept read first; once past them, the rest read at once by
234
- // when its commits were made (history-windows.ts windowsOn), as far back
235
- // as it needs, the year's as far as its commits are followed.
236
- const next: Awaited<ReturnType<typeof windowsOn>> | null = windowed || found.size === 0 ? null
237
- : await windowsOn(fullName, token, head, starts, found, need > since ? need : since - YEAR_SKEW_MS, from, pages, fetchImpl, queries)
238
- windowed ||= next?.windowed === true
239
- queries += next?.queries ?? 0
240
- const batch = (next?.batch ?? starts).slice(0, YEAR_STARTS)
241
- for (const sha of batch) tried.add(sha)
242
- const got = batch.length > 0 ? await historyFrom(fullName, token, batch, pages, fetchImpl) : { commits: [], read: 0 }
243
- if (got.read > 0) queries++
244
- for (const commit of got.commits) if (!found.has(commit.sha)) found.set(commit.sha, commit)
245
- told(read())
246
- if (read() > YEAR_COMMITS) return { complete: false, read: read(), tooMany: true }
247
- starts = [...new Set([...found.values()].filter(within).flatMap(commit => commit.parents))].filter(sha => !found.has(sha) && !tried.has(sha))
248
- }
249
- return { complete: true, commits: [...found.values()].filter(dated), passed: passed(), from: null }
250
- }
251
-
252
184
  // Whether an author is a GitHub App's bot: by its login (`<app>[bot]`, as a
253
185
  // commit's no-reply address names it, github-accounts.ts commitAccount),
254
186
  // else, for one GitHub names no account for, by the name it commits as.
@@ -46,7 +46,68 @@ export const isBusy = (error: unknown) => (error instanceof NpmPackageError && e
46
46
  // `integrity`, a mirror's held to it.
47
47
  export interface AssessedPackage { name: string; version: string; integrity?: string }
48
48
 
49
- export type Assessment = { published: string | null; findings: { id: string; severity: Severity; takenDown?: unknown }[]; score: { score: number } }
49
+ export type Assessment = { published: string | null; findings: ({ id: string; severity: Severity } & Record<string, unknown>)[]; score: { score: number } }
50
+
51
+ // How many of what a finding found a risk line keeps, the first (its files,
52
+ // dependencies or scripts; the hosts it names anew, short as each is, up to
53
+ // TOLD_HOSTS), with how many there are (`count`), for the Packages tab's
54
+ // tooltips (repository-risk.js); and how long a text of it (npm's
55
+ // deprecation message, a script's command) may be.
56
+ export const TOLD_ROWS = 5
57
+ export const TOLD_HOSTS = 10
58
+ const TOLD_TEXT = 300
59
+
60
+ // What a risk line tells of a finding: its id and severity, whether npm took
61
+ // its package down, and of what it found (assessNpm's, risk/npm/held.js,
62
+ // combined.js), what its tooltip says, bounded (TOLD_ROWS, TOLD_TEXT): npm's
63
+ // deprecation message; its package's tier by downloads, and the known
64
+ // account or scope that lowers it; the accounts that published it and the
65
+ // one before; the scripts npm runs installing it; its files, each with what
66
+ // it runs or reaches for (their kinds), the services it names, how it is
67
+ // obfuscated, where it links, its size, or its longest line before and now;
68
+ // the dependencies it takes from elsewhere than npm or imports none of, by
69
+ // their specs; and the hosts it names anew, each where first.
70
+ export type ToldFinding = { id: string; severity: Severity; takenDown?: true } & Record<string, unknown>
71
+ type Row = Record<string, unknown>
72
+ const cut = (text: unknown) => typeof text === 'string' && text.length > TOLD_TEXT ? `${text.slice(0, TOLD_TEXT - 1)}…` : typeof text === 'string' ? text : undefined
73
+ const keysOf = (found: unknown) => found && typeof found === 'object' ? Object.keys(found) : []
74
+ const first = (key: string, rows: unknown, pick: (row: Row) => Row, most = TOLD_ROWS) => Array.isArray(rows)
75
+ ? { [key]: (rows as Row[]).slice(0, most).map(pick), count: rows.length } : {}
76
+ const FILES: Partial<Record<string, (row: Row) => Row>> = {
77
+ 'held-runs-code': row => ({ path: row['path'], kinds: keysOf(row['found']) }),
78
+ 'held-credentials': row => ({ path: row['path'], kinds: keysOf(row['found']) }),
79
+ 'held-exfiltration': row => ({ path: row['path'], services: keysOf(row['found']) }),
80
+ 'held-remote': row => ({ path: row['path'], services: keysOf(row['found']) }),
81
+ 'held-ip-lookup': row => ({ path: row['path'], services: keysOf(row['found']) }),
82
+ 'held-obfuscated': row => ({ path: row['path'], ...row['found'] as Row }),
83
+ 'held-symlinks': row => ({ path: row['path'], link: row['link'], ...row['outside'] === true ? { outside: true } : {} }),
84
+ 'large-code': row => ({ path: row['path'], bytes: row['bytes'] }),
85
+ 'binary-code': row => ({ path: row['path'], bytes: row['bytes'] }),
86
+ 'now-unreadable': row => ({ path: row['path'], was: row['was'], now: row['now'] }),
87
+ }
88
+ export function toldFinding({ id, severity, ...found }: { id: string; severity: Severity } & Record<string, unknown>): ToldFinding {
89
+ const told: ToldFinding = { id, severity, ...found['takenDown'] === true ? { takenDown: true as const } : {} }
90
+ const files = FILES[id]
91
+ if (files) return { ...told, ...first('files', found['files'], files) }
92
+ switch (id) {
93
+ case 'deprecated': return { ...told, message: cut(found['message']) }
94
+ case 'popularity': return { ...told, tier: typeof found['tier'] === 'number' && Number.isFinite(found['tier']) ? found['tier'] : null,
95
+ ...found['known'] ? { known: true } : {}, ...typeof found['scope'] === 'string' ? { scope: found['scope'] } : {}, ...typeof found['account'] === 'string' ? { account: found['account'] } : {} }
96
+ case 'publisher': return { ...told, was: found['was'], now: found['now'], wasStanding: found['wasStanding'] ?? (found['wasKnown'] ? 'known' : 'unknown'),
97
+ nowStanding: found['nowStanding'] ?? (found['nowKnown'] ? 'known' : 'unknown'), ...found['major'] ? { major: true } : {} }
98
+ case 'held-install-scripts': {
99
+ const scripts = Array.isArray(found['scripts']) ? found['scripts'] as [string, unknown][] : []
100
+ return { ...told, scripts: scripts.slice(0, TOLD_ROWS).map(([script, command]) => [script, cut(command) ?? '']), count: scripts.length }
101
+ }
102
+ case 'held-non-registry-deps': return { ...told, ...first('dependencies', found['dependencies'], row => ({ name: row['name'], spec: row['now'] })) }
103
+ case 'held-unused-deps': return { ...told, ...first('dependencies', found['dependencies'], row => ({ name: row['name'], spec: row['range'] })) }
104
+ case 'new-hosts': return { ...told, ...first('hosts', found['hosts'], row => {
105
+ const [place] = Array.isArray(row['places']) ? row['places'] as Row[] : []
106
+ return { host: row['host'], ...place ? { path: place['path'], line: place['line'] } : {} }
107
+ }, TOLD_HOSTS) }
108
+ default: return told
109
+ }
110
+ }
50
111
 
51
112
  // What of a scan's source assessing a package asks (RepositoryRiskSource).
52
113
  export interface AssessingSource {
@@ -71,7 +132,7 @@ export async function assessPackage(source: AssessingSource, signal: AbortSignal
71
132
  const read = doc ??= await documentOf(source, pkg, signal)
72
133
  if (!(read instanceof NpmPackageError) && pkg.integrity !== undefined && !pkg.integrity.split(/\s+/u).includes(read.dist.integrity)) return { ...at, error: 'integrity-mismatch' }
73
134
  const { published, findings, score } = read instanceof NpmPackageError ? await removedOf(source, pkg, teamScoped, signal, read) : await assessedOf(source, pkg, teamScoped, signal, read)
74
- const told = findings.map(({ id, severity, takenDown }) => ({ id, severity, ...takenDown === true ? { takenDown: true as const } : {} }))
135
+ const told = findings.map(toldFinding)
75
136
  return { ...at, published, severity: highestSeverity(told), score: score.score, findings: told }
76
137
  } catch (error) {
77
138
  if (signal.aborted) return null
@@ -1,6 +1,7 @@
1
1
  // What repository risk scans keep between them (repository-risk.ts), in this
2
2
  // instance's memory.
3
3
  import { type Lru, lru } from './lru.ts'
4
+ import type { KeptStore } from './npm-kept.ts'
4
5
  import { type ActionAnswers, type ActionLine, type WorkflowsRead, answerWeight } from './repository-actions.ts'
5
6
  import type { Audit } from './repository-risk-audit.ts'
6
7
  import type { ListedLockfile, LockfileRead } from './repository-risk-read.ts'
@@ -35,3 +36,21 @@ export const riskCaches = (): RiskCaches => ({
35
36
  // What GitHub answered of public repositories' actions, by answerWeight.
36
37
  actionAnswers: lru(200_000, answerWeight),
37
38
  })
39
+
40
+ // How many kept risk lines are read of a source's `risks` at once.
41
+ const KEPT_READ = 500
42
+
43
+ // Risk lines kept of `keys`, by key: in this instance's memory (`caches`),
44
+ // else a source's `risks`, KEPT_READ at a time, held in memory then.
45
+ export async function keptRiskLines(caches: RiskCaches, risks: KeptStore<RiskLine> | undefined, keys: string[]) {
46
+ const kept = new Map<string, { at: number; line: RiskLine }>()
47
+ const left = keys.filter(key => { const hit = caches.risks.get(key); if (hit) kept.set(key, hit); return !hit })
48
+ if (!risks) return kept
49
+ for (let from = 0; from < left.length; from += KEPT_READ) {
50
+ for (const [key, { at, value }] of await risks.readMany(left.slice(from, from + KEPT_READ))) {
51
+ caches.risks.set(key, { at, line: value })
52
+ kept.set(key, { at, line: value })
53
+ }
54
+ }
55
+ return kept
56
+ }
@@ -0,0 +1,86 @@
1
+ // What a repository risk scan (repository-risk.ts) told of each repository,
2
+ // but its Dependabot alerts, kept gzipped for its reader (riskKeptStore), for
3
+ // a scan to tell first as it opens; one failing, or archived, kept no more.
4
+ import { gunzipBytes, gzipText } from '../common/gzip.js'
5
+ import { decodeUtf8 } from '../common/utf8.js'
6
+ import type { LockedPackage } from './locked-packages.ts'
7
+ import type { KeptStore } from './npm-kept.ts'
8
+ import type { ActionRef } from './repository-actions.ts'
9
+ import { inTurns } from './queue.ts'
10
+ import { stasisVersions } from './repository-risk-read.ts'
11
+ import type { RepositoryRiskLine, RepositoryRiskRepo } from './repository-risk.ts'
12
+
13
+ // What a scan told of a repository: its name then, its lines, and its Actions' references.
14
+ export interface KeptRepository { name: string; lines: RepositoryRiskLine[]; refs: ActionRef[] }
15
+ // A line of what was kept of a repository, told first, as of when it was read.
16
+ export type KeptLine = RepositoryRiskLine & { kept: number }
17
+
18
+ // Where it is kept, for one reader: read of many repositories at once, kept
19
+ // as each is told whole, and no longer.
20
+ export interface KeptRepositories {
21
+ read(repos: RepositoryRiskRepo[]): Promise<Map<number, { at: number; value: KeptRepository }>>
22
+ write(repo: RepositoryRiskRepo, value: KeptRepository, at: number): Promise<void>
23
+ remove(repo: RepositoryRiskRepo): Promise<void>
24
+ }
25
+
26
+ // None kept whose gzipped text, in base64, is longer, as a scan of a
27
+ // monorepo of many lockfiles may be; none unpacked past KEPT_TEXT_BYTES.
28
+ const KEPT_BYTES = 8 * 1024 * 1024
29
+ const KEPT_TEXT_BYTES = 128 * 1024 * 1024
30
+ const VERSION = 1
31
+
32
+ // What is kept in `store` for reader `user` (their id and role).
33
+ export function keptRepositories(store: KeptStore<string>, user: { id: string; role: string }): KeptRepositories {
34
+ const keyOf = (repo: RepositoryRiskRepo) => JSON.stringify([VERSION, user.id, user.role, repo.repoId, repo.paths ?? null])
35
+ const valueOf = async (packed: unknown): Promise<KeptRepository | null> => {
36
+ if (typeof packed !== 'string') return null
37
+ try {
38
+ const value = JSON.parse(decodeUtf8(await gunzipBytes(Buffer.from(packed, 'base64'), { maxBytes: KEPT_TEXT_BYTES }))) as Partial<KeptRepository> | null
39
+ return typeof value?.name === 'string' && Array.isArray(value.lines) && Array.isArray(value.refs) ? value as KeptRepository : null
40
+ } catch { return null }
41
+ }
42
+ return {
43
+ async read(repos) {
44
+ const keys = repos.map(keyOf)
45
+ const hits = await store.readMany(keys)
46
+ const kept = new Map<number, { at: number; value: KeptRepository }>()
47
+ await Promise.all(repos.map(async (repo, at) => {
48
+ const hit = hits.get(keys[at]!)
49
+ const value = hit && await valueOf(hit.value)
50
+ if (value) kept.set(repo.repoId, { at: hit.at, value })
51
+ }))
52
+ return kept
53
+ },
54
+ async write(repo, value, at) {
55
+ const packed = Buffer.from(await gzipText(JSON.stringify(value))).toString('base64')
56
+ await (packed.length > KEPT_BYTES ? store.remove(keyOf(repo)) : store.write(keyOf(repo), packed, at))
57
+ },
58
+ remove: repo => store.remove(keyOf(repo)),
59
+ }
60
+ }
61
+
62
+ // Whether its reader may read a repository now, as opening it asks GitHub;
63
+ // each line to tell; and what the scan is given again (repository-risk.ts reseed).
64
+ interface Telling { signal: AbortSignal; readable(repo: RepositoryRiskRepo): Promise<boolean>; tell(line: KeptLine): void
65
+ reseed(told: { stasis: string[]; packages: LockedPackage[][]; refs: ActionRef[] }): void }
66
+
67
+ // What is kept of `repos` told, each line marked when it was read (`kept`),
68
+ // of each with the name it had then that its reader may still read.
69
+ const READ_AT_ONCE = 20
70
+ const READABLE_AT_ONCE = 6
71
+ export async function tellKept(kept: KeptRepositories, repos: RepositoryRiskRepo[], to: Telling) {
72
+ const asking = inTurns(READABLE_AT_ONCE)
73
+ for (let from = 0; from < repos.length && !to.signal.aborted; from += READ_AT_ONCE) {
74
+ const some = repos.slice(from, from + READ_AT_ONCE)
75
+ const read = await kept.read(some)
76
+ const told = some.map(repo => read.get(repo.repoId)?.value.name === repo.fullName && asking(() => to.readable(repo).catch(() => false)))
77
+ for (const [at, repo] of some.entries()) {
78
+ const hit = read.get(repo.repoId)
79
+ if (!hit || !await told[at] || to.signal.aborted) continue
80
+ const { lines, refs } = hit.value
81
+ for (const line of lines) to.tell({ ...line, kept: hit.at })
82
+ to.reseed({ stasis: stasisVersions(lines.find(line => line.type === 'stasis') ?? null), refs,
83
+ packages: lines.flatMap(line => line.type === 'lockfile' && 'packages' in line ? [line.packages] : []) })
84
+ }
85
+ }
86
+ }
@@ -15,7 +15,8 @@
15
15
  import { createHash } from 'node:crypto'
16
16
  import type { LockfileFormat, RepoLockfile } from '@preventive/upstream/github.js'
17
17
  import type { AlertsRead } from './dependabot-access.ts'
18
- import type { DependabotAlert } from './dependabot-alerts.ts'
18
+ import { type DependabotAlert, alertVersions } from './dependabot-alerts.ts'
19
+ import { npmMalwareAdvisory } from '../risk/index.js'
19
20
  import { type LockedPackage, isTestFixture, lockedPackages, yarnManifests } from './locked-packages.ts'
20
21
  import type { Lru } from './lru.ts'
21
22
  import type { KeptStore } from './npm-kept.ts'
@@ -25,7 +26,7 @@ import { type RiskFailure, failureOf } from './repository-risk-assess.ts'
25
26
  import type { LockfileLine, RepositoryRiskLine, RepositoryRiskRepo } from './repository-risk.ts'
26
27
  import type { StasisDependency } from './bundle-build.ts'
27
28
  import { isStasisConfig } from './lockfile-scope.ts'
28
- import type { StasisRead } from './stasis-dependencies.ts'
29
+ import type { StasisBuilt, StasisRead } from './stasis-dependencies.ts'
29
30
 
30
31
  // The formats of npm's ecosystem, as findRepoLockfiles names them, and those
31
32
  // of them read here.
@@ -54,26 +55,34 @@ export type RepositoryArchived = Extract<RepositoryRiskLine, { type: 'repo'; arc
54
55
  // (`dependencies`), that its build is still to be made (`pending`), or why it
55
56
  // failed.
56
57
  // `lockfiles`, those its `lockfiles` names, from the repository's root,
57
- // where it names some: those its builds install from (namedLockfiles).
58
- export type StasisConfigRow = { path: string; lockfiles?: string[] } & ({ dependencies: StasisDependency[] } | { pending: true } | RiskFailure)
58
+ // where it names some: those its builds install from (namedLockfiles). One
59
+ // still to be made with what the last built of it on its branch installs
60
+ // meanwhile (`dependencies`, of `lastBuilt`, its commit), where one was.
61
+ export type StasisConfigRow = { path: string; lockfiles?: string[] } & ({ dependencies: StasisDependency[] } | { pending: true }
62
+ | { pending: true; dependencies: StasisDependency[]; lastBuilt: string } | RiskFailure)
59
63
  // A repository's stasis.config.json files, those of its `paths` alone, each
60
64
  // what Stasis reaches of it, or why they couldn't be listed.
61
65
  export type StasisConfigsRead = { configs: StasisConfigRow[] } | RiskFailure
62
66
 
63
67
  // A version, as Stasis tells those it installs, whatever its integrity.
64
68
  export const versionKey = ({ name, version }: { name: string; version: string }) => `${name}@${version}`
65
- // The versions a repository's Stasis builds made install (versionKey); none
66
- // of those still to be made, which aren't waited for.
69
+ // The versions a repository's Stasis builds made install (versionKey): of
70
+ // those still to be made, which aren't waited for, what the last built on
71
+ // its branch installs, where one was.
67
72
  export const stasisVersions = (read: StasisConfigsRead | null): string[] => [...new Set(read && 'configs' in read
68
73
  ? read.configs.flatMap(config => 'dependencies' in config ? config.dependencies.map(versionKey) : []) : [])]
69
74
  // The paths of a repository's stasis.config.json files whose builds are still
70
75
  // to be made.
71
76
  export const stasisBuilding = (read: StasisConfigsRead | null): string[] => read && 'configs' in read ? read.configs.flatMap(config => 'pending' in config ? [config.path] : []) : []
72
77
 
78
+ // A config's read, a build still to be made with the last built at its branch's head (`last`), where one was.
79
+ export type RiskStasisRead = StasisRead | { status: 'pending'; last: StasisBuilt }
80
+
73
81
  // A config's row of its read: a failed build told by its code (`detail`).
74
- export function stasisConfigRow(path: string, read: StasisRead): StasisConfigRow {
82
+ export function stasisConfigRow(path: string, read: RiskStasisRead): StasisConfigRow {
75
83
  if (read.status === 'ready') return { path, dependencies: read.dependencies }
76
- return read.status === 'pending' ? { path, pending: true } : { path, error: 'stasis-failed', detail: read.error }
84
+ if (read.status === 'pending') return 'last' in read ? { path, pending: true, dependencies: read.last.dependencies, lastBuilt: read.last.commit } : { path, pending: true }
85
+ return { path, error: 'stasis-failed', detail: read.error }
77
86
  }
78
87
 
79
88
  // A repository opened at its default branch's head (`commit`): its lockfiles,
@@ -94,7 +103,7 @@ export interface OpenedRepository {
94
103
  // as a dependency review's reader has it (stasis-dependencies.ts), its
95
104
  // build asked for where none is kept yet, never waited for.
96
105
  files?(): Promise<string[]>
97
- stasis?(config: string): Promise<StasisRead>
106
+ stasis?(config: string): Promise<RiskStasisRead>
98
107
  }
99
108
 
100
109
  // What a repository is read with: the scan's source and caches, and its
@@ -258,3 +267,30 @@ export async function readRepository<R extends RepositoryRiskRepo>(reading: Repo
258
267
  const stasis = await reaching
259
268
  return reading.signal.aborted ? null : { commit: opened.commit, lockfiles, dependabot, actions, stasis, recheck: () => opened.recheck() }
260
269
  }
270
+
271
+ // A Dependabot alert as a scan tells it: with the versions of its package
272
+ // the lockfile it is of locks that it covers, none where it is of none read
273
+ // (a package.json, bun's lockfile), and whether it is of malware, by the rule
274
+ // upstream tells an advisory's by (risk's npmMalwareAdvisory).
275
+ export type DependabotAlertRow = DependabotAlert & { versions: string[]; malware: boolean }
276
+
277
+ type DependabotLine = Extract<RepositoryRiskLine, { type: 'dependabot' }>
278
+
279
+ // A repository's Dependabot alerts' line, each alert with the versions the
280
+ // lockfile it is of locks that it covers (`lockfiles`, a repository read's),
281
+ // or why they couldn't be had.
282
+ export function dependabotLine(repo: number, read: DependabotRead, lockfiles: RepositoryRead['lockfiles']): DependabotLine {
283
+ if ('error' in read) return { type: 'dependabot', repo, ...read }
284
+ const locked = new Map(lockfiles.flatMap(({ line }) => 'packages' in line ? [[line.path, line.packages] as const] : []))
285
+ return { type: 'dependabot', repo, alerts: read.alerts.map(alert => ({ ...alert, versions: alertVersions(alert, locked.get(alert.manifest)),
286
+ malware: npmMalwareAdvisory({ id: alert.ghsa, aliases: alert.aliases, cwe: alert.cwe, title: alert.title }) })) }
287
+ }
288
+
289
+ // A repository's alerts checked again just before they are told, as access to
290
+ // the repository is (DependabotRead `recheck`): why not, where the user's
291
+ // access to them is withdrawn since they were read.
292
+ export async function rechecked(read: DependabotRead): Promise<DependabotRead> {
293
+ if (!('alerts' in read) || !read.recheck) return read
294
+ try { await read.recheck() } catch (error) { return failureOf(error, 'checking access to its Dependabot alerts again') }
295
+ return read
296
+ }