@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
@@ -67,11 +67,14 @@
67
67
  // name are (github-users.ts), by login
68
68
  // POST /api/admin/repositories/remove → admin permanently removes a repo
69
69
  // GET /api/admin/repositories/risk[?team=|?repo=] → admin: each connected repo's npm lockfiles, or a team's or one repo's,
70
- // their packages and what risk tells of each, Brotli-encoded ndjson as each is found; the reader leaving stops it | 400/401/403/404
71
- // GET /api/admin/repositories/risk/stasis?repoId=&commit=&path=… → admin: what Stasis reaches of a repo's stasis.config.json
72
- // files at a commit, each built as its dependency review builds it, a build still to be made asked for again | 400/401/403/404
73
- // GET /api/admin/repositories/risk/lockfile?repoId=&commit=&path= → admin: an npm lockfile of a repo at a commit, as a scan
74
- // read it, and the package.json beside a yarn.lock, for what depends on a package it locks | 400/401/403/404/429/502
70
+ // their packages and what risk tells of each, Brotli-encoded ndjson as each is found; the reader leaving stops it; a manager:
71
+ // a team's they are a member of alone (readRiskSession) | 400/401/403/404
72
+ // GET /api/admin/repositories/risk/stasis?repoId=&commit=&path=…[&team=] → admin, or a manager of `team`: what Stasis reaches
73
+ // of a repo's stasis.config.json files at a commit, each built as its dependency review builds it, a build still to be made
74
+ // asked for again; with `team`, of its repos and directories alone | 400/401/403/404
75
+ // GET /api/admin/repositories/risk/lockfile?repoId=&commit=&path=[&team=] → admin, or a manager of `team`: an npm lockfile of
76
+ // a repo at a commit, as a scan read it, and the package.json beside a yarn.lock, for what depends on a package it locks;
77
+ // with `team`, of its repos and directories alone | 400/401/403/404/429/502
75
78
  // GET /api/admin/reports → admin|manage list of uploaded reports | 401/403
76
79
  // POST /api/admin/reports → admin|manage uploads a report (raw body) | 401/403/413
77
80
  // GET /api/admin/reports/<id> → admin|manage downloads a stored report | 401/403/404
@@ -203,7 +206,7 @@ import type { ConnectedRepo } from './github-app.ts'
203
206
  import { canAddAnyPublicRepository, canAddRepositories, passesPublicRepositorySafeguard } from './repository-policy.ts'
204
207
  import { RepositoryDiscovery } from './repository-discovery.ts'
205
208
  import { RISK_KEPT_MS, SCAN_READ_KEPT_MS, type ScanProgress, repositoryRiskLines } from './repository-risk.ts'
206
- import { stasisConfigRow } from './repository-risk-read.ts'
209
+ import { lockfileOf, stasisConfigRow } from './repository-risk-read.ts'
207
210
  import { WORKFLOWS_DIR } from './repository-actions.ts'
208
211
  import { githubActionsSource } from './github-actions.ts'
209
212
  import { type RepositoryEntry, createRepositoryBrowser, repositoryTreeFiles, scopedDirectory } from './repository-browser.ts'
@@ -3523,9 +3526,10 @@ async function sendEncoded(req: IncomingMessage, res: ServerResponse, blob: Open
3523
3526
  }
3524
3527
 
3525
3528
 
3526
- // How often a scan of repositories' risk checks again that its reader is
3527
- // still an admin, between the lines it sends; and how long its connection may
3528
- // go idle, unread or with no line to send, before the scan is stopped.
3529
+ // How often a scan of repositories' risk checks again that its reader may
3530
+ // still read it (mayReadRisk), between the lines it sends; and how long its
3531
+ // connection may go idle, unread or with no line to send, before the scan
3532
+ // is stopped.
3529
3533
  const REPO_RISK_RECHECK_MS = 10_000
3530
3534
  const REPO_RISK_IDLE_MS = 5 * 60_000
3531
3535
  // A scan's part on a serverless deployment, within its function's 300s
@@ -3560,6 +3564,36 @@ async function riskRepositories(db: ManagedDb, query: URLSearchParams): Promise<
3560
3564
  })
3561
3565
  }
3562
3566
 
3567
+ // Who reads repositories' risk, of the scope `query` names: an admin, any;
3568
+ // or a manager, a team's alone (`team`), one they are a member of and not
3569
+ // hidden, as its Risk tab scans it (ui/view/workspace-content.js). Null,
3570
+ // answered, for anyone else.
3571
+ async function readRiskSession(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams, { handed = false } = {}) {
3572
+ const s = await readManageSession(res, deps, cookie, { handed })
3573
+ if (!s) return null
3574
+ if (await mayReadRisk(deps.db, s.user, query)) return s
3575
+ sendJson(res, 403, { error: 'forbidden' })
3576
+ return null
3577
+ }
3578
+
3579
+ // Whether `user` may read risk of the scope `query` names (readRiskSession).
3580
+ async function mayReadRisk(db: ManagedDb, user: StoredUser, query: URLSearchParams): Promise<boolean> {
3581
+ if (user.role === 'admin') return true
3582
+ const teamId = query.get('team')
3583
+ if (user.role !== 'manage' || teamId === null || query.has('repo')) return false
3584
+ const team = (await db.listTeams()).find(item => item.id === teamId)
3585
+ return team !== undefined && !team.hidden && team.members.some(member => member.userId === user.id)
3586
+ }
3587
+
3588
+ // Repository `repoId` as a scan of `query`'s scope reads it: connected, and
3589
+ // where `query` names a team, the team's, with its directories in it; null
3590
+ // where it isn't.
3591
+ async function riskRepository(db: ManagedDb, query: URLSearchParams, repoId: number): Promise<(SelectedRepo & { paths?: string[] }) | null> {
3592
+ const teamId = query.get('team')
3593
+ const repos: (SelectedRepo & { paths?: string[] })[] | null = teamId === null ? await db.listSelectedRepos() : await riskRepositories(db, new URLSearchParams({ team: teamId }))
3594
+ return repos?.find(item => item.repoId === repoId) ?? null
3595
+ }
3596
+
3563
3597
  // What Stasis reaches of the stasis.config.json at `config` of `repo` at
3564
3598
  // `commit`, as its dependency review's reader has it (stasisReader): the
3565
3599
  // same builds, in the same worker, kept the same way. One not kept yet is
@@ -3583,18 +3617,20 @@ async function riskStasis(deps: ManagedHttpDeps, repo: { repoId: number; fullNam
3583
3617
  // them (repository-risk-read.ts StasisConfigRow), for its page to ask again
3584
3618
  // while builds of them are still to be made, every 30 seconds as a dependency
3585
3619
  // review's page asks: each asked for again (riskStasis), lest it lapse
3586
- // (stasis-dependencies.ts). For admins, with their own GitHub access, as the
3587
- // scan reads the repository; a path naming no stasis.config.json in the
3588
- // commit's tree told so (`no-config`).
3620
+ // (stasis-dependencies.ts). For admins, or managers of the team it names
3621
+ // (`team`, of whose repositories and directories alone: riskRepository),
3622
+ // with their own GitHub access, as the scan reads the repository; a path
3623
+ // naming no stasis.config.json in the commit's tree told so (`no-config`).
3589
3624
  const MAX_RISK_STASIS = 50
3590
3625
  async function handleRepositoryRiskStasis(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
3591
- const s = await readAdminSession(res, deps, cookie)
3626
+ const s = await readRiskSession(res, deps, cookie, query)
3592
3627
  if (!s) return
3593
3628
  const commit = query.get('commit') ?? '', paths = query.getAll('path'), repoId = askedRepoId(query)
3594
3629
  if (repoId === null || !/^[\da-f]{40}$/u.test(commit) || paths.length === 0 || paths.length > MAX_RISK_STASIS || new Set(paths).size < paths.length
3595
3630
  || !paths.every(isStasisConfig)) { sendJson(res, 400, { error: 'bad-request' }); return }
3596
- const repo = (await deps.db.listSelectedRepos()).find(item => item.repoId === repoId)
3631
+ const repo = await riskRepository(deps.db, query, repoId)
3597
3632
  if (!repo) { sendJson(res, 404, { error: 'no-repository' }); return }
3633
+ if (!paths.every(path => lockfileOf(path, repo.paths))) { sendJson(res, 403, { error: 'forbidden' }); return }
3598
3634
  try {
3599
3635
  const reader = await repositoryReader(deps, s.user.id, repo)
3600
3636
  const token = reader.readToken()
@@ -3612,16 +3648,19 @@ async function handleRepositoryRiskStasis(res: ServerResponse, deps: ManagedHttp
3612
3648
  // GET /api/admin/repositories/risk/lockfile?repoId=&commit=&path=: a lockfile
3613
3649
  // a risk scan reads (locked-packages.ts) at `commit`, for its page to show
3614
3650
  // what depends on a package in it: its text, and the package.json beside a
3615
- // yarn.lock, which its reader there takes (null for none). For admins, with
3616
- // their own GitHub access, as the scan reads the repository.
3651
+ // yarn.lock, which its reader there takes (null for none). For admins, or
3652
+ // managers of the team it names (`team`, of whose repositories and
3653
+ // directories alone: riskRepository), with their own GitHub access, as the
3654
+ // scan reads the repository.
3617
3655
  const RISK_LOCKFILE = /^(?:(?!\.\.?\/)[^/]+\/)*(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock)$/u
3618
3656
  async function handleRepositoryRiskLockfile(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
3619
- const s = await readAdminSession(res, deps, cookie)
3657
+ const s = await readRiskSession(res, deps, cookie, query)
3620
3658
  if (!s) return
3621
3659
  const commit = query.get('commit') ?? '', path = query.get('path') ?? '', repoId = askedRepoId(query)
3622
3660
  if (repoId === null || !/^[\da-f]{40}$/u.test(commit) || !RISK_LOCKFILE.test(path)) { sendJson(res, 400, { error: 'bad-request' }); return }
3623
- const repo = (await deps.db.listSelectedRepos()).find(item => item.repoId === repoId)
3661
+ const repo = await riskRepository(deps.db, query, repoId)
3624
3662
  if (!repo) { sendJson(res, 404, { error: 'no-repository' }); return }
3663
+ if (!lockfileOf(path, repo.paths)) { sendJson(res, 403, { error: 'forbidden' }); return }
3625
3664
  try {
3626
3665
  const client = createClient({ token: (await repositoryReader(deps, s.user.id, repo)).readToken() })
3627
3666
  const file = (at: string) => upstreamGithub(() => client.getRepoFile({ repo: repo.fullName, path: at, ref: commit }))
@@ -3645,8 +3684,9 @@ function scanProgress(deps: ManagedHttpDeps, key: string, scan: string | null) {
3645
3684
  }
3646
3685
 
3647
3686
  // GET /api/admin/repositories/risk: every connected repository's npm
3648
- // packages, or a team's or one repository's (riskRepositories), as its
3649
- // lockfiles lock them at its default branch's head, each assessed by risk
3687
+ // packages, or a team's or one repository's (riskRepositories), but those
3688
+ // GitHub has archived, told so as each is opened and read no further, as
3689
+ // its lockfiles lock them at its default branch's head, each assessed by risk
3650
3690
  // (repository-risk.ts), a line as each is found. A
3651
3691
  // repository is read with the admin's own GitHub access, as browsing it is
3652
3692
  // (repository-browser.ts), and that access checked again once it is read,
@@ -3658,11 +3698,13 @@ function scanProgress(deps: ManagedHttpDeps, key: string, scan: string | null) {
3658
3698
  // GitHub (dependabot-access.ts); and its GitHub Actions, the references they
3659
3699
  // make resolved with the admin's own GitHub token (github-actions.ts); and
3660
3700
  // what Stasis reaches of each of its stasis.config.json files, as its
3661
- // dependency review has them built (riskStasis). The
3662
- // reader leaving, losing their admin role or
3663
- // the server shutting down stops it.
3701
+ // dependency review has them built (riskStasis), a build still to be made
3702
+ // looked at again as the scan goes on. Read by an admin, or by a
3703
+ // manager of the team it names (readRiskSession), each alike, with their
3704
+ // own access. The reader leaving, losing what let them read it or the
3705
+ // server shutting down stops it.
3664
3706
  async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
3665
- const s = await readAdminSession(res, deps, cookie, { handed: true })
3707
+ const s = await readRiskSession(res, deps, cookie, query, { handed: true })
3666
3708
  if (!s) return
3667
3709
  const repos = await riskRepositories(deps.db, query)
3668
3710
  if (!repos) {
@@ -3692,6 +3734,8 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3692
3734
  repos: () => Promise.resolve(repos),
3693
3735
  async open(repo) {
3694
3736
  const reader = await browser.reader(repo)
3737
+ // One GitHub has archived is read no further, as nothing installs from it anew.
3738
+ if (reader.archived) return { archived: true as const }
3695
3739
  const commit = await reader.commit('')
3696
3740
  const token = reader.readToken()
3697
3741
  const client = createClient({ token })
@@ -3710,6 +3754,10 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3710
3754
  stasis: config => riskStasis(deps, repo, token, commit, reader.defaultBranch, config),
3711
3755
  }
3712
3756
  },
3757
+ // What Stasis has made of a build still to be made as the scan read its
3758
+ // repository, as its dependency review's reader has it: the page asks
3759
+ // for the build again (handleRepositoryRiskStasis), the scan only looks.
3760
+ stasisBuilt: ({ repoId, commit, config }) => stasisReader(deps).read(repoId, commit, config),
3713
3761
  // References resolved with the admin's token, and each one's advisories
3714
3762
  // asked as a bundle's `github` package's are (bundle-advisories.ts), one
3715
3763
  // `internal` of its repository alone, each bounded on its own.
@@ -3766,7 +3814,8 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3766
3814
  await sendLines(res, lines, async () => {
3767
3815
  if (deps.isShuttingDown()) return false
3768
3816
  if (Date.now() - checked < REPO_RISK_RECHECK_MS) return true
3769
- if ((await readSession(deps.config, deps.db, cookie, Date.now()))?.user.role !== 'admin') return false
3817
+ const current = await readSession(deps.config, deps.db, cookie, Date.now())
3818
+ if (current?.user.id !== s.user.id || !await mayReadRisk(deps.db, current.user, query)) return false
3770
3819
  checked = Date.now()
3771
3820
  return true
3772
3821
  })
@@ -64,7 +64,7 @@ interface ReadPackage { name: string; version: string | undefined; resolution: R
64
64
  // patched one of pnpm's with its patch's file where the lockfile names it,
65
65
  // but one pnpm 9 names by an md5, which reviews don't read (isPatchHash).
66
66
  // Versions go unchecked against ranges, as only what is locked is asked for.
67
- function packagesOf(format: LockfileFormat, text: string): ReadPackage[] {
67
+ function packagesOf(format: LockfileFormat, text: string, manifests?: YarnManifests | null): ReadPackage[] {
68
68
  if (format === 'npm') return Object.values(parseNpmLockfile(text, { checkVersions: false }).packages)
69
69
  if (format === 'pnpm') {
70
70
  const { lockfile, env } = parsePnpmLockfile(text)
@@ -76,8 +76,17 @@ function packagesOf(format: LockfileFormat, text: string): ReadPackage[] {
76
76
  // Yarn 2 and later write another format, which only the text tells apart.
77
77
  if (/^__metadata:/mu.test(text)) throw new LockfileError('a yarn.lock of Yarn 2 or later, which is not read')
78
78
  // Yarn 1 names an alias, `my-q@npm:q@^1.5.1`, by its own name, and
79
- // resolves none of a directory (`file:` or `link:`).
80
- return Object.values(parseYarn1Lockfile(text, { checkVersions: false }).packages)
79
+ // resolves none of a directory (`file:` or `link:`). What only
80
+ // devDependencies need its manifests alone say: read with them, else, of
81
+ // ones its reader refuses (a workspace of no version, say), without, none
82
+ // told so.
83
+ const read = (withManifests: boolean) => parseYarn1Lockfile(text, { checkVersions: false, ...withManifests && manifests && { manifests } }).packages
84
+ let packages
85
+ try { packages = read(true) } catch (error) {
86
+ if (!manifests || !(error instanceof LockfileError)) throw error
87
+ packages = read(false)
88
+ }
89
+ return Object.values(packages)
81
90
  .map(pkg => ({ ...pkg, name: /@npm:((?:@[^/@]+\/)?[^/@]+)/u.exec(pkg.patterns[0] ?? '')?.[1] ?? pkg.name, resolution: pkg.resolution ?? { type: 'directory' as const } }))
82
91
  }
83
92
 
@@ -128,9 +137,9 @@ function locked(pkg: ReadPackage, format: LockfileFormat, review: boolean): Lock
128
137
  // reviews hold it to (LockedPackage `integrity`, `shasum`, `patchHash`),
129
138
  // each patch of it apart. Throws the reader's LockfileError or YamlError for
130
139
  // one it refuses.
131
- export function lockedPackages(format: LockfileFormat, text: string, { review = false } = {}): LockedPackage[] {
140
+ export function lockedPackages(format: LockfileFormat, text: string, { review = false, manifests = null as YarnManifests | null } = {}): LockedPackage[] {
132
141
  const found = new Map<string, LockedPackage>()
133
- for (const pkg of packagesOf(format, text)) {
142
+ for (const pkg of packagesOf(format, text, manifests)) {
134
143
  const one = locked(pkg, format, review)
135
144
  if (!one) continue
136
145
  if (pkg.dev === true) one.dev = true
@@ -142,6 +151,54 @@ export function lockedPackages(format: LockfileFormat, text: string, { review =
142
151
  return [...found.values()]
143
152
  }
144
153
 
154
+ // A yarn.lock's package.json files (`manifests`, yarn1.js), by directory
155
+ // from it, `.` its own: Yarn 1's lockfile says nothing of what only
156
+ // devDependencies need, which they alone do.
157
+ export type YarnManifests = Record<string, object>
158
+ // How many workspaces' are read at most; past it, none are, nor told dev.
159
+ const MAX_YARN_WORKSPACES = 200
160
+
161
+ // Whether a directory, from the root's, is one a glob of its `workspaces`
162
+ // finds, as yarn 1's minimatch reads one (@preventive/lockfile's glob.js): a
163
+ // segment at a time, `**` any of them, `*` and `?` within one, none of
164
+ // these taking a segment that starts with `.`.
165
+ function workspaceGlob(glob: string) {
166
+ const globs = glob.replace(/^(?:\.\/)+/u, '').replace(/\/+$/u, '').split('/')
167
+ const segment = (pattern: string) => new RegExp(`^${pattern.replaceAll(/[.+^${}()|[\]\\]/gu, '\\$&').replaceAll('*', '[^/]*').replaceAll('?', '[^/]')}$`, 'u')
168
+ const tests = globs.map(each => each === '**' ? null : { test: segment(each), wild: /[*?]/u.test(each) && !each.startsWith('.') })
169
+ const matches = (at: number, parts: string[], from: number): boolean => {
170
+ if (at === tests.length) return from === parts.length
171
+ const test = tests[at]!
172
+ if (test === null) return matches(at + 1, parts, from) || (from < parts.length && !parts[from]!.startsWith('.') && matches(at, parts, from + 1))
173
+ return from < parts.length && !(test.wild && parts[from]!.startsWith('.')) && test.test.test(parts[from]!) && matches(at + 1, parts, from + 1)
174
+ }
175
+ return (dir: string) => matches(0, dir.split('/'), 0)
176
+ }
177
+
178
+ // The package.json files a yarn.lock at `path` is read with (YarnManifests):
179
+ // the one beside it, and where it names `workspaces`, each of `files` (the
180
+ // repository's) its globs find, outside node_modules, MAX_YARN_WORKSPACES at
181
+ // most, read by `file`. Null where there is none beside it, one isn't JSON,
182
+ // or one couldn't be read.
183
+ export async function yarnManifests(path: string, file: (path: string) => Promise<string>, files?: () => Promise<string[]>): Promise<YarnManifests | null> {
184
+ const dir = path.slice(0, Math.max(path.lastIndexOf('/'), 0)), from = (at: string) => dir ? `${dir}/${at}` : at
185
+ const json = (text: string) => { try { const value: unknown = JSON.parse(text); return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null } catch { return null } }
186
+ try {
187
+ const root = json(await file(from('package.json')))
188
+ if (!root) return null
189
+ const listed = Array.isArray(root['workspaces']) ? root['workspaces'] : (root['workspaces'] as { packages?: unknown } | undefined)?.packages
190
+ const globs = Array.isArray(listed) ? listed.filter(each => typeof each === 'string').map(workspaceGlob) : []
191
+ if (globs.length === 0 || !files) return { '.': root }
192
+ const workspaces = (await files()).flatMap(each => {
193
+ const at = each.endsWith('/package.json') && (dir === '' || each.startsWith(`${dir}/`)) ? each.slice(dir ? dir.length + 1 : 0, -'/package.json'.length) : null
194
+ return at && !at.split('/').includes('node_modules') && globs.some(matches => matches(at)) ? [at] : []
195
+ })
196
+ if (workspaces.length > MAX_YARN_WORKSPACES) return null
197
+ const read = await Promise.all(workspaces.map(async at => [at, json(await file(from(`${at}/package.json`)))] as const))
198
+ return read.every(([, manifest]) => manifest) ? Object.fromEntries([['.', root], ...read]) as YarnManifests : null
199
+ } catch { return null }
200
+ }
201
+
145
202
  // `path`, from directory `dir` ('' the repository's root), from the root;
146
203
  // null where it leads outside the repository, or names nothing.
147
204
  export function pathFrom(dir: string, path: string): string | null {
@@ -392,8 +392,9 @@ export const npmExecutablePaths = (files: NpmPackageFile[]) => files.flatMap(fil
392
392
  export const pathOrder = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
393
393
 
394
394
  // How a tar stream is read (readNpmTar): how far its symlinks may climb above
395
- // it, and the entries, files and bytes it may hold, a package's unless given.
396
- export interface TarReading { symlinksAbove?: number; maxEntries?: number; maxFiles?: number; maxBytes?: number }
395
+ // it, and the entries, files and bytes it may hold, a package's unless given;
396
+ // and whether two paths one on macOS or Windows conflict (`foldPaths`), as they do unless given.
397
+ export interface TarReading { symlinksAbove?: number; maxEntries?: number; maxFiles?: number; maxBytes?: number; foldPaths?: boolean }
397
398
 
398
399
  // The regular files of a tar stream, by package path, as npm and pnpm install
399
400
  // them (risk's npmTarLayout): each name as stored past its first component,
@@ -406,18 +407,19 @@ export interface TarReading { symlinksAbove?: number; maxEntries?: number; maxFi
406
407
  // or not an installer installs it, a hard link as its target's bytes, a
407
408
  // symlink for where it points. Where
408
409
  // the files conflict (two that differ at one path, as under two top
409
- // directories, a file within another), it is refused as `tarball-conflict`,
410
+ // directories, or at two paths one on macOS or Windows unless `foldPaths` is
411
+ // false, a file within another), it is refused as `tarball-conflict`,
410
412
  // never read as one installer does. Directories and devices hold no file
411
413
  // content and are skipped.
412
414
  export function readNpmTar(tar: Uint8Array, { symlinksAbove = NPM_SYMLINKS_ABOVE, maxEntries = MAX_NPM_TAR_ENTRIES, maxFiles = MAX_NPM_PACKAGE_FILES,
413
- maxBytes = MAX_NPM_PACKAGE_BYTES }: TarReading = {}): NpmPackageFile[] {
415
+ maxBytes = MAX_NPM_PACKAGE_BYTES, foldPaths = true }: TarReading = {}): NpmPackageFile[] {
414
416
  let entries: Entry[]
415
417
  try { entries = unpack(tar, { maxEntries, symlinksAbove }) }
416
418
  catch (err) {
417
419
  if (err instanceof ArchiveError) throw err.limited ? new NpmPackageError(413, 'package-too-large') : new NpmPackageError(422, 'bad-tarball')
418
420
  throw err
419
421
  }
420
- const files = npmTarLayout(entries, { maxFiles, maxBytes }, (code) => { throw new NpmPackageError(code === 'package-too-large' ? 413 : 422, code) })
422
+ const files = npmTarLayout(entries, { maxFiles, maxBytes, foldPaths }, (code) => { throw new NpmPackageError(code === 'package-too-large' ? 413 : 422, code) })
421
423
  return [...files].map(([path, file]) => ({ path, ...file })).toSorted((a, b) => pathOrder(a.path, b.path))
422
424
  }
423
425
 
@@ -1,20 +1,21 @@
1
- // Items in the order they are added, each taken once by whichever reader asks
2
- // first: none once closed and all taken, or once `signal` aborts, but those
3
- // added by then where `drain`, none waited for.
4
- export interface Queue<T> { add(item: T): void; close(): void; take(): Promise<T | undefined> }
1
+ // Items in the order they are added, those added `first` before the rest,
2
+ // each taken once by whichever reader asks first: none once closed and all
3
+ // taken, or once `signal` aborts, but those added by then where `drain`, none
4
+ // waited for.
5
+ export interface Queue<T> { add(item: T, first?: boolean): void; close(): void; take(): Promise<T | undefined> }
5
6
  export function queue<T>(signal: AbortSignal, { drain = false } = {}): Queue<T> {
6
- const items: T[] = []
7
+ const firsts: T[] = [], items: T[] = []
7
8
  const waiting: (() => void)[] = []
8
9
  let closed = false
9
10
  const wake = () => { for (const resolve of waiting.splice(0)) resolve() }
10
11
  signal.addEventListener('abort', wake, { once: true })
11
12
  return {
12
- add(item) { items.push(item); wake() },
13
+ add(item, first = false) { (first ? firsts : items).push(item); wake() },
13
14
  close() { closed = true; wake() },
14
15
  async take() {
15
16
  for (;;) {
16
17
  if (signal.aborted && !drain) return undefined
17
- const item = items.shift()
18
+ const item = firsts.length > 0 ? firsts.shift() : items.shift()
18
19
  if (item !== undefined || closed || signal.aborted) return item
19
20
  await new Promise<void>(resolve => { waiting.push(resolve) })
20
21
  }
@@ -65,7 +65,7 @@ function credentialFailure(err: unknown): err is GithubApiError {
65
65
  // that token (`userToken`, hashed), whichever credential reads it: a private
66
66
  // repository's was granted on who that token told GitHub they are. The next
67
67
  // check asks GitHub, falling back to the installation's or none as it does.
68
- type RepoMetadata = { id?: unknown; full_name?: unknown; private?: unknown; visibility?: unknown; default_branch?: unknown }
68
+ type RepoMetadata = { id?: unknown; full_name?: unknown; private?: unknown; visibility?: unknown; default_branch?: unknown; archived?: unknown }
69
69
  type AccessVerdict = { until: number; data: RepoMetadata; credential: 'user' | 'app' | 'none'; level: string | null; userToken: string | null }
70
70
  type VerdictCache = { get(): AccessVerdict | undefined; set(verdict: Omit<AccessVerdict, 'until' | 'userToken'>): void }
71
71
  const MAX_ACCESS_VERDICTS = 1000
@@ -251,8 +251,8 @@ async function keptAccess(verdicts: VerdictCache | null, userToken: string | nul
251
251
  if (kept.credential === 'none' || credential) return { data: kept.data, token: credential, level: kept.level }
252
252
  }
253
253
  const asked = await ask()
254
- const { id, full_name, private: hidden, visibility, default_branch } = asked.data
255
- const data = { id, full_name, private: hidden, visibility, default_branch }
254
+ const { id, full_name, private: hidden, visibility, default_branch, archived } = asked.data
255
+ const data = { id, full_name, private: hidden, visibility, default_branch, archived }
256
256
  verdicts?.set({ data, credential: asked.token === null ? 'none' : asked.token === userToken ? 'user' : 'app', level: asked.level })
257
257
  return { ...asked, data }
258
258
  }
@@ -299,6 +299,9 @@ async function repositoryReader(repo: SelectedRepo, userToken: string | null, in
299
299
  // Its default branch as GitHub named it when access was first checked,
300
300
  // `''` where it named none: the one whose head `commit('')` reads.
301
301
  defaultBranch,
302
+ // Whether GitHub had it archived then, read-only, as a risk scan leaves
303
+ // one out (http.ts handleRepositoryRisk).
304
+ archived: current.archived === true,
302
305
  async refs() {
303
306
  // Suggestions are bounded; the input also accepts any branch or tag name.
304
307
  const list = async (kind: string) => {
@@ -22,8 +22,9 @@ export const MAX_REPOSITORY_CODE_FILES = 80_000
22
22
  export const MAX_REPOSITORY_CODE_BYTES = 256 * 1024 * 1024
23
23
  // The tarball they come in, bounded in proportion as a package's is: its tar
24
24
  // stream, headers and padding included, and its entries, as many again as
25
- // files, as GitHub's has one for each directory too.
26
- const REPOSITORY_TAR = { maxFiles: MAX_REPOSITORY_CODE_FILES, maxBytes: MAX_REPOSITORY_CODE_BYTES, maxEntries: 2 * MAX_REPOSITORY_CODE_FILES, maxTarBytes: 384 * 1024 * 1024 }
25
+ // files, as GitHub's has one for each directory too. Its paths are compared
26
+ // as git holds them, which may differ only in case.
27
+ const REPOSITORY_TAR = { maxFiles: MAX_REPOSITORY_CODE_FILES, maxBytes: MAX_REPOSITORY_CODE_BYTES, maxEntries: 2 * MAX_REPOSITORY_CODE_FILES, maxTarBytes: 384 * 1024 * 1024, foldPaths: false }
27
28
  // What the files may take as the viewer's JSON, written as one string: short
28
29
  // of the longest V8 holds (2^29 - 24 characters).
29
30
  const MAX_REPOSITORY_CODE_JSON_LENGTH = 384 * 1024 * 1024
@@ -0,0 +1,37 @@
1
+ // What repository risk scans keep between them (repository-risk.ts), in this
2
+ // instance's memory.
3
+ import { type Lru, lru } from './lru.ts'
4
+ import { type ActionAnswers, type ActionLine, type WorkflowsRead, answerWeight } from './repository-actions.ts'
5
+ import type { Audit } from './repository-risk-audit.ts'
6
+ import type { ListedLockfile, LockfileRead } from './repository-risk-read.ts'
7
+ import type { RiskLine } from './repository-risk.ts'
8
+
9
+ // What scans keep between them, in this instance's memory: a repository's
10
+ // lockfiles as listed at a commit, and a lockfile's packages by its blob,
11
+ // neither of which changes; a lockfile's advisories, asked again after
12
+ // RISK_KEPT_MS, as npm publishes advisories; and a package's risk line,
13
+ // told stale after RISK_KEPT_MS and assessed again, as risk tells again what
14
+ // of a package changes in time (a deprecation, its age, its downloads). A
15
+ // lockfile's, and its packages' lines, are told only once access to its
16
+ // repository is checked as when it was read.
17
+ export interface RiskCaches {
18
+ listings: Lru<ListedLockfile[]>
19
+ lockfiles: Lru<LockfileRead>
20
+ risks: Lru<{ at: number; line: RiskLine }>
21
+ advisories: Lru<{ at: number; audit: Audit }>
22
+ actionFiles: Lru<WorkflowsRead>
23
+ actions: Lru<{ at: number; line: ActionLine }>
24
+ actionAnswers: ActionAnswers
25
+ }
26
+ export const riskCaches = (): RiskCaches => ({
27
+ listings: lru(1000),
28
+ // By the packages they hold, a few hundred bytes each.
29
+ lockfiles: lru(200_000, read => 'packages' in read ? read.packages.length + 1 : 1),
30
+ risks: lru(50_000),
31
+ advisories: lru(50_000, kept => Array.isArray(kept.audit) ? kept.audit.length + 1 : 1),
32
+ // By their text, a kilobyte at a time.
33
+ 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),
34
+ actions: lru(10_000),
35
+ // What GitHub answered of public repositories' actions, by answerWeight.
36
+ actionAnswers: lru(200_000, answerWeight),
37
+ })
@@ -12,10 +12,11 @@
12
12
  // instance's memory, and the source's `listings`, `actionFiles` and
13
13
  // `lockfiles` for SCAN_READ_KEPT_MS, so that only opening a repository and
14
14
  // checking access to it again ask GitHub where all else is kept.
15
+ import { createHash } from 'node:crypto'
15
16
  import type { LockfileFormat, RepoLockfile } from '@preventive/upstream/github.js'
16
17
  import type { AlertsRead } from './dependabot-access.ts'
17
18
  import type { DependabotAlert } from './dependabot-alerts.ts'
18
- import { type LockedPackage, isTestFixture, lockedPackages } from './locked-packages.ts'
19
+ import { type LockedPackage, isTestFixture, lockedPackages, yarnManifests } from './locked-packages.ts'
19
20
  import type { Lru } from './lru.ts'
20
21
  import type { KeptStore } from './npm-kept.ts'
21
22
  import { inTurns } from './queue.ts'
@@ -45,6 +46,9 @@ export type LockfileRead = { packages: LockedPackage[] } | RiskFailure
45
46
  // be had.
46
47
  export type DependabotRead = { alerts: DependabotAlert[]; recheck?(): Promise<void> } | RiskFailure
47
48
  export type RepositoryFailure = Extract<RepositoryRiskLine, { type: 'repo'; error: string }>
49
+ // A repository GitHub has archived, which a scan reads no further: its
50
+ // history alone, nothing that installs anew.
51
+ export type RepositoryArchived = Extract<RepositoryRiskLine, { type: 'repo'; archived: true }>
48
52
  // What Stasis reaches of a stasis.config.json, as a dependency review's
49
53
  // build of it tells (stasis-dependencies.ts): the versions it installs
50
54
  // (`dependencies`), that its build is still to be made (`pending`), or why it
@@ -56,6 +60,16 @@ export type StasisConfigRow = { path: string; lockfiles?: string[] } & ({ depend
56
60
  // what Stasis reaches of it, or why they couldn't be listed.
57
61
  export type StasisConfigsRead = { configs: StasisConfigRow[] } | RiskFailure
58
62
 
63
+ // A version, as Stasis tells those it installs, whatever its integrity.
64
+ 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.
67
+ export const stasisVersions = (read: StasisConfigsRead | null): string[] => [...new Set(read && 'configs' in read
68
+ ? read.configs.flatMap(config => 'dependencies' in config ? config.dependencies.map(versionKey) : []) : [])]
69
+ // The paths of a repository's stasis.config.json files whose builds are still
70
+ // to be made.
71
+ export const stasisBuilding = (read: StasisConfigsRead | null): string[] => read && 'configs' in read ? read.configs.flatMap(config => 'pending' in config ? [config.path] : []) : []
72
+
59
73
  // A config's row of its read: a failed build told by its code (`detail`).
60
74
  export function stasisConfigRow(path: string, read: StasisRead): StasisConfigRow {
61
75
  if (read.status === 'ready') return { path, dependencies: read.dependencies }
@@ -86,7 +100,8 @@ export interface OpenedRepository {
86
100
  // What a repository is read with: the scan's source and caches, and its
87
101
  // signal.
88
102
  interface RepositoryReading<R extends RepositoryRiskRepo> {
89
- source: { open(repo: R): Promise<OpenedRepository>; listings?: KeptStore<ListedLockfile[]>; lockfiles?: KeptStore<LockfileRead>; actionFiles?: KeptStore<WorkflowsRead> }
103
+ source: { open(repo: R): Promise<OpenedRepository | { archived: true }>; listings?: KeptStore<ListedLockfile[]>; lockfiles?: KeptStore<LockfileRead>;
104
+ actionFiles?: KeptStore<WorkflowsRead> }
90
105
  caches: { listings: Lru<ListedLockfile[]>; lockfiles: Lru<LockfileRead>; actionFiles: Lru<WorkflowsRead> }
91
106
  signal: AbortSignal
92
107
  }
@@ -106,8 +121,9 @@ export interface RepositoryRead {
106
121
  recheck(): Promise<void>
107
122
  }
108
123
 
109
- // Whether a lockfile at `path` is of `paths` (RepositoryRiskRepo).
110
- function lockfileOf(path: string, paths: readonly string[] | undefined) {
124
+ // Whether a lockfile at `path` is of `paths` (RepositoryRiskRepo), as a
125
+ // stasis.config.json is.
126
+ export function lockfileOf(path: string, paths: readonly string[] | undefined) {
111
127
  const dir = path.slice(0, Math.max(path.lastIndexOf('/'), 0))
112
128
  return !paths || paths.some(scope => dir === '' || dir === scope || dir.startsWith(`${scope}/`) || scope.startsWith(`${dir}/`))
113
129
  }
@@ -127,29 +143,36 @@ async function keptRead<T>(memory: Lru<T>, store: KeptStore<T> | undefined, key:
127
143
  }
128
144
 
129
145
  // A lockfile's line, its packages or why they couldn't be had: as kept by its
130
- // blob, else read from GitHub and kept.
146
+ // blob, else read from GitHub and kept; with the `sha` it is kept by, a
147
+ // yarn.lock's with its package.json files' (yarnManifests), which alone say
148
+ // what only devDependencies need, and change while it may not.
131
149
  async function readLockfile({ source, caches }: RepositoryReading<RepositoryRiskRepo>, repo: number, opened: OpenedRepository,
132
- { path, format, sha }: ListedLockfile): Promise<LockfileLine> {
150
+ { path, format, sha }: ListedLockfile): Promise<{ sha: string; line: LockfileLine }> {
133
151
  const at = { type: 'lockfile', repo, path, format } as const
134
- if (!READ_FORMATS.has(format)) return { ...at, error: 'unsupported-format' }
152
+ if (!READ_FORMATS.has(format)) return { sha, line: { ...at, error: 'unsupported-format' } }
135
153
  try {
136
- return { ...at, ...await keptRead(caches.lockfiles, source.lockfiles, `${format}\0${sha}`, async (): Promise<LockfileRead> => {
154
+ const manifests = format === 'yarn' ? await yarnManifests(path, file => opened.file(file), opened.files) : null
155
+ const kept = manifests ? `${sha}+${createHash('sha256').update(JSON.stringify(manifests)).digest('hex').slice(0, 16)}` : sha
156
+ return { sha: kept, line: { ...at, ...await keptRead(caches.lockfiles, source.lockfiles, `${format}\0${kept}`, async (): Promise<LockfileRead> => {
137
157
  const text = await opened.file(path)
138
- try { return { packages: lockedPackages(format, text) } } catch (error) {
158
+ try { return { packages: lockedPackages(format, text, { manifests }) } } catch (error) {
139
159
  return { error: 'lockfile-unreadable', ...error instanceof Error ? { detail: error.message.slice(0, 500) } : {} }
140
160
  }
141
- }) }
142
- } catch (error) { return { ...at, ...failureOf(error) } }
161
+ }) } }
162
+ } catch (error) { return { sha, line: { ...at, ...failureOf(error) } } }
143
163
  }
144
164
 
145
165
  // A repository opened and its lockfiles of npm's ecosystem listed, as kept
146
166
  // for its commit or else from GitHub, those of its `paths` alone; its line
147
- // telling why where either failed; null where the scan stopped.
148
- async function listLockfiles<R extends RepositoryRiskRepo>(reading: RepositoryReading<R>, repo: R) {
167
+ // telling why where either failed, or that GitHub has it archived, read no
168
+ // further; null where the scan stopped.
169
+ async function listLockfiles<R extends RepositoryRiskRepo>(reading: RepositoryReading<R>, repo: R):
170
+ Promise<{ opened: OpenedRepository; lockfiles: ListedLockfile[] } | RepositoryFailure | RepositoryArchived | null> {
149
171
  let doing = 'opening it'
150
172
  try {
151
173
  const opened = await reading.source.open(repo)
152
174
  if (reading.signal.aborted) return null
175
+ if ('archived' in opened) return { type: 'repo', id: repo.repoId, archived: true } as const
153
176
  doing = 'listing its lockfiles'
154
177
  const listed = await keptRead(reading.caches.listings, reading.source.listings, `${repo.repoId}@${opened.commit}`, () => opened.lockfiles())
155
178
  const lockfiles = listed.filter(({ path, format }) => NPM_LOCKFILE_FORMATS.has(format) && lockfileOf(path, repo.paths))
@@ -210,10 +233,10 @@ export const namedLockfiles = (path: string) => (text: string): string[] | null
210
233
  // A repository read: its lockfiles listed and read, a few at once, its
211
234
  // Dependabot alerts asked, its Actions read and its stasis.config.json files
212
235
  // asked meanwhile; its line telling why where listing
213
- // failed; null where the scan stopped. A test's
236
+ // failed, or that it is archived; null where the scan stopped. A test's
214
237
  // fixture or example its reader refuses (isTestFixture) is left out, as a
215
238
  // test may keep one so on purpose.
216
- export async function readRepository<R extends RepositoryRiskRepo>(reading: RepositoryReading<R>, repo: R): Promise<RepositoryRead | RepositoryFailure | null> {
239
+ export async function readRepository<R extends RepositoryRiskRepo>(reading: RepositoryReading<R>, repo: R): Promise<RepositoryRead | RepositoryFailure | RepositoryArchived | null> {
217
240
  const listed = await listLockfiles(reading, repo)
218
241
  if (!listed || 'type' in listed) return listed
219
242
  const { opened } = listed
@@ -226,9 +249,9 @@ export async function readRepository<R extends RepositoryRiskRepo>(reading: Repo
226
249
  const inTurn = inTurns(LOCKFILES_AT_ONCE)
227
250
  const lines = await Promise.all(listed.lockfiles.map(lockfile => inTurn(() => (reading.signal.aborted ? Promise.resolve(null) : readLockfile(reading, repo.repoId, opened, lockfile)))))
228
251
  const lockfiles: RepositoryRead['lockfiles'] = []
229
- for (const [at, line] of lines.entries()) {
230
- if (!line) return null
231
- if (!('error' in line && line.error === 'lockfile-unreadable' && isTestFixture(line.path))) lockfiles.push({ sha: listed.lockfiles[at]!.sha, line })
252
+ for (const read of lines) {
253
+ if (!read) return null
254
+ if (!('error' in read.line && read.line.error === 'lockfile-unreadable' && isTestFixture(read.line.path))) lockfiles.push(read)
232
255
  }
233
256
  const dependabot = await alerting
234
257
  const actions = await acting