@preventive/triage 1.0.0-alpha.73 → 1.0.0-alpha.75

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 (61) hide show
  1. package/common/bundle-compare-diff.d.ts +4 -1
  2. package/common/bundle-compare-diff.js +4 -3
  3. package/common/bundle-sources.js +4 -2
  4. package/common/finding-duplicates.js +4 -4
  5. package/common/finding-filters.js +11 -13
  6. package/common/managed/roles.ts +6 -0
  7. package/common/managed/routes.js +4 -3
  8. package/common/managed/team-app.d.ts +2 -0
  9. package/common/managed/team-app.js +31 -14
  10. package/out/activity.js +1 -1
  11. package/out/{chunk-5NUDNLJA.js → chunk-62QT2RXR.js} +2 -2
  12. package/out/{chunk-ROHACH7V.js → chunk-EYTPAODY.js} +2 -2
  13. package/out/{chunk-PX5DLFSD.js → chunk-HLMQ7QYS.js} +1 -1
  14. package/out/chunk-ITUKKCCK.js +10 -0
  15. package/out/{chunk-BLPHP4U3.js → chunk-IVDE66N5.js} +1 -1
  16. package/out/{chunk-CXVBTUK3.js → chunk-NMC7P5AA.js} +2 -2
  17. package/out/chunk-O6FA2R5G.js +53 -0
  18. package/out/{chunk-RLLA4GHZ.js → chunk-PLF4LBLE.js} +1 -1
  19. package/out/{chunk-RGNF4OH6.js → chunk-RHOQDAU4.js} +1 -1
  20. package/out/{chunk-GV5U7OLP.js → chunk-SZHJZVBL.js} +1 -1
  21. package/out/{chunk-2IHCVA3Y.js → chunk-T6EXDRB7.js} +1 -1
  22. package/out/chunk-VOJBPNPL.js +255 -0
  23. package/out/{chunk-ROWUGPID.js → chunk-VSVFMSGI.js} +1 -1
  24. package/out/{chunk-TD7RVUTT.js → chunk-W5PRH5D7.js} +1 -1
  25. package/out/chunk-WGQ7D5DB.js +1 -0
  26. package/out/client-managed-import.js +1 -1
  27. package/out/client-managed.js +30 -30
  28. package/out/compare.js +4 -4
  29. package/out/dialogs.js +1 -1
  30. package/out/graph.js +1 -1
  31. package/out/index.html +10 -10
  32. package/out/prism.js +1 -1
  33. package/out/scan.js +1 -1
  34. package/out/view.css +1 -1
  35. package/out/view.js +4 -4
  36. package/package.json +4 -3
  37. package/risk/files/characters.js +142 -8
  38. package/risk/files/hosts.js +4 -3
  39. package/risk/files/readability.js +18 -13
  40. package/risk/files/runs-code.js +41 -80
  41. package/risk/files/script.js +210 -48
  42. package/risk/index.d.ts +6 -4
  43. package/risk/npm/assess.js +1 -1
  44. package/risk/npm/tarball.js +41 -25
  45. package/server-managed/comparison.ts +6 -5
  46. package/server-managed/http.ts +71 -28
  47. package/server-managed/locked-packages.ts +62 -5
  48. package/server-managed/npm-loads.ts +2 -2
  49. package/server-managed/npm-packages.ts +12 -6
  50. package/server-managed/npm-patch-paths.ts +57 -0
  51. package/server-managed/npm-patch.ts +71 -76
  52. package/server-managed/repository-code.ts +12 -8
  53. package/server-managed/repository-risk-read.ts +42 -15
  54. package/server-managed/team-app-summaries.ts +3 -1
  55. package/server-managed/team-app.ts +4 -2
  56. package/server-managed/team-reports.ts +8 -3
  57. package/out/chunk-5YP7P5KA.js +0 -1
  58. package/out/chunk-74AEKRES.js +0 -10
  59. package/out/chunk-BIWPZT4E.js +0 -52
  60. package/out/chunk-YCEMQETS.js +0 -255
  61. /package/out/{chunk-Y2XGV3RC.js → chunk-S5HSDGTP.js} +0 -0
@@ -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'
@@ -236,7 +239,7 @@ import { canDeleteComment, parseCommentBody } from '../common/managed/comments.t
236
239
  import { ManagedMutationError, reportReferenceSnapshot } from './management.ts'
237
240
  import { confirmedDefaultOffered, readConfirmedOffered, withConfirmedOffered } from './report-opening.ts'
238
241
  import { BundleBuildError, buildRepositoryBundle, buildRepositoryLockfile, parseBundleBuild, withBundleBuildLease } from './bundle-build.ts'
239
- import { NpmPackageError, type NpmReader, type NpmVersionDocument, type NpmVersionStore, VERSION_KEPT_MS, canReadPrivateNpm, npmFileRows, npmPublishTime, npmScopesCount, npmTarballFilename, readNpmVersion, readNpmVersions, readTogether } from './npm-packages.ts'
242
+ import { NpmPackageError, type NpmReader, type NpmVersionDocument, type NpmVersionStore, VERSION_KEPT_MS, canReadPrivateNpm, npmExecutablePaths, npmFileRows, npmPublishTime, npmScopesCount, npmTarballFilename, readNpmVersion, readNpmVersions, readTogether } from './npm-packages.ts'
240
243
  import { loadNpmFiles, loadNpmPackageBody, loadNpmTarball } from './npm-loads.ts'
241
244
  import { type ReadPatch, type RequestedPatch, foundPatch, keptPatch, patchedFiles, readPatch, requestedPatch, withPatchFiles } from './npm-patch.ts'
242
245
  import { type RepositoryCodeKept, loadRepositoryCodeBody, repositoryCodeFits, repositoryCodeKept } from './repository-code.ts'
@@ -269,7 +272,7 @@ import { STAMP_READ, repositoryStamp } from './repository-stamp.ts'
269
272
  import { ISSUES_LIST_READ_VERSION, type IssueList, type Listed, PULLS_READ_VERSION, type PullList, pullsReadTo, readIssues, readPulls } from './repository-pulls.ts'
270
273
  import { AGENT_MARKS_READ } from './app-agents.ts'
271
274
  import { releaseCommits } from './release-commits.ts'
272
- import { computeBundleDiff } from '../common/bundle-compare-diff.js'
275
+ import { bundleFileMeta, computeBundleDiff } from '../common/bundle-compare-diff.js'
273
276
  import type { ReviewChange, ReviewContext, ReviewInput, ReviewedTarballs } from './dependency-reviews.ts'
274
277
  import { allowedReviewVerdicts, isReviewableFile, npmReviewVerdictLimit, npmTakenDown } from '../common/dependency-reviews.js'
275
278
  import { type NpmAdvisoryOptions, npmAdvisories, npmCommitTags, npmDownloads, npmGithubStats, npmKnown, npmLatestRepo, npmSocketReport } from './npm-insights.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 }))
@@ -3658,11 +3697,12 @@ function scanProgress(deps: ManagedHttpDeps, key: string, scan: string | null) {
3658
3697
  // GitHub (dependabot-access.ts); and its GitHub Actions, the references they
3659
3698
  // make resolved with the admin's own GitHub token (github-actions.ts); and
3660
3699
  // 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.
3700
+ // dependency review has them built (riskStasis). Read by an admin, or by a
3701
+ // manager of the team it names (readRiskSession), each alike, with their
3702
+ // own access. The reader leaving, losing what let them read it or the
3703
+ // server shutting down stops it.
3664
3704
  async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
3665
- const s = await readAdminSession(res, deps, cookie, { handed: true })
3705
+ const s = await readRiskSession(res, deps, cookie, query, { handed: true })
3666
3706
  if (!s) return
3667
3707
  const repos = await riskRepositories(deps.db, query)
3668
3708
  if (!repos) {
@@ -3766,7 +3806,8 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3766
3806
  await sendLines(res, lines, async () => {
3767
3807
  if (deps.isShuttingDown()) return false
3768
3808
  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
3809
+ const current = await readSession(deps.config, deps.db, cookie, Date.now())
3810
+ if (current?.user.id !== s.user.id || !await mayReadRisk(deps.db, current.user, query)) return false
3770
3811
  checked = Date.now()
3771
3812
  return true
3772
3813
  })
@@ -5327,10 +5368,12 @@ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps:
5327
5368
  }
5328
5369
  if (change?.action === 'publish' || change?.action === 'save') {
5329
5370
  const patchOf = [patchRead, basePatchRead]
5330
- const maps = files.map((list, at) => new Map<string, unknown>(npmFileRows(patchOf[at] ? patchedFiles(list, patchOf[at].files) : list)
5331
- .map(([path, size, text, digest]) => [path, text ?? { format: 'digest', size, digest }])))
5371
+ const lists = files.map((list, at) => patchOf[at] ? patchedFiles(list, patchOf[at].files) : list)
5372
+ const maps = lists.map(list => new Map<string, unknown>(npmFileRows(list).map(([path, size, text, digest]) => [path, text ?? { format: 'digest', size, digest }])))
5373
+ // A file made executable or not is one changed, as Compare shows it.
5374
+ const modes = lists.map(list => bundleFileMeta({ npmExecutable: new Set(npmExecutablePaths(list)) }))
5332
5375
  const after = maps[0]!, before = maps[1] ?? new Map<string, unknown>()
5333
- const diff = computeBundleDiff(before, after, () => '.')
5376
+ const diff = computeBundleDiff(before, after, () => '.', undefined, [modes[1] ?? null, modes[0]!])
5334
5377
  const changed: { path: string; basePath?: string }[] = [...diff.files.onlyBase, ...diff.files.onlyOther, ...diff.files.changed]
5335
5378
  const reviewable = (file: typeof changed[number]) => isReviewableFile(before.get(file.basePath ?? file.path), after.get(file.path))
5336
5379
  const reviewedPath = change.action === 'save' ? change.entry.file : null
@@ -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 {
@@ -10,7 +10,7 @@ import { CompressionError, decompress } from '@preventive/archive/compression.js
10
10
  import { encodeBrotli } from './brotli.ts'
11
11
  import { keptBriefly } from './kept-briefly.ts'
12
12
  import { MAX_NPM_PACKAGE_BYTES, MAX_NPM_PACKAGE_FILES, NPM_REGISTRY, NpmPackageError, type NpmPackageFile, type NpmVersionDocument, type TarReading,
13
- askUpstream, npmFileRows, npmPublishTime, npmToken, readNpmTar } from './npm-packages.ts'
13
+ askUpstream, npmExecutablePaths, npmFileRows, npmPublishTime, npmToken, readNpmTar } from './npm-packages.ts'
14
14
  import { keepFile, readKeptFile, upstreamCachePath } from './upstream-cache.ts'
15
15
 
16
16
  // The tar stream a package's files may come in, headers and padding included.
@@ -253,7 +253,7 @@ export function loadNpmPackageBody(doc: NpmVersionDocument, known: () => object
253
253
  const { files, tarballSize } = await unpackedOf(doc)
254
254
  return encodeBrotli(Buffer.from(JSON.stringify({
255
255
  name: doc.name, version: doc.version, private: doc.private, integrity: doc.dist.integrity, tarballSize,
256
- published: await published(), manifest: doc.manifest, files: npmFileRows(files), known: known(),
256
+ published: await published(), manifest: doc.manifest, files: npmFileRows(files), executable: npmExecutablePaths(files), known: known(),
257
257
  })))
258
258
  })
259
259
  }
@@ -381,15 +381,20 @@ export function npmPublishTime(doc: Pick<NpmVersionDocument, 'name' | 'version'
381
381
  }
382
382
 
383
383
  // A symlink's `link` is its target as stored, its bytes that target's: no text, whatever they spell.
384
- export interface NpmPackageFile { path: string; bytes: Uint8Array; link?: string }
384
+ // One with an execute bit is `executable`.
385
+ export interface NpmPackageFile { path: string; bytes: Uint8Array; link?: string; executable?: true }
386
+
387
+ // The paths of `files` that are executable, as the viewer gets them beside their rows.
388
+ export const npmExecutablePaths = (files: NpmPackageFile[]) => files.flatMap(file => file.executable ? [file.path] : [])
385
389
 
386
390
  // Paths in the order a package's files are read in (readNpmTar), and
387
391
  // Compare's: by their UTF-16 code units, as a plain sort orders them.
388
392
  export const pathOrder = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
389
393
 
390
394
  // How a tar stream is read (readNpmTar): how far its symlinks may climb above
391
- // it, and the entries, files and bytes it may hold, a package's unless given.
392
- 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 }
393
398
 
394
399
  // The regular files of a tar stream, by package path, as npm and pnpm install
395
400
  // them (risk's npmTarLayout): each name as stored past its first component,
@@ -402,18 +407,19 @@ export interface TarReading { symlinksAbove?: number; maxEntries?: number; maxFi
402
407
  // or not an installer installs it, a hard link as its target's bytes, a
403
408
  // symlink for where it points. Where
404
409
  // the files conflict (two that differ at one path, as under two top
405
- // 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`,
406
412
  // never read as one installer does. Directories and devices hold no file
407
413
  // content and are skipped.
408
414
  export function readNpmTar(tar: Uint8Array, { symlinksAbove = NPM_SYMLINKS_ABOVE, maxEntries = MAX_NPM_TAR_ENTRIES, maxFiles = MAX_NPM_PACKAGE_FILES,
409
- maxBytes = MAX_NPM_PACKAGE_BYTES }: TarReading = {}): NpmPackageFile[] {
415
+ maxBytes = MAX_NPM_PACKAGE_BYTES, foldPaths = true }: TarReading = {}): NpmPackageFile[] {
410
416
  let entries: Entry[]
411
417
  try { entries = unpack(tar, { maxEntries, symlinksAbove }) }
412
418
  catch (err) {
413
419
  if (err instanceof ArchiveError) throw err.limited ? new NpmPackageError(413, 'package-too-large') : new NpmPackageError(422, 'bad-tarball')
414
420
  throw err
415
421
  }
416
- 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) })
417
423
  return [...files].map(([path, file]) => ({ path, ...file })).toSorted((a, b) => pathOrder(a.path, b.path))
418
424
  }
419
425
 
@@ -0,0 +1,57 @@
1
+ // Paths as git writes them in a diff's headers (npm-patch.ts parsePatch):
2
+ // quoted as C writes a string where they need it, prefixed `a/` and `b/`.
3
+ import { Buffer } from 'node:buffer'
4
+ import { NpmPackageError } from './npm-packages.ts'
5
+
6
+ const unreadable = () => new NpmPackageError(422, 'patch-unreadable')
7
+
8
+ // A path as git writes it, unquoted where quoted (as C writes a string, its
9
+ // bytes past ASCII in octal); null where it is quoted otherwise.
10
+ const ESCAPES: Record<string, number> = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 }
11
+ export function unquoted(path: string): string | null {
12
+ if (!path.startsWith('"')) return path
13
+ const bytes: number[] = []
14
+ for (let at = 1; at < path.length; at++) {
15
+ const char = path[at]!
16
+ if (char === '"') return at === path.length - 1 ? new TextDecoder().decode(Uint8Array.from(bytes)) : null
17
+ if (char !== '\\') { bytes.push(...Buffer.from(char)); continue }
18
+ const next = path[++at] ?? ''
19
+ const octal = /^[0-3][0-7]{2}/u.exec(path.slice(at))?.[0]
20
+ if (octal) { bytes.push(Number.parseInt(octal, 8)); at += 2 }
21
+ else if (next in ESCAPES) bytes.push(ESCAPES[next]!)
22
+ else return null
23
+ }
24
+ return null
25
+ }
26
+
27
+ // A side's path in the package, as a `---` or `+++` line names it after its
28
+ // prefix (`a/` or `b/`), git's tab after one with a space in it left out;
29
+ // null for none (`/dev/null`).
30
+ export function sidePath(named: string, prefix: string): string | null {
31
+ const path = unquoted(named.endsWith('\t') ? named.slice(0, -1) : named)
32
+ if (path === '/dev/null') return null
33
+ if (path === null || !path.startsWith(prefix)) throw unreadable()
34
+ return path.slice(prefix.length)
35
+ }
36
+
37
+ // The paths a `diff --git` line names, where they are the same, as git
38
+ // writes them for a file neither renamed nor copied: `a/<path> b/<path>`.
39
+ export function gitPath(named: string): string | null {
40
+ if (named.startsWith('"')) {
41
+ const quoted = /^("(?:[^"\\]|\\.)*") ("(?:[^"\\]|\\.)*")$/u.exec(named)
42
+ const [a, b] = quoted ? [unquoted(quoted[1]!), unquoted(quoted[2]!)] : []
43
+ return a?.startsWith('a/') && b?.startsWith('b/') && a.slice(2) === b.slice(2) ? a.slice(2) : null
44
+ }
45
+ const length = (named.length - 5) / 2
46
+ const path = named.slice(2, 2 + length)
47
+ return Number.isInteger(length) && named.startsWith('a/') && named.slice(2 + length) === ` b/${path}` ? path : null
48
+ }
49
+
50
+ // Whether a `diff --git` line's paths (`rest`, past `diff --git `) are
51
+ // `before` and `after`, as git writes them, either quoted or not.
52
+ export function namesBoth(rest: string, before: string, after: string): boolean {
53
+ const first = rest.startsWith('"') ? /^"(?:[^"\\]|\\.)*"/u.exec(rest)?.[0] : `a/${before}`
54
+ if (first === undefined || !rest.startsWith(`${first} `)) return false
55
+ const second = rest.slice(first.length + 1)
56
+ return unquoted(first) === `a/${before}` && unquoted(second) === `b/${after}`
57
+ }