@preventive/triage 1.0.0-alpha.74 → 1.0.0-alpha.76

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 (58) hide show
  1. package/common/finding-duplicates.js +4 -4
  2. package/common/finding-filters.js +11 -13
  3. package/common/managed/roles.ts +6 -0
  4. package/common/managed/routes.js +4 -3
  5. package/common/managed/team-app.d.ts +2 -0
  6. package/common/managed/team-app.js +31 -14
  7. package/out/activity.js +1 -1
  8. package/out/{chunk-C6OPCPCA.js → chunk-24LZZYAP.js} +1 -1
  9. package/out/{chunk-VRAJCPV5.js → chunk-EYTPAODY.js} +2 -2
  10. package/out/chunk-ITUKKCCK.js +10 -0
  11. package/out/{chunk-BLPHP4U3.js → chunk-IVDE66N5.js} +1 -1
  12. package/out/{chunk-VS7RV24Z.js → chunk-MFAB7P3T.js} +2 -2
  13. package/out/chunk-O6FA2R5G.js +53 -0
  14. package/out/chunk-OCE6KQGJ.js +40 -0
  15. package/out/{chunk-YI4D6XVX.js → chunk-RHOQDAU4.js} +1 -1
  16. package/out/{chunk-2IHCVA3Y.js → chunk-T6EXDRB7.js} +1 -1
  17. package/out/chunk-UZC7POI4.js +255 -0
  18. package/out/chunk-WGQ7D5DB.js +1 -0
  19. package/out/client-managed-import.js +1 -1
  20. package/out/client-managed.js +30 -30
  21. package/out/compare.js +4 -4
  22. package/out/dialogs.js +1 -1
  23. package/out/graph.js +6 -6
  24. package/out/index.html +8 -8
  25. package/out/prism.js +1 -1
  26. package/out/scan.js +1 -1
  27. package/out/view.css +1 -1
  28. package/out/view.js +4 -4
  29. package/package.json +5 -2
  30. package/risk/files/characters.js +142 -8
  31. package/risk/files/hosts.js +4 -3
  32. package/risk/files/readability.js +18 -13
  33. package/risk/files/runs-code.js +41 -80
  34. package/risk/files/script.js +210 -48
  35. package/risk/index.d.ts +4 -2
  36. package/risk/npm/assess.js +1 -1
  37. package/risk/npm/tarball.js +35 -19
  38. package/server-managed/dependency-review-comments.ts +22 -10
  39. package/server-managed/http.ts +74 -25
  40. package/server-managed/locked-packages.ts +62 -5
  41. package/server-managed/npm-packages.ts +7 -5
  42. package/server-managed/queue.ts +8 -7
  43. package/server-managed/repository-browser.ts +6 -3
  44. package/server-managed/repository-code.ts +3 -2
  45. package/server-managed/repository-risk-caches.ts +37 -0
  46. package/server-managed/repository-risk-read.ts +41 -18
  47. package/server-managed/repository-risk-stasis.ts +61 -0
  48. package/server-managed/repository-risk-turn.ts +97 -0
  49. package/server-managed/repository-risk.ts +128 -102
  50. package/server-managed/scan-downloads.ts +44 -10
  51. package/server-managed/team-app-summaries.ts +3 -1
  52. package/server-managed/team-app.ts +4 -2
  53. package/server-managed/team-reports.ts +8 -3
  54. package/out/chunk-5YP7P5KA.js +0 -1
  55. package/out/chunk-74AEKRES.js +0 -10
  56. package/out/chunk-DQJEVHRE.js +0 -52
  57. package/out/chunk-ESJZZF2Y.js +0 -255
  58. package/out/chunk-GV5U7OLP.js +0 -40
@@ -0,0 +1,61 @@
1
+ // What a repository risk scan knows of Stasis's builds (repository-risk.ts):
2
+ // the versions those made install (versionKey), Stasis's wherever they are
3
+ // locked, as the page tells them apart (repository-risk.js stasisReach),
4
+ // assessed before the rest; the packages seen of each version, to move up
5
+ // once it is told Stasis's; and the builds still to be made as their
6
+ // repositories were read, watched: asked again every STASIS_AGAIN_MS what
7
+ // Stasis has made of them, as their page asks, none ever waited for.
8
+ import { setTimeout as delay } from 'node:timers/promises'
9
+ import type { AssessedPackage } from './repository-risk-assess.ts'
10
+ import { versionKey } from './repository-risk-read.ts'
11
+ import type { StasisRead } from './stasis-dependencies.ts'
12
+
13
+ // As often as a page asks again of the builds it shows still to be made
14
+ // (repository-risk.js STASIS_POLL_MS).
15
+ export const STASIS_AGAIN_MS = 30_000
16
+
17
+ // A build still to be made: of the stasis.config.json at `config` of
18
+ // repository `repoId` at `commit`.
19
+ export interface StasisBuild { repoId: number; commit: string; config: string }
20
+
21
+ export interface StasisReach {
22
+ // Whether a Stasis build made installs its version.
23
+ has(pkg: AssessedPackage): boolean
24
+ // A package the scan sees, the first time.
25
+ seen(pkg: AssessedPackage): void
26
+ // `versions` told Stasis's: the packages seen of those new to it.
27
+ add(versions: readonly string[]): AssessedPackage[]
28
+ // Builds still to be made, to watch.
29
+ building(builds: StasisBuild[]): void
30
+ // Those watched asked of `built` every `everyMs`, till `signal` aborts:
31
+ // each made since given to `made` with the versions it installs, once; one
32
+ // failed let go, one still to be made asked again.
33
+ watch(built: (build: StasisBuild) => Promise<StasisRead>, made: (build: StasisBuild, versions: string[]) => void, signal: AbortSignal, everyMs: number): Promise<void>
34
+ }
35
+
36
+ export function stasisReach(): StasisReach {
37
+ const builds = new Map<string, StasisBuild>(), reached = new Set<string>(), seen = new Map<string, AssessedPackage[]>()
38
+ return {
39
+ has: pkg => reached.has(versionKey(pkg)),
40
+ seen(pkg) { seen.set(versionKey(pkg), [...seen.get(versionKey(pkg)) ?? [], pkg]) },
41
+ add(versions) {
42
+ const fresh = [...new Set(versions)].filter(version => !reached.has(version))
43
+ for (const version of fresh) reached.add(version)
44
+ return fresh.flatMap(version => seen.get(version) ?? [])
45
+ },
46
+ building(told) { for (const build of told) builds.set(`${build.repoId}\0${build.commit}\0${build.config}`, build) },
47
+ async watch(built, made, signal, everyMs) {
48
+ for (;;) {
49
+ try { await delay(everyMs, undefined, { signal }) } catch { return }
50
+ for (const [key, build] of builds) {
51
+ let read: StasisRead
52
+ try { read = await built(build) } catch { continue }
53
+ if (signal.aborted) return
54
+ if (read.status === 'pending') continue
55
+ builds.delete(key)
56
+ if (read.status === 'ready') made(build, [...new Set(read.dependencies.map(versionKey))])
57
+ }
58
+ }
59
+ },
60
+ }
61
+ }
@@ -0,0 +1,97 @@
1
+ // A turn of a repository risk scan's assessments (repository-risk.ts): the
2
+ // packages given it, each assessed once, as many at a time as npm-risk.ts
3
+ // makes spare assessments, those `first` (the scan's Stasis's) before the
4
+ // rest, each given to the assessors once its downloads are readied, where
5
+ // the scan readies them (scan-downloads.ts); once all it is given are
6
+ // assessed, or the scan stops, those given once its feed is over too. One
7
+ // given that is `first` only since, as a Stasis build made since installs
8
+ // it, is hurried where it is still waiting: its downloads readied before the
9
+ // rest, or put before the rest waiting for an assessor.
10
+ import { MAX_SPARE_ASSESSMENTS } from './npm-risk.ts'
11
+ import { type Queue, queue } from './queue.ts'
12
+ import { type AssessedPackage, BUSY_RETRIES, BUSY_WAIT_MS, isBusy } from './repository-risk-assess.ts'
13
+ import { type DownloadsSource, readyingDownloads } from './scan-downloads.ts'
14
+
15
+ export interface Turn {
16
+ // Packages to assess: those given it before not again. False, none taken,
17
+ // once the turn is over.
18
+ give(packages: AssessedPackage[]): boolean
19
+ // Those of `packages` given it that are `first` now, hurried.
20
+ hurry(packages: AssessedPackage[]): void
21
+ }
22
+
23
+ export interface TurnOptions {
24
+ signal: AbortSignal
25
+ downloads: DownloadsSource | undefined
26
+ // A package as the scan tells it apart (repository-risk.ts seenKey).
27
+ key(pkg: AssessedPackage): string
28
+ first(pkg: AssessedPackage): boolean
29
+ assess(pkg: AssessedPackage): Promise<void>
30
+ }
31
+
32
+ // Where a package given is: its downloads being readied, waiting for an
33
+ // assessor, or taken by one.
34
+ type Given = 'readying' | 'pending' | 'taken'
35
+
36
+ async function assessor({ key, assess }: TurnOptions, pending: Queue<AssessedPackage>, given: Map<string, Given>, done: () => void) {
37
+ for (let next = await pending.take(); next !== undefined; next = await pending.take()) {
38
+ // One hurried is in line twice: assessed once.
39
+ if (given.get(key(next)) === 'taken') continue
40
+ given.set(key(next), 'taken')
41
+ try { await assess(next) } finally { done() }
42
+ }
43
+ }
44
+
45
+ // The packages `feed` gives the turn assessed, once `feed` ends and all
46
+ // given it are: those given it since too, it being over only then.
47
+ export async function assessingTurn(options: TurnOptions, feed: (turn: Turn) => Promise<void>): Promise<void> {
48
+ const { signal, downloads, key, first } = options
49
+ const pending = queue<AssessedPackage>(signal)
50
+ const given = new Map<string, Given>()
51
+ // Whether an assessor failed; what waits for the last of those given once
52
+ // `feed` is over; whether it is; how many given are still to be assessed;
53
+ // and whether the turn is over.
54
+ let broken = false, drained = () => {}, fed = false, left = 0, over = false
55
+ const done = () => { left--; if (fed && left === 0) drained() }
56
+ const toAssessors = (pkg: AssessedPackage) => { given.set(key(pkg), 'pending'); pending.add(pkg, first(pkg)) }
57
+ const readying = downloads ? readyingDownloads<AssessedPackage>(downloads, signal, toAssessors, { busy: isBusy, retries: BUSY_RETRIES, waitMs: BUSY_WAIT_MS }) : null
58
+ // One failing ends the wait for the rest, its failure thrown as the turn ends.
59
+ const assessors = Array.from({ length: MAX_SPARE_ASSESSMENTS }, () => assessor(options, pending, given, done).catch((error: unknown) => { broken = true; drained(); throw error }))
60
+ const turn: Turn = {
61
+ give(packages) {
62
+ if (over) return false
63
+ const fresh = packages.filter(pkg => !given.has(key(pkg)))
64
+ left += fresh.length
65
+ if (!readying) { for (const pkg of fresh) toAssessors(pkg); return true }
66
+ for (const pkg of fresh) given.set(key(pkg), 'readying')
67
+ const firsts = fresh.filter(first)
68
+ if (firsts.length > 0) readying.add(firsts, true)
69
+ if (firsts.length < fresh.length) readying.add(fresh.filter(pkg => !first(pkg)))
70
+ return true
71
+ },
72
+ hurry(packages) {
73
+ if (over) return
74
+ const names: string[] = []
75
+ for (const pkg of packages) {
76
+ if (!first(pkg)) continue
77
+ const at = given.get(key(pkg))
78
+ if (at === 'readying') names.push(pkg.name)
79
+ else if (at === 'pending') pending.add(pkg, true)
80
+ }
81
+ if (names.length > 0) readying?.hurry(names)
82
+ },
83
+ }
84
+ try { await feed(turn) } finally {
85
+ fed = true
86
+ if (left > 0 && !signal.aborted && !broken) {
87
+ await new Promise<void>(resolve => {
88
+ drained = resolve
89
+ signal.addEventListener('abort', () => { resolve() }, { once: true })
90
+ })
91
+ }
92
+ over = true
93
+ await readying?.close()
94
+ pending.close()
95
+ }
96
+ await Promise.all(assessors)
97
+ }
@@ -14,9 +14,14 @@
14
14
  // from elsewhere (git, a tarball with no integrity, a file) is listed, not
15
15
  // assessed. Repositories are read a few at a time (READ_AHEAD), each told in
16
16
  // turn, as GitHub's limits are the caller's; packages are assessed meanwhile, as many at a time as npm-risk.ts
17
- // makes spare assessments, those only devDependencies need in every lockfile
18
- // that locks them (LockedPackage `dev`) once all the rest are, as an install
19
- // of no devDependencies leaves them out. A lockfile's packages of npm's
17
+ // makes spare assessments: those with no risk line kept first, those a
18
+ // Stasis build installs before the rest, then those only devDependencies
19
+ // need in every lockfile that locks them (LockedPackage `dev`), as an install
20
+ // of no devDependencies leaves them out; then those told stale, in the same
21
+ // order (LEFT_OVER). A Stasis build still to be made isn't waited for: the
22
+ // versions it installs keep their place among the rest till it is made, the
23
+ // scan asking again what Stasis made as its page does (repository-risk-stasis.ts),
24
+ // and those still to assess then go first. A lockfile's packages of npm's
20
25
  // registry or a mirror are asked of npm's advisories all at once, as `npm
21
26
  // audit` asks, each advisory told with whether it is of malware (upstream's
22
27
  // `malware`), which alone is a supply chain's risk; the rest are
@@ -30,25 +35,30 @@
30
35
  // has a build tell it (stasis-dependencies.ts), told once its lockfiles are:
31
36
  // the versions a build installs, or that it is still to be made, which isn't
32
37
  // waited for, its page asking for it again (GET
33
- // /api/admin/repositories/risk/stasis), or why it failed.
38
+ // /api/admin/repositories/risk/stasis), or why it failed. A repository GitHub
39
+ // has archived is told so as it is opened, and read no further: nothing
40
+ // installs from it anew.
34
41
  import type { LockfileFormat } from '@preventive/upstream/github.js'
35
42
  import { type ActionsSource, type Severity, npmMalwareAdvisory } from '../risk/index.js'
36
43
  import { isNpmPackageName, isNpmPackageSpec } from '../common/managed/npm-packages.js'
37
- import { type Lru, lru } from './lru.ts'
44
+ import { type RiskCaches, riskCaches } from './repository-risk-caches.ts'
38
45
  import type { KeptStore } from './npm-kept.ts'
39
- import { MAX_SPARE_ASSESSMENTS } from './npm-risk.ts'
40
46
  import type { LockedPackage } from './locked-packages.ts'
41
47
  import { type Queue, inTurns, queue } from './queue.ts'
42
- import { type DownloadsSource, readyingDownloads } from './scan-downloads.ts'
43
- import { type AssessedPackage, type AssessingSource, BUSY_RETRIES, BUSY_WAIT_MS, RISK_KEPT_MS, type RiskFailure, assessPackage, failureOf, isBusy } from './repository-risk-assess.ts'
48
+ import type { DownloadsSource } from './scan-downloads.ts'
49
+ import { type AssessedPackage, type AssessingSource, RISK_KEPT_MS, type RiskFailure, assessPackage, failureOf } from './repository-risk-assess.ts'
44
50
  import { type AdvisoryRow, type Audit, type AuditSource, auditLockfiles } from './repository-risk-audit.ts'
45
- import { type DependabotRead, type ListedLockfile, type LockfileRead, type OpenedRepository, type RepositoryFailure, type RepositoryRead, SCAN_READ_KEPT_MS,
46
- type StasisConfigsRead, readRepository } from './repository-risk-read.ts'
51
+ import { type DependabotRead, type ListedLockfile, type LockfileRead, type OpenedRepository, type RepositoryArchived, type RepositoryFailure, type RepositoryRead, SCAN_READ_KEPT_MS,
52
+ type StasisConfigsRead, readRepository, stasisBuilding, stasisVersions } from './repository-risk-read.ts'
53
+ import { STASIS_AGAIN_MS, type StasisBuild, type StasisReach, stasisReach } from './repository-risk-stasis.ts'
54
+ import { type Turn, assessingTurn } from './repository-risk-turn.ts'
55
+ import type { StasisRead } from './stasis-dependencies.ts'
47
56
  import { type DependabotAlert, alertVersions } from './dependabot-alerts.ts'
48
- import { type ActionAnswers, type ActionLine, type ActionRef, type WorkflowLine, type WorkflowsLine, type WorkflowsRead, actionsLines, answerWeight,
57
+ import { type ActionLine, type ActionRef, type WorkflowLine, type WorkflowsLine, type WorkflowsRead, actionsLines,
49
58
  lockedNames, resolvingActions } from './repository-actions.ts'
50
59
 
51
60
  export { RISK_KEPT_MS, highestSeverity } from './repository-risk-assess.ts'
61
+ export { riskCaches } from './repository-risk-caches.ts'
52
62
  export { SCAN_READ_KEPT_MS } from './repository-risk-read.ts'
53
63
 
54
64
  // A repository to read: where `paths` are given, a team's directories in it,
@@ -58,7 +68,8 @@ export interface RepositoryRiskRepo { repoId: number; fullName: string; paths?:
58
68
 
59
69
  interface RepositoryRiskSource<R extends RepositoryRiskRepo> extends AuditSource, AssessingSource {
60
70
  repos(): Promise<R[]>
61
- open(repo: R): Promise<OpenedRepository>
71
+ // Opened to read, or `archived` where GitHub has it so, read no further.
72
+ open(repo: R): Promise<OpenedRepository | { archived: true }>
62
73
  // Whether a team lists a package's scope, its own packages.
63
74
  teamScoped(name: string): Promise<boolean>
64
75
  // Where risk lines are kept beyond this instance, as RiskCaches keeps them
@@ -84,6 +95,10 @@ interface RepositoryRiskSource<R extends RepositoryRiskRepo> extends AuditSource
84
95
  // Where Actions' files read and references resolved are kept.
85
96
  actionFiles?: KeptStore<WorkflowsRead>
86
97
  actionLines?: KeptStore<ActionLine>
98
+ // What Stasis has made of a build still to be made as its repository was
99
+ // read, as known now, asking GitHub nothing, nor for a build, as its page
100
+ // asks for them; none watched without it.
101
+ stasisBuilt?(build: StasisBuild): Promise<StasisRead>
87
102
  }
88
103
 
89
104
  // A Dependabot alert as a scan tells it: with the versions of its package
@@ -97,7 +112,7 @@ type DependabotAlertRow = DependabotAlert & { versions: string[]; malware: boole
97
112
  // of it, out of 100 (assessNpm `score`, risk/npm/score.js).
98
113
  export type RepositoryRiskLine =
99
114
  | { type: 'repos'; repos: { id: number; fullName: string }[] }
100
- | ({ type: 'repo'; id: number } & ({ commit: string; lockfiles: { path: string; format: LockfileFormat }[] } | RiskFailure))
115
+ | ({ type: 'repo'; id: number } & ({ commit: string; lockfiles: { path: string; format: LockfileFormat }[] } | RiskFailure | { archived: true }))
101
116
  | ({ type: 'lockfile'; repo: number; path: string; format: LockfileFormat } & ({ packages: LockedPackage[] } | RiskFailure))
102
117
  | ({ type: 'risk'; name: string; version: string; integrity?: string; stale?: { assessedAt: number } }
103
118
  & ({ published: string | null; severity: Severity | null; score: number; findings: { id: string; severity: Severity; takenDown?: true }[] } | RiskFailure))
@@ -112,42 +127,16 @@ export type RepositoryRiskLine =
112
127
 
113
128
  // The repositories a scan answered in parts told whole by a part's end: each
114
129
  // by its id, its name and a team's directories in it then, and its
115
- // lockfiles' keys (`${format}\0${sha}`) of those read, and the references
116
- // its Actions make, to resolve.
130
+ // lockfiles' keys (`${format}\0${sha}`) of those read, the references its
131
+ // Actions make, to resolve, the versions its Stasis builds made install
132
+ // (versionKey), assessed before the rest, and its builds still to be made,
133
+ // to watch.
117
134
  export interface ScanProgress { repos: ToldRepository[] }
118
- interface ToldRepository { id: number; name: string; paths: readonly string[] | null; lockfiles: string[]; actions?: ActionRef[] }
135
+ interface ToldRepository { id: number; name: string; paths: readonly string[] | null; lockfiles: string[]; actions?: ActionRef[]; stasis?: string[]
136
+ building?: { commit: string; configs: string[] } }
119
137
 
120
138
  export type RiskLine = Extract<RepositoryRiskLine, { type: 'risk' }>
121
139
 
122
- // What scans keep between them, in this instance's memory: a repository's
123
- // lockfiles as listed at a commit, and a lockfile's packages by its blob,
124
- // neither of which changes; a lockfile's advisories, asked again after
125
- // RISK_KEPT_MS, as npm publishes advisories; and a package's risk line,
126
- // told stale after RISK_KEPT_MS and assessed again, as risk tells again what
127
- // of a package changes in time (a deprecation, its age, its downloads). A
128
- // lockfile's, and its packages' lines, are told only once access to its
129
- // repository is checked as when it was read.
130
- interface RiskCaches {
131
- listings: Lru<ListedLockfile[]>
132
- lockfiles: Lru<LockfileRead>
133
- risks: Lru<{ at: number; line: RiskLine }>
134
- advisories: Lru<{ at: number; audit: Audit }>
135
- actionFiles: Lru<WorkflowsRead>
136
- actions: Lru<{ at: number; line: ActionLine }>
137
- actionAnswers: ActionAnswers
138
- }
139
- export const riskCaches = (): RiskCaches => ({
140
- listings: lru(1000),
141
- // By the packages they hold, a few hundred bytes each.
142
- lockfiles: lru(200_000, read => 'packages' in read ? read.packages.length + 1 : 1),
143
- risks: lru(50_000),
144
- advisories: lru(50_000, kept => Array.isArray(kept.audit) ? kept.audit.length + 1 : 1),
145
- // By their text, a kilobyte at a time.
146
- actionFiles: lru(64 * 1024, read => 'files' in read ? read.files.reduce((sum, file) => sum + ('text' in file ? Math.ceil(file.text.length / 1024) : 1), 1) : 1),
147
- actions: lru(10_000),
148
- // What GitHub answered of public repositories' actions, by answerWeight.
149
- actionAnswers: lru(200_000, answerWeight),
150
- })
151
140
  // How many repositories are read at once (repository-risk-read.ts), ahead of
152
141
  // the one told: each asks GitHub one thing after another (opening it, and
153
142
  // its head) even where all else is kept.
@@ -168,13 +157,18 @@ interface Scan {
168
157
  lines: Queue<RepositoryRiskLine>
169
158
  // Each lockfile's packages not yet seen, to look up as kept (lookUp); those
170
159
  // already seen, by seenKey, each with whether only devDependencies need it
171
- // so far; those of them with none kept, put off as long as that holds, by
172
- // seenKey; and those told stale, to assess again once those with none kept
173
- // are.
160
+ // so far; those of them with none kept, put off as long as that holds; and
161
+ // those told stale, to assess again once those with none kept are: each by
162
+ // seenKey till given a turn.
174
163
  lookups: Queue<AssessedPackage[]>
175
164
  seen: Map<string, boolean>
176
165
  dev: Map<string, AssessedPackage>
177
- stale: AssessedPackage[]
166
+ stale: Map<string, AssessedPackage>
167
+ // What it knows of Stasis's builds (repository-risk-stasis.ts); and the turn
168
+ // under way (assessing), of those stale or not, to give or hurry those told
169
+ // Stasis's since.
170
+ reach: StasisReach
171
+ turn: { turn: Turn; stale: boolean } | null
178
172
  // The repositories told whole, this part or one before (ScanProgress).
179
173
  told: Map<number, ToldRepository>
180
174
  actions: ReturnType<typeof resolvingActions> | null
@@ -183,6 +177,7 @@ interface Scan {
183
177
 
184
178
  // A package as a scan meets it: by its name, version and a mirror's integrity.
185
179
  const seenKey = (pkg: AssessedPackage) => `${pkg.name}@${pkg.version}\0${pkg.integrity ?? ''}`
180
+ const isStasis = (scan: Scan, pkg: AssessedPackage) => scan.reach.has(pkg)
186
181
 
187
182
  // A package's key, as its risk line is kept: its name, version and a
188
183
  // mirror's integrity, and whether a team lists its scope.
@@ -191,11 +186,12 @@ const riskKey = (pkg: AssessedPackage, teamScoped: boolean) => `${seenKey(pkg)}\
191
186
  // since risk told a score (assessNpm `score`).
192
187
  const isFresh = ({ at, line }: { at: number; line: RiskLine }) => Date.now() - at < RISK_KEPT_MS && ('error' in line || typeof line.score === 'number')
193
188
 
194
- // A package assessed (assess), its line kept, in RiskCaches and the source's
195
- // `risks`, where it tells what risk found, or that a mirror's copy isn't npm's.
196
- async function assessed(scan: Scan, pkg: AssessedPackage): Promise<RiskLine | null> {
189
+ // A package assessed (assess), its line told, and kept, in RiskCaches and the
190
+ // source's `risks`, where it tells what risk found, or that a mirror's copy
191
+ // isn't npm's.
192
+ async function assessed(scan: Scan, pkg: AssessedPackage): Promise<void> {
197
193
  let teamScoped
198
- try { teamScoped = await scan.source.teamScoped(pkg.name) } catch (error) { return { type: 'risk', ...pkg, ...failureOf(error) } }
194
+ try { teamScoped = await scan.source.teamScoped(pkg.name) } catch (error) { scan.lines.add({ type: 'risk', ...pkg, ...failureOf(error) }); return }
199
195
  const key = riskKey(pkg, teamScoped)
200
196
  const line = await assessPackage(scan.source, scan.signal, pkg, teamScoped)
201
197
  if (line && (!('error' in line) || line.error === 'integrity-mismatch')) {
@@ -203,7 +199,7 @@ async function assessed(scan: Scan, pkg: AssessedPackage): Promise<RiskLine | nu
203
199
  scan.caches.risks.set(key, { at, line })
204
200
  await scan.source.risks?.write(key, line, at)
205
201
  }
206
- return line
202
+ if (line) scan.lines.add(line)
207
203
  }
208
204
 
209
205
  // Risk lines kept of `keys`, by key: in this instance's memory, else the
@@ -224,7 +220,8 @@ async function keptLines({ source, caches }: Scan, keys: string[]) {
224
220
  // kept, however old, told at once, a fresh one as it is and an older one as
225
221
  // stale (`stale`, when it was assessed), its package assessed again once
226
222
  // those with none kept are (`scan.stale`); those with none given to `assess`,
227
- // but those only devDependencies need so far, put off (`scan.dev`).
223
+ // but those only devDependencies need so far, and no Stasis build installs,
224
+ // put off (`scan.dev`).
228
225
  async function lookUp(scan: Scan, assess: (packages: AssessedPackage[]) => void) {
229
226
  for (let packages = await scan.lookups.take(); packages !== undefined; packages = await scan.lookups.take()) {
230
227
  const keyed: { pkg: AssessedPackage; key: string }[] = []
@@ -236,34 +233,21 @@ async function lookUp(scan: Scan, assess: (packages: AssessedPackage[]) => void)
236
233
  for (const { pkg, key } of keyed) {
237
234
  const hit = kept.get(key)
238
235
  if (hit && isFresh(hit)) scan.lines.add(hit.line)
239
- else if (hit) { scan.lines.add({ ...hit.line, stale: { assessedAt: hit.at } }); scan.stale.push(pkg) }
240
- else if (scan.seen.get(seenKey(pkg)) === true) scan.dev.set(seenKey(pkg), pkg)
236
+ else if (hit) { scan.lines.add({ ...hit.line, stale: { assessedAt: hit.at } }); scan.stale.set(seenKey(pkg), pkg) }
237
+ else if (scan.seen.get(seenKey(pkg)) === true && !isStasis(scan, pkg)) scan.dev.set(seenKey(pkg), pkg)
241
238
  else missing.push(pkg)
242
239
  }
243
240
  if (missing.length > 0) assess(missing)
244
241
  }
245
242
  }
246
243
 
247
- async function assessor(scan: Scan, pending: Queue<AssessedPackage>) {
248
- for (let next = await pending.take(); next !== undefined; next = await pending.take()) {
249
- const line = await assessed(scan, next)
250
- if (line) scan.lines.add(line)
251
- }
252
- }
253
-
254
- // The packages `feed` gives assessed, each given to the assessors once its
255
- // downloads are readied, where the source readies them (scan-downloads.ts):
256
- // once all it gives are told, or the scan stops.
257
- async function assessing(scan: Scan, feed: (assess: (packages: AssessedPackage[]) => void) => Promise<void>) {
258
- const pending = queue<AssessedPackage>(scan.signal)
259
- const readying = scan.source.downloads
260
- ? readyingDownloads<AssessedPackage>(scan.source.downloads, scan.signal, pkg => { pending.add(pkg) }, { busy: isBusy, retries: BUSY_RETRIES, waitMs: BUSY_WAIT_MS }) : null
261
- const assessors = Array.from({ length: MAX_SPARE_ASSESSMENTS }, () => assessor(scan, pending))
262
- try { await feed(packages => { if (readying) readying.add(packages); else for (const pkg of packages) pending.add(pkg) }) } finally {
263
- await readying?.close()
264
- pending.close()
265
- }
266
- await Promise.all(assessors)
244
+ // The packages `feed` gives assessed in a turn (repository-risk-turn.ts), of
245
+ // those `stale` or not, Stasis's before the rest: once all given it are told,
246
+ // or the scan stops. It is the turn under way till then (reach).
247
+ async function assessing(scan: Scan, feed: (assess: (packages: AssessedPackage[]) => void) => Promise<void>, stale = false) {
248
+ await assessingTurn({ signal: scan.signal, downloads: scan.source.downloads, key: seenKey, first: pkg => isStasis(scan, pkg), assess: pkg => assessed(scan, pkg) },
249
+ turn => { scan.turn = { turn, stale }; return feed(packages => { turn.give(packages) }) })
250
+ scan.turn = null
267
251
  }
268
252
 
269
253
  // A lockfile's packages of npm's registry or a mirror not yet seen this scan,
@@ -279,11 +263,36 @@ function assessLater(scan: Scan, packages: LockedPackage[]) {
279
263
  const was = scan.seen.get(key)
280
264
  if (was === false || (was && dev)) continue
281
265
  scan.seen.set(key, dev)
266
+ if (was === undefined) scan.reach.seen(pkg)
282
267
  if (was === undefined || scan.dev.delete(key)) fresh.push(pkg)
283
268
  }
284
269
  if (fresh.length > 0) scan.lookups.add(fresh)
285
270
  }
286
271
 
272
+ // `versions` told Stasis's (StasisReach), as a repository is told, before its
273
+ // lockfiles are given to assessLater, or as a build is made since: those
274
+ // seen of each already that wait for a turn of the kind under way (put off as
275
+ // only devDependencies need them, or stale) given it now, and those it has
276
+ // hurried, where they still wait.
277
+ function reach(scan: Scan, versions: readonly string[]) {
278
+ const at = scan.turn, moved = scan.reach.add(versions)
279
+ if (!at || moved.length === 0) return
280
+ const waiting = at.stale ? scan.stale : scan.dev
281
+ const now = moved.filter(pkg => waiting.has(seenKey(pkg)))
282
+ if (now.length > 0 && at.turn.give(now)) for (const pkg of now) waiting.delete(seenKey(pkg))
283
+ at.turn.hurry(moved)
284
+ }
285
+
286
+ // A build watched made (StasisReach `watch`): the versions it installs told
287
+ // Stasis's, and kept with its repository told, for a part after.
288
+ function madeSince(scan: Scan, build: StasisBuild, versions: string[]) {
289
+ reach(scan, versions)
290
+ const told = scan.told.get(build.repoId)
291
+ if (!told) return
292
+ told.stasis = [...new Set([...told.stasis ?? [], ...versions])]
293
+ if (told.building) told.building = { ...told.building, configs: told.building.configs.filter(config => config !== build.config) }
294
+ }
295
+
287
296
  export type LockfileLine = Extract<RepositoryRiskLine, { type: 'lockfile' }>
288
297
 
289
298
  // A lockfile's advisories line, of its audit (repository-risk-audit.ts auditLockfile).
@@ -291,8 +300,8 @@ const advisoriesLine = ({ repo, path }: LockfileLine, audit: Audit) => ({ type:
291
300
 
292
301
  // A repository read, its lockfiles' audits asked meanwhile, AUDITS_AT_ONCE
293
302
  // across the scan (auditLockfiles), to tell in turn once access is checked again.
294
- type Audited = (RepositoryRead & { audits: Promise<Audit | null>[] }) | RepositoryFailure
295
- const audited = (scan: Scan, read: RepositoryRead | RepositoryFailure | null): Audited | null => (read === null || 'type' in read ? read : { ...read, audits: auditLockfiles(scan.source, scan.caches.advisories,
303
+ type Audited = (RepositoryRead & { audits: Promise<Audit | null>[] }) | RepositoryFailure | RepositoryArchived
304
+ const audited = (scan: Scan, read: RepositoryRead | RepositoryFailure | RepositoryArchived | null): Audited | null => (read === null || 'type' in read ? read : { ...read, audits: auditLockfiles(scan.source, scan.caches.advisories,
296
305
  scan.signal, read.lockfiles.map(({ sha, line }) => ({ key: `${line.format}\0${sha}`, packages: 'packages' in line ? line.packages : null })), scan.audits) })
297
306
 
298
307
  type DependabotLine = Extract<RepositoryRiskLine, { type: 'dependabot' }>
@@ -332,6 +341,9 @@ async function tellRepository(scan: Scan, repo: RepositoryRiskRepo, read: Audite
332
341
  if (scan.signal.aborted) return
333
342
  const { commit, lockfiles } = read
334
343
  scan.lines.add({ type: 'repo', id: repo.repoId, commit, lockfiles: lockfiles.map(({ line: { path, format } }) => ({ path, format })) })
344
+ const building = stasisBuilding(read.stasis), reached = stasisVersions(read.stasis)
345
+ reach(scan, reached)
346
+ scan.reach.building(building.map(config => ({ repoId: repo.repoId, commit, config })))
335
347
  for (const { line } of lockfiles) {
336
348
  scan.lines.add(line)
337
349
  if ('packages' in line) assessLater(scan, line.packages)
@@ -348,7 +360,8 @@ async function tellRepository(scan: Scan, repo: RepositoryRiskRepo, read: Audite
348
360
  if (scan.signal.aborted) return
349
361
  if (dependabot) scan.lines.add(dependabotLine(repo.repoId, dependabot, lockfiles))
350
362
  scan.told.set(repo.repoId, { id: repo.repoId, name: repo.fullName, paths: repo.paths ?? null,
351
- lockfiles: lockfiles.flatMap(({ sha, line }) => 'packages' in line ? [`${line.format}\0${sha}`] : []), ...refs.length > 0 ? { actions: refs } : {} })
363
+ lockfiles: lockfiles.flatMap(({ sha, line }) => 'packages' in line ? [`${line.format}\0${sha}`] : []), ...refs.length > 0 ? { actions: refs } : {}, ...reached.length > 0 ? { stasis: reached } : {},
364
+ ...building.length > 0 ? { building: { commit, configs: building } } : {} })
352
365
  }
353
366
 
354
367
  // A repository's Actions told, and the references they make to resolve.
@@ -362,8 +375,9 @@ function tellActions(scan: Scan, repo: RepositoryRiskRepo, read: WorkflowsRead,
362
375
 
363
376
  // Whether an earlier part told `repo` whole, by its name and a team's
364
377
  // directories in it as they are now, its packages then looked up as its
365
- // lockfiles are kept, GitHub asked nothing of it: not where one isn't. It is
366
- // told as read then, its default branch's head not asked again.
378
+ // lockfiles are kept, those its Stasis builds made install before the rest,
379
+ // those still to be made watched, GitHub asked nothing of it: not where one
380
+ // isn't. It is told as read then, its default branch's head not asked again.
367
381
  async function toldBefore(scan: Scan, repo: RepositoryRiskRepo) {
368
382
  const told = scan.told.get(repo.repoId)
369
383
  if (!told || told.name !== repo.fullName || JSON.stringify(told.paths) !== JSON.stringify(repo.paths ?? null)) return false
@@ -374,6 +388,9 @@ async function toldBefore(scan: Scan, repo: RepositoryRiskRepo) {
374
388
  if (!read || !('packages' in read)) return false
375
389
  reads.push(read.packages)
376
390
  }
391
+ reach(scan, told.stasis ?? [])
392
+ const { building } = told
393
+ if (building) scan.reach.building(building.configs.map(config => ({ repoId: told.id, commit: building.commit, config })))
377
394
  for (const packages of reads) assessLater(scan, packages)
378
395
  scan.actions?.add(told.actions ?? [])
379
396
  return true
@@ -406,41 +423,50 @@ async function readRepositories(scan: Scan) {
406
423
  }
407
424
  }
408
425
 
409
- // What is left to assess once the repositories are read, a turn at a time:
410
- // the stale ones that more than devDependencies need, then those only
411
- // devDependencies need, those with none kept before the stale ones.
412
- function leftOver(scan: Scan): AssessedPackage[][] {
413
- const dev = (pkg: AssessedPackage) => scan.seen.get(seenKey(pkg)) === true
414
- return [scan.stale.filter(pkg => !dev(pkg)), [...scan.dev.values(), ...scan.stale.filter(dev)]]
415
- }
426
+ // What is left to assess once the repositories are read, a turn at a time,
427
+ // each taken as it begins, as a build made since may tell more Stasis's:
428
+ // those with none kept that only devDependencies need, then the stale ones,
429
+ // those a Stasis build installs, those more than devDependencies need, and
430
+ // those only devDependencies need.
431
+ const isDev = (scan: Scan, pkg: AssessedPackage) => scan.seen.get(seenKey(pkg)) === true
432
+ const LEFT_OVER: { stale: boolean; of(scan: Scan, pkg: AssessedPackage): boolean }[] = [{ stale: false, of: () => true }, { stale: true, of: isStasis },
433
+ { stale: true, of: (scan, pkg) => !isDev(scan, pkg) }, { stale: true, of: () => true }]
416
434
 
417
435
  // The scan's work, behind its lines (repositoryRiskLines), `done` last, its
418
- // lines closed once it ends, its failure given to `fail`.
419
- async function runScan(scan: Scan, fail: (error: unknown) => void) {
436
+ // lines closed once it ends, its failure given to `fail`; the builds still to
437
+ // be made watched meanwhile, every `everyMs`, none waited for.
438
+ async function runScan(scan: Scan, fail: (error: unknown) => void, everyMs: number) {
439
+ const watching = new AbortController(), { stasisBuilt } = scan.source
440
+ const watch = stasisBuilt ? scan.reach.watch(build => stasisBuilt(build), (build, versions) => { madeSince(scan, build, versions) },
441
+ AbortSignal.any([scan.signal, watching.signal]), everyMs) : null
420
442
  try {
421
443
  // Those with no risk line kept assessed first, as their lockfiles are read,
444
+ // those a Stasis build installs before the rest,
422
445
  await assessing(scan, async assess => {
423
446
  const looking = lookUp(scan, assess)
424
447
  // stopped at once where reading fails;
425
448
  try { await readRepositories(scan) } catch (error) { fail(error) } finally { scan.lookups.close() }
426
449
  await looking
427
450
  })
428
- // then those told stale, and those only devDependencies need, in turn.
429
- for (const left of leftOver(scan)) {
430
- if (!scan.signal.aborted && left.length > 0) await assessing(scan, assess => { assess(left); return Promise.resolve() })
451
+ // then those only devDependencies need, and those told stale, in turn.
452
+ for (const { stale, of } of LEFT_OVER) {
453
+ const from = stale ? scan.stale : scan.dev, left = [...from.values()].filter(pkg => of(scan, pkg))
454
+ for (const pkg of left) from.delete(seenKey(pkg))
455
+ if (!scan.signal.aborted && left.length > 0) await assessing(scan, assess => { assess(left); return Promise.resolve() }, stale)
431
456
  }
432
457
  await scan.actions?.close()
433
458
  if (!scan.signal.aborted) scan.lines.add({ type: 'done' })
434
- } catch (error) { fail(error) } finally { scan.lines.close() }
459
+ } catch (error) { fail(error) } finally { watching.abort(); await watch; scan.lines.close() }
435
460
  }
436
461
 
437
462
  // The scan's lines, in the order they are found: the repositories first,
438
463
  // then each repository's lockfiles and their packages once read and access
439
464
  // is checked again, and each package's risk: as kept, however old, at once
440
465
  // (lookUp), then those with none kept once assessed, while the repositories
441
- // are still being read, then those told stale once assessed again, and those
442
- // only devDependencies need after all the rest (leftOver); `done`
443
- // last. Ends at once, the work
466
+ // are still being read, those a Stasis build installs first, then those only
467
+ // devDependencies need, then those told stale once assessed again, in the
468
+ // same order (LEFT_OVER), a Stasis build made meanwhile asked of every
469
+ // `stasisEveryMs` (STASIS_AGAIN_MS); `done` last. Ends at once, the work
444
470
  // under way given up on, where `signal` aborts or the lines are no longer read. A failure of
445
471
  // a repository, a lockfile or a package is told in its line; one of the scan
446
472
  // itself is thrown, the lines before it told. What it reads is kept in
@@ -450,7 +476,7 @@ async function runScan(scan: Scan, fail: (error: unknown) => void) {
450
476
  // again: those it assessed are kept, and told at once then, and the
451
477
  // repositories it told whole kept as its source's `progress`.
452
478
  export async function* repositoryRiskLines<R extends RepositoryRiskRepo>(source: RepositoryRiskSource<R>, signal: AbortSignal, caches = shared,
453
- { partMs = null }: { partMs?: number | null } = {}): AsyncGenerator<RepositoryRiskLine> {
479
+ { partMs = null, stasisEveryMs = STASIS_AGAIN_MS }: { partMs?: number | null; stasisEveryMs?: number } = {}): AsyncGenerator<RepositoryRiskLine> {
454
480
  const part = new AbortController(), stopped = new AbortController()
455
481
  const parting = partMs === null ? undefined : setTimeout(() => { part.abort() }, partMs)
456
482
  const running = AbortSignal.any([signal, stopped.signal, part.signal])
@@ -460,12 +486,12 @@ export async function* repositoryRiskLines<R extends RepositoryRiskRepo>(source:
460
486
  const lines = queue<RepositoryRiskLine>(AbortSignal.any([signal, part.signal]), { drain: true })
461
487
  const actions = source.actions ? resolvingActions({ source: source.actions, signal: running, tell: line => { lines.add(line) }, memory: caches.actions,
462
488
  answers: caches.actionAnswers, store: source.actionLines }) : null
463
- const scan: Scan = { source, caches, signal: running, lines, lookups: queue(running), seen: new Map(), dev: new Map(), stale: [], told: new Map(), actions,
464
- audits: inTurns(AUDITS_AT_ONCE) }
489
+ const scan: Scan = { source, caches, signal: running, lines, lookups: queue(running), seen: new Map(), dev: new Map(), stale: new Map(), reach: stasisReach(),
490
+ turn: null, told: new Map(), actions, audits: inTurns(AUDITS_AT_ONCE) }
465
491
  // A failure of the scan itself kept, to throw once the lines before it are
466
492
  // told, and the scan stopped.
467
493
  const failed: unknown[] = []
468
- void runScan(scan, error => { failed.push(error); stopped.abort() })
494
+ void runScan(scan, error => { failed.push(error); stopped.abort() }, stasisEveryMs)
469
495
  try {
470
496
  let done = false
471
497
  for (let line = await scan.lines.take(); line !== undefined; line = await scan.lines.take()) {