@preventive/triage 1.0.0-alpha.66 → 1.0.0-alpha.67

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 (64) hide show
  1. package/common/bundle-imports.js +20 -0
  2. package/common/bundle-metadata.js +1 -1
  3. package/common/bundle-reasons.d.ts +4 -0
  4. package/common/bundle-reasons.js +38 -1
  5. package/common/bundle-sources.d.ts +1 -0
  6. package/common/bundle-sources.js +22 -0
  7. package/common/managed/npm-packages.js +3 -3
  8. package/common/managed/routes.js +23 -11
  9. package/common/managed/stasis-config.ts +7 -0
  10. package/out/activity.js +4 -4
  11. package/out/chunk-5F5FPI75.js +3 -0
  12. package/out/chunk-6ATPGDDI.js +1 -0
  13. package/out/chunk-6YGH7BJG.js +42 -0
  14. package/out/{chunk-OVGR4D3M.js → chunk-A5A3LEMV.js} +1 -1
  15. package/out/chunk-CGRIZ5M5.js +1 -0
  16. package/out/chunk-FUHRMY7R.js +247 -0
  17. package/out/{chunk-J2FWBXFV.js → chunk-LBJVV6UB.js} +1 -1
  18. package/out/chunk-LDO42LAC.js +1 -0
  19. package/out/{chunk-24AKGEH3.js → chunk-NB4JBTKK.js} +1 -1
  20. package/out/{chunk-IZ6MYRYB.js → chunk-R3WUYD4F.js} +1 -1
  21. package/out/chunk-U5C2TNNQ.js +52 -0
  22. package/out/chunk-VG5RH6KN.js +2 -0
  23. package/out/{chunk-Z6VEV2QL.js → chunk-VR3NRE5V.js} +1 -1
  24. package/out/chunk-WFDXHPT2.js +12 -0
  25. package/out/client-managed-import.js +2 -2
  26. package/out/client-managed.js +19 -19
  27. package/out/compare.js +12 -12
  28. package/out/dialogs.js +38 -38
  29. package/out/graph.js +8 -8
  30. package/out/index.html +9 -9
  31. package/out/scan.js +2 -2
  32. package/out/view.css +1 -1
  33. package/out/view.js +15 -15
  34. package/package.json +11 -8
  35. package/server-managed/activity.ts +21 -12
  36. package/server-managed/bundle-build-diagnostics.d.ts +1 -1
  37. package/server-managed/bundle-build-worker.js +84 -15
  38. package/server-managed/bundle-build.ts +95 -19
  39. package/server-managed/bundle-cache.ts +28 -6
  40. package/server-managed/bundle-dependency-reviews.ts +38 -22
  41. package/server-managed/commit-lockfiles.ts +2 -1
  42. package/server-managed/db-neon.ts +1 -1
  43. package/server-managed/dependency-review-comments.ts +31 -12
  44. package/server-managed/http.ts +127 -59
  45. package/server-managed/locked-packages.ts +34 -14
  46. package/server-managed/lockfile-scope.ts +10 -1
  47. package/server-managed/npm-kept.ts +10 -0
  48. package/server-managed/npm-patch.ts +127 -50
  49. package/server-managed/public-workspace.ts +3 -2
  50. package/server-managed/pull-dependencies.ts +55 -37
  51. package/server-managed/pull-dependency-reviews.ts +15 -11
  52. package/server-managed/report-sources.ts +6 -3
  53. package/server-managed/repository-issues.ts +14 -11
  54. package/server-managed/stasis-dependencies.ts +153 -0
  55. package/out/chunk-65PLAG3I.js +0 -12
  56. package/out/chunk-DCBXCBLL.js +0 -52
  57. package/out/chunk-F3UI65ZI.js +0 -42
  58. package/out/chunk-FAG6E5RC.js +0 -3
  59. package/out/chunk-OBZWBTZL.js +0 -247
  60. package/out/chunk-PTFQKLKO.js +0 -1
  61. package/out/chunk-QVKFY4FA.js +0 -1
  62. package/out/chunk-SYXT3SFP.js +0 -2
  63. package/out/chunk-WL3SPQB4.js +0 -1
  64. /package/out/{chunk-WCPJDAYA.js → chunk-D6NVKGGG.js} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.66",
3
+ "version": "1.0.0-alpha.67",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -218,6 +218,7 @@
218
218
  "server-managed/sql-postgres.ts",
219
219
  "server-managed/sql.ts",
220
220
  "server-managed/stasis-config.ts",
221
+ "server-managed/stasis-dependencies.ts",
221
222
  "server-managed/static.ts",
222
223
  "server-managed/storage.ts",
223
224
  "server-managed/storage-command.ts",
@@ -260,6 +261,7 @@
260
261
  "common/bundle-compare-diff.d.ts",
261
262
  "common/bundle-compare-inputs.d.ts",
262
263
  "common/bundle-compare-inputs.js",
264
+ "common/bundle-imports.js",
263
265
  "common/bundle-metadata.d.ts",
264
266
  "common/bundle-pkg-of.d.ts",
265
267
  "common/bundle-pkg-of.js",
@@ -312,6 +314,7 @@
312
314
  "common/managed/routes.d.ts",
313
315
  "common/managed/routes.js",
314
316
  "common/managed/scan-models.ts",
317
+ "common/managed/stasis-config.ts",
315
318
  "common/managed/team-app.js",
316
319
  "common/managed/team-app.d.ts",
317
320
  "common/managed/team-filters.js",
@@ -412,23 +415,23 @@
412
415
  "@noble/ciphers": "^2.4.0",
413
416
  "@preventive/terminal": "2.0.0-beta.3",
414
417
  "@rray/frontend": "^1.0.0",
415
- "@stylistic/stylelint-plugin": "^6.0.0",
418
+ "@stylistic/stylelint-plugin": "^6.0.1",
416
419
  "@types/node": "^26.6.6",
417
420
  "@types/ws": "^8.18.2",
418
- "@vercel/functions": "^3.10.6",
421
+ "@vercel/functions": "^3.11.0",
419
422
  "brotli": "^1.3.3",
420
423
  "esbuild": "^0.28.2",
421
424
  "lit": "^3.3.3",
422
425
  "minify-html-literals": "^1.3.5",
423
- "oxlint": "^1.91.0",
426
+ "oxlint": "^1.92.0",
424
427
  "prismjs": "^1.30.0",
425
428
  "stylelint": "^18.0.0",
426
429
  "stylelint-config-recommended": "^19.0.0",
427
430
  "typescript": "^7.0.2"
428
431
  },
429
432
  "dependencies": {
430
- "@exodus/stasis": "1.0.0-rc.4",
431
- "@exodus/stasis-core": "1.0.0-rc.4",
433
+ "@exodus/stasis": "1.0.0-rc.6",
434
+ "@exodus/stasis-core": "1.0.0-rc.6",
432
435
  "@preventive/archive": "^1.4.1",
433
436
  "@preventive/compare": "^1.2.13",
434
437
  "@preventive/diff": "^1.1.1",
@@ -440,7 +443,7 @@
440
443
  "css-tree": "^3.2.1",
441
444
  "oxc-minify": "^0.157.0",
442
445
  "oxc-parser": "^0.152.0",
443
- "oxfmt": "^0.76.0",
446
+ "oxfmt": "^0.77.0",
444
447
  "semver": "^7.8.6",
445
448
  "ws": "^8.22.1"
446
449
  },
@@ -460,5 +463,5 @@
460
463
  "optional": true
461
464
  }
462
465
  },
463
- "packageManager": "pnpm@12.17.0+sha512.b8d223ebec04b580a89ed206daa71d1bccb6a1ee1d52efa95cc3b0db75271561df8f0d8e2c43add39c5ec08018af7a8a95108e7090f95a29f88727b7a40fd53d"
466
+ "packageManager": "pnpm@12.18.0+sha512.9d7882d5dc82147ecfc4e062aa34834e0ad0296710a1837a1115ae012127d36b7109e321ac1598a1dd0a65597681b1e99917e12ed0d749eae91187943363beb3"
464
467
  }
@@ -26,8 +26,11 @@ export interface ActivityContext {
26
26
  repo: string | null
27
27
  }
28
28
 
29
+ // `actor` is the login of who acted as it is now, else the one recorded;
30
+ // `actorId` the user they are (null for a legacy login), and `actorName` the
31
+ // name they chose to show, as it is now.
29
32
  export type ActivityEntry = {
30
- id: string; kind: string; actor: string | null; action: string
33
+ id: string; kind: string; actor: string | null; actorId: string | null; actorName: string | null; action: string
31
34
  repo: string | null; reportId: string | null; report: string | null
32
35
  finding: string | null; at: number
33
36
  }
@@ -48,7 +51,8 @@ export interface ActivityQuery {
48
51
 
49
52
  export interface ActivityFilters {
50
53
  repos: string[]
51
- users: { id: string; login: string; detail: string | null }[]
54
+ // `id` is the actor's filter key; `userId` the user, null for a legacy login.
55
+ users: { id: string; userId: string | null; login: string; name: string | null; detail: string | null }[]
52
56
  }
53
57
 
54
58
  export interface ActivityStore {
@@ -175,9 +179,10 @@ export function activityMethods(db: ManagedSql): ActivityStore {
175
179
  }
176
180
  const history = rows.map(({ total: _total, ...entry }) => entry)
177
181
  const filters: ActivityFilters = { repos: [], users: [] }
178
- for (const row of (await stmts.filters.all(scope)) as { facet: string; id: string; login: string; detail: string | null }[]) {
182
+ type FacetRow = { facet: string; id: string; userId: string | null; login: string; name: string | null; detail: string | null }
183
+ for (const row of (await stmts.filters.all(scope)) as FacetRow[]) {
179
184
  if (row.facet === 'repo') filters.repos.push(row.id)
180
- else filters.users.push({ id: row.id, login: row.login, detail: row.detail })
185
+ else filters.users.push({ id: row.id, userId: row.userId, login: row.login, name: row.name, detail: row.detail })
181
186
  }
182
187
  return { history, total, page: currentPage, limit, filters }
183
188
  },
@@ -186,14 +191,17 @@ export function activityMethods(db: ManagedSql): ActivityStore {
186
191
 
187
192
  // Both rows and selector choices come from the authorized source. Keep legacy
188
193
  // login-only actors separate: a historical login is not proof of user identity.
194
+ // A user shows by their login and name as they are now, as in the selector.
189
195
  function activityStatements(db: ManagedSql, source: string) {
190
196
  const activity = `WITH events AS (${source}), activity AS (
191
- SELECT events.*, COALESCE('user:' || actorId, 'legacy:' || actor) AS actorKey FROM events
197
+ SELECT e.id, e.kind, COALESCE(u.login, e.actor) AS actor, e.actorId, u.name AS actorName, e.action,
198
+ e.repo, e.reportId, e.report, e.finding, e.at, COALESCE('user:' || e.actorId, 'legacy:' || e.actor) AS actorKey
199
+ FROM events e LEFT JOIN managed_user u ON u.id = e.actorId
192
200
  )`
193
- const filtered = `${activity} SELECT id, kind, actor, action, repo, reportId, report, finding, at FROM activity
201
+ const filtered = `${activity} SELECT id, kind, actor, actorId, actorName, action, repo, reportId, report, finding, at FROM activity
194
202
  WHERE (:kind = 'all' OR kind = :kind)
195
203
  AND (:repo = '' OR repo = :repo) AND (:actor = '' OR actorKey = :actor)
196
- AND (:query = '' OR instr(lower(coalesce(actor, '') || ' ' || action || ' ' ||
204
+ AND (:query = '' OR instr(lower(coalesce(actor, '') || ' ' || coalesce(actorName, '') || ' ' || action || ' ' ||
197
205
  coalesce(repo, '') || ' ' || coalesce(report, '') || ' ' || coalesce(finding, '')), lower(:query)) > 0)`
198
206
  // A page's rows each carry the total, so the source is read once for both;
199
207
  // the selector choices, repositories then users, once between them.
@@ -202,13 +210,14 @@ function activityStatements(db: ManagedSql, source: string) {
202
210
  rows: db.prepare(`SELECT filtered.*, count(*) OVER () AS total FROM (${filtered}) AS filtered ORDER BY at DESC,
203
211
  CASE WHEN kind = 'triage' THEN CAST(substr(id, instr(id, ':') + 1) AS INTEGER) ELSE 0 END DESC,
204
212
  id DESC LIMIT :limit OFFSET :offset`),
205
- filters: db.prepare(`${activity} SELECT 'repo' AS facet, repo AS id, repo AS login, NULL AS detail, repo AS sort, '' AS tiebreak
213
+ filters: db.prepare(`${activity} SELECT 'repo' AS facet, repo AS id, NULL AS userId, repo AS login, NULL AS name, NULL AS detail,
214
+ repo AS sort, '' AS tiebreak
206
215
  FROM (SELECT DISTINCT repo FROM activity WHERE repo IS NOT NULL AND repo <> '') AS repos
207
- UNION ALL SELECT 'user' AS facet, a.actorKey AS id, COALESCE(u.login, a.actor, a.actorId) AS login,
208
- CASE WHEN a.actorId IS NULL THEN 'Legacy actor' ELSE NULL END AS detail, COALESCE(u.login, a.actor, a.actorId) AS sort, a.actorKey AS tiebreak FROM (
209
- SELECT actorKey, actorId, actor, ROW_NUMBER() OVER (PARTITION BY actorKey ORDER BY at DESC, id DESC) AS position
216
+ UNION ALL SELECT 'user' AS facet, a.actorKey AS id, a.actorId AS userId, COALESCE(a.actor, a.actorId) AS login, a.actorName AS name,
217
+ CASE WHEN a.actorId IS NULL THEN 'Legacy actor' ELSE NULL END AS detail, COALESCE(a.actor, a.actorId) AS sort, a.actorKey AS tiebreak FROM (
218
+ SELECT actorKey, actorId, actor, actorName, ROW_NUMBER() OVER (PARTITION BY actorKey ORDER BY at DESC, id DESC) AS position
210
219
  FROM activity WHERE actorKey IS NOT NULL AND actorKey <> 'legacy:'
211
- ) a LEFT JOIN managed_user u ON u.id = a.actorId WHERE a.position = 1
220
+ ) a WHERE a.position = 1
212
221
  ORDER BY facet, sort, tiebreak`),
213
222
  }
214
223
  }
@@ -7,4 +7,4 @@ export interface BundleBuildDiagnostic {
7
7
  cause?: BundleBuildDiagnostic
8
8
  }
9
9
  export function bundleBuildDiagnostic(error: unknown, token: string | null): BundleBuildDiagnostic
10
- export type BundleBuildStage = 'worker-start' | 'build' | 'scope' | 'serialize' | 'compress'
10
+ export type BundleBuildStage = 'worker-start' | 'build' | 'scope' | 'serialize' | 'compress' | 'lockfile'
@@ -2,8 +2,10 @@ import { parentPort, workerData } from 'node:worker_threads'
2
2
  import { Buffer } from 'node:buffer'
3
3
  import { posix } from 'node:path'
4
4
  import { brotliCompressSync } from 'node:zlib'
5
+ import { isEvidenceFile } from '@exodus/stasis/audit-corrections'
5
6
  import { buildGitHubBundle, setCacheDir } from '@exodus/stasis/vfs-bundle'
6
7
  import { brotliOptions } from '@exodus/stasis-core/brotli'
8
+ import { LOCK_FILE, dependencyEcosystem, integrityHex } from '@exodus/stasis-core/util'
7
9
  import { HttpError, createClient } from '@preventive/upstream/github.js'
8
10
  import { githubBundleFilename } from './bundle-build.ts'
9
11
  import { bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
@@ -104,11 +106,10 @@ async function packageName(input, github, project, bundle, client) {
104
106
  return typeof name === 'string' ? name : null
105
107
  }
106
108
 
107
- // `note` is told what the build log keeps of a build beside its stages: the
108
- // directory Stasis builds from (`project`), and each tree it downloads of the
109
- // repo (`download`), the whole repo's or a directory's, and its bytes.
110
- export async function buildStasisBundle({ input, github, token, maxBytes, scopes, cacheDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
111
- const allowed = path => scopes.some(scope => !scope || path === scope || path.startsWith(scope + '/'))
109
+ // `client` as a build reads the repo with it: each directory's listing read
110
+ // once, and each tree it downloads of the repo noted (`download`), the whole
111
+ // repo's or a directory's, and its bytes.
112
+ function buildClientOf(client, note) {
112
113
  // Reuse these immutable listings when Stasis discovers the lockfile root.
113
114
  const listings = new Map()
114
115
  const downloaded = (tree, read) => async options => {
@@ -116,12 +117,20 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
116
117
  note('download', { tree, bytes: bytes.length })
117
118
  return bytes
118
119
  }
119
- const buildClient = { ...client, listRepoDir(options) {
120
+ return { ...client, listRepoDir(options) {
120
121
  const key = JSON.stringify([options.repo, options.sha, options.directory ?? ''])
121
122
  if (!listings.has(key)) listings.set(key, client.listRepoDir(options))
122
123
  return listings.get(key)
123
124
  }, getRepoTarball: downloaded('repo', options => client.getRepoTarball(options)),
124
125
  getRepoTreeTarball: downloaded('directory', options => client.getRepoTreeTarball(options)) }
126
+ }
127
+
128
+ // `note` is told what the build log keeps of a build beside its stages: the
129
+ // directory Stasis builds from (`project`), and each tree it downloads of the
130
+ // repo (`download`, buildClientOf).
131
+ export async function buildStasisBundle({ input, github, token, maxBytes, scopes, cacheDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
132
+ const allowed = path => scopes.some(scope => !scope || path === scope || path.startsWith(scope + '/'))
133
+ const buildClient = buildClientOf(client, note)
125
134
  // Upstream's disk cache keeps the npm tarballs and version documents, and
126
135
  // the repo's tree, in `cacheDir`; without one (Vercel), nothing is kept on
127
136
  // disk. This fresh worker inherits no application credentials but NPM_TOKEN.
@@ -144,8 +153,10 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
144
153
  const { packageManager, ...options } = input.options
145
154
  const named = packageManager !== undefined && !namesLockfiles(await configText(project) ?? '{}')
146
155
  note('project', { project, configured: configured !== null, ...(named && { packageManager }) })
156
+ // The branch the commit was picked by, where it was, Stasis asks first of
157
+ // whether the commit is the repo's own (bundle-build.ts).
147
158
  const { bundle } = await buildGitHubBundle({
148
- github, sha: input.commit, directory: project || undefined,
159
+ github, sha: input.commit, ...(input.branch !== undefined && { branch: input.branch }), directory: project || undefined,
149
160
  entries: input.entries.map(entry => posix.relative(project || '.', entry)),
150
161
  ...options, ...(named && { packageManager }), client: buildClient, ...(cacheDir === null && { cache: false }),
151
162
  })
@@ -159,6 +170,8 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
159
170
  // module too large for V8 to hold as one is too large too.
160
171
  let serialized
161
172
  try { serialized = bundle.serializedBytes() } catch (error) {
173
+ // A failure's code, as buildErrorCode reads it, not a value of the wrong type.
174
+ // oxlint-disable-next-line unicorn/prefer-type-error
162
175
  if (error instanceof RangeError) throw new Error('too-large', { cause: error })
163
176
  throw error
164
177
  }
@@ -170,13 +183,54 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
170
183
  return { bytes, directory, filename: githubBundleFilename(github, project, input.commit, name) }
171
184
  }
172
185
 
186
+ // The npm package versions a Stasis lockfile holds code of (an evidence
187
+ // file, by Stasis's audit rule), each once as it was installed: with its
188
+ // tarball's integrity and, patched, pnpm's hash of its patch (a sha256 in
189
+ // hex, as pnpm's lockfile names it), where the lockfile attests them.
190
+ export function lockfileDependencies(lockfile) {
191
+ const found = new Map()
192
+ for (const [dir, info] of lockfile.modules) {
193
+ const { name, version } = info
194
+ if (dir === '.' || dependencyEcosystem(dir, info.ecosystem) !== 'npm' || typeof name !== 'string' || !name || typeof version !== 'string' || !version) continue
195
+ if (!Object.keys(info.files).some(file => isEvidenceFile(name, version, file, 'npm'))) continue
196
+ const patch = typeof info.patch?.integrity === 'string' ? integrityHex(info.patch.integrity) : undefined
197
+ const one = { name, version, ...(typeof info.integrity === 'string' && { integrity: info.integrity }), ...(patch && { patch }) }
198
+ found.set(`${name}\0${version}\0${one.integrity ?? ''}\0${patch ?? ''}`, one)
199
+ }
200
+ return [...found].toSorted(([a], [b]) => a < b ? -1 : 1).map(([, one]) => one)
201
+ }
202
+
203
+ // What the stasis.config.json at `input.config` has Stasis reach at
204
+ // `input.commit`, for the repository's dependency review
205
+ // (stasis-dependencies.ts): the npm versions of the lockfile it builds in
206
+ // its directory, as `stasis github-bundle --lockfile-only` does, no bundle
207
+ // serialized; none of a commit with no file there.
208
+ export async function buildStasisLockfile({ input, github, token, cacheDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
209
+ const buildClient = buildClientOf(client, note)
210
+ setCacheDir(cacheDir ?? false)
211
+ progress('build')
212
+ const directory = parentOf(input.config)
213
+ const configText = configReader(input, github, buildClient)
214
+ if (await configText(directory) === null) return []
215
+ // One Stasis can't tell the entries of is config-invalid before anything is fetched.
216
+ await directoryConfig(configText, directory)
217
+ note('project', { project: directory, configured: true })
218
+ const { lockfile } = await buildGitHubBundle({ github, sha: input.commit, ...(input.branch !== undefined && { branch: input.branch }), directory: directory || undefined, lockfile: LOCK_FILE, client: buildClient,
219
+ ...(cacheDir === null && { cache: false }) })
220
+ progress('lockfile')
221
+ if (!lockfile) throw new Error('Stasis built no lockfile of these entries')
222
+ return lockfileDependencies(lockfile)
223
+ }
224
+
173
225
  // The code a failed build answers with. Never upstream bodies or paths outside
174
226
  // the caller's grants: those stay in the diagnostic. A missing or ambiguous
175
227
  // lockfile, or the named one missing, is the lockfile's. Stasis refuses a
176
228
  // stasis.config.json entry setting an option that runs a program, whatever
177
229
  // is given (nothing of the repo runs); a bundle holding a path or package its
178
230
  // allowedPaths, disallowedPaths, allowedModules or disallowedModules refuses,
179
- // the config's or an entry's, is the policy's; one it can't read, build with
231
+ // or its excludeModules excludes (an entry in such a package among them), the
232
+ // config's or an entry's, is the policy's, as is one broken at load by
233
+ // imports excludeModules excludes alone; one it can't read, build with
180
234
  // its options, or lay out the lockfiles it names of, is the config's. A build
181
235
  // the repository's stasis.lock.json disagrees with, or that its lock mode
182
236
  // holds to one that isn't there, is the stasis.lock.json's. A commit Stasis
@@ -188,13 +242,23 @@ export function buildErrorCode(error, message) {
188
242
  if (error instanceof HttpError) return error.status === 429 ? 'github-rate-limited' : 'github-build-failed'
189
243
  if (/, which runs .+, and nothing of the project runs here$/u.test(message)) return 'config-runs-code'
190
244
  if (message.endsWith(': bundle either the entries it names or others, not both')) return 'config-mixed'
191
- if (/\bstasis\.config\.json(?:: entries .*?)?: (?:allowed|disallowed)(?:Paths|Modules) (?:refuses|does not allow|allows none of) /u.test(message)) return 'config-policy'
245
+ if (/\bstasis\.config\.json(?:: entries .*?)?: (?:(?:allowed|disallowed)(?:Paths|Modules) (?:refuses|does not allow|allows none of)|excludeModules excludes) /u.test(message)) return 'config-policy'
246
+ if (brokenByExclusion(message)) return 'config-policy'
192
247
  if (/\bstasis\.config\.json(?: is not valid JSON|: |'s lockfiles )/u.test(message)) return 'config-invalid'
193
248
  if (/\bstasis\.lock\.json(?::| isn't there,| \(lock = )/u.test(message)) return 'stasis-lock'
194
249
  if (/ is in the history of no branch or tag of | is at no tag or branch head of .+ nor in its default branch's history/u.test(message)) return 'commit-not-own'
195
250
  return /no packageManager given|lockfile installs|no (?:pnpm-lock\.yaml|yarn\.lock|package-lock\.json|soldeer\.lock) found in /u.test(message) ? 'build-lockfile' : 'build-failed'
196
251
  }
197
252
 
253
+ // Whether Stasis finds a JS bundle broken at load by what excludeModules
254
+ // leaves out alone: each of what it lists (ten at most, none cut short past
255
+ // them) an import unresolved for that reason, which it gives first.
256
+ function brokenByExclusion(message) {
257
+ const [head, ...lines] = message.split('\n')
258
+ return /JS bundle would be broken at load time(?: \(.*\))?:$/u.test(head) && lines.length > 0
259
+ && lines.every(line => /^ {2}unresolved .* \(excluded by excludeModules[;)]/u.test(line))
260
+ }
261
+
198
262
  // The status a failed build answers with, by its code: 422 for any other.
199
263
  const FAILED_STATUS = new Map([['too-large', 413], ['build-scope', 403], ['bad-conditions', 400]])
200
264
 
@@ -221,13 +285,18 @@ if (parentPort && workerData?.type === 'managed-bundle-build') {
221
285
  }
222
286
  const reporting = setInterval(() => send({ type: 'memory', memory: memoryOf() }), MEMORY_EVERY_MS)
223
287
  reporting.unref()
288
+ const progress = stage => send({ type: 'progress', stage, memory: memoryOf() })
289
+ const note = (event, details) => send({ type: 'note', event, details })
224
290
  try {
225
- const built = await buildStasisBundle(workerData, undefined, stage => send({ type: 'progress', stage, memory: memoryOf() }),
226
- (event, details) => send({ type: 'note', event, details }))
227
- // The bytes handed over rather than copied, where they alone fill their
228
- // buffer (a small one may share Node's pool, which can't be moved).
229
- const { bytes } = built
230
- send(built, bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? [bytes.buffer] : [])
291
+ // A lockfile's dependencies in place of a bundle, where they are asked for (`lockfileOnly`).
292
+ if (workerData.lockfileOnly) send({ dependencies: await buildStasisLockfile(workerData, undefined, progress, note) })
293
+ else {
294
+ const built = await buildStasisBundle(workerData, undefined, progress, note)
295
+ // The bytes handed over rather than copied, where they alone fill their
296
+ // buffer (a small one may share Node's pool, which can't be moved).
297
+ const { bytes } = built
298
+ send(built, bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? [bytes.buffer] : [])
299
+ }
231
300
  } catch (error) {
232
301
  const diagnostic = bundleBuildDiagnostic(error, workerData.token)
233
302
  const code = buildErrorCode(error, diagnostic.message)
@@ -23,6 +23,19 @@ interface BundleBuildInput {
23
23
  // conditions, and for entries given none, which stasis.config.json must
24
24
  // then list (the build checks: bundle-build-worker.js).
25
25
  conditions: BundleBuildConditions | null
26
+ // The branch the commit was picked by, where it was: Stasis asks it first
27
+ // when it holds the commit to the repo's own history, which GitHub's compare
28
+ // tells of it, so nothing is taken on trust (one the commit isn't of is
29
+ // looked past). Without it, Stasis lists the repo's tags and branches and
30
+ // compares up to 100 of those.
31
+ branch?: string
32
+ }
33
+
34
+ // A name git takes for a branch (git check-ref-format --branch), at most
35
+ // GitHub's length for one.
36
+ export function branchName(value: unknown): value is string {
37
+ return typeof value === 'string' && value.length > 0 && value.length <= 255
38
+ && !/[\p{Cc}\s~^:?*[\\]|\.\.|@\{|\/\/|^-|^\/|\/$|\.$|^@$|(?:^|\/)\.|\.lock(?:\/|$)/u.test(value)
26
39
  }
27
40
 
28
41
  function path(value: unknown): value is string {
@@ -40,10 +53,11 @@ export function buildableEntry(value: unknown): value is string {
40
53
  export function parseBundleBuild(value: unknown): BundleBuildInput {
41
54
  const fail = (code = 'bad-request'): never => { throw new BundleBuildError(400, code) }
42
55
  if (value == null || typeof value !== 'object' || Array.isArray(value)) return fail()
43
- const { repoId, commit, entries, conditions } = value as Record<string, unknown>
56
+ const { repoId, commit, entries, conditions, branch } = value as Record<string, unknown>
44
57
  if (typeof repoId !== 'number' || !Number.isSafeInteger(repoId) || repoId <= 0
45
58
  || typeof commit !== 'string' || !/^[a-f\d]{40}$/u.test(commit)
46
- || !Array.isArray(entries) || entries.length === 0 || entries.length > 100 || !entries.every(path)) return fail()
59
+ || !Array.isArray(entries) || entries.length === 0 || entries.length > 100 || !entries.every(path)
60
+ || (branch != null && !branchName(branch))) return fail()
47
61
  const selected = [...new Set(entries as string[])]
48
62
  const scripts = selected.every(isScript)
49
63
  if (!scripts && !selected.every(entry => entry.endsWith('.sol'))) return fail('unsupported-entries')
@@ -76,7 +90,7 @@ export function parseBundleBuild(value: unknown): BundleBuildInput {
76
90
  recorded = { preset: preset as BundleBuildConditions['preset'], conditions: [...new Set(names as string[])],
77
91
  platforms: options.platforms ?? [] }
78
92
  }
79
- return { repoId, commit, entries: selected, directory: parts.join('/'), options, conditions: recorded }
93
+ return { repoId, commit, entries: selected, directory: parts.join('/'), options, conditions: recorded, ...(branchName(branch) && { branch }) }
80
94
  }
81
95
 
82
96
  // A package name as a filename base: `@scope/name` as `scope-name`, or as
@@ -113,10 +127,29 @@ interface BuildRequest {
113
127
  // VERCEL_ENV alone.
114
128
  cacheDir: string | null
115
129
  }
130
+ // A version a Stasis lockfile holds, as the worker tells it in place of a
131
+ // bundle (bundle-build-worker.js buildStasisLockfile); and what it is asked
132
+ // to build one of, with the `branch` the commit is of, where its asker knows
133
+ // it, as a bundle's is (BundleBuildInput).
134
+ export interface StasisDependency { name: string; version: string; integrity?: string; patch?: string }
135
+ export interface LockfileInput { repoId: number; commit: string; config: string; branch?: string }
136
+ interface LockfileRequest { input: LockfileInput; github: string; token: string | null; cacheDir: string | null }
116
137
  // An extra per-process ceiling, one build at a time, its worker given the heap
117
138
  // buildHeapLimitMib sizes; admission must also hold the shared DB lease.
118
139
  const active = new Set<string>()
119
140
  const MAX_ACTIVE_BUILDS = 1
141
+ // The build running behind no request (buildRepositoryLockfile), which one
142
+ // asked for takes the slot and the lease of: told to yield
143
+ // (`build-yielded`), and gone once its lease is released.
144
+ let behind: { yield: () => void; gone: Promise<void> } | null = null
145
+ // Who builds behind no request, as `active` and the shared lease name it.
146
+ const LOCKFILE_BUILDER = 'dependency-review'
147
+ async function yielded(): Promise<void> {
148
+ const running = behind
149
+ if (!running) return
150
+ running.yield()
151
+ await running.gone
152
+ }
120
153
 
121
154
  // What a build's worker may take of the JS heap, in MiB: the memory the
122
155
  // process may use, its container's limit else the machine's, less
@@ -134,6 +167,9 @@ export function buildHeapLimitMib(memory = processMemory()): number {
134
167
  return Math.max(MIN_BUILD_HEAP_MIB, Math.floor(memory / 1024 ** 2) - RESERVED_MIB)
135
168
  }
136
169
 
170
+ // `work` under one of the deployment's leases, `userId`'s one at a time. One
171
+ // asked for first has this instance's build behind no request yield, and
172
+ // waits for its lease to be released, lest that hold a lease against it.
137
173
  export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId: string, signal: AbortSignal,
138
174
  work: (signal: AbortSignal) => Promise<T>): Promise<T> {
139
175
  signal.throwIfAborted()
@@ -143,6 +179,7 @@ export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId:
143
179
  const combined = AbortSignal.any([signal, timeout.signal])
144
180
  let claimed = false
145
181
  try {
182
+ if (userId !== LOCKFILE_BUILDER && behind) await yielded()
146
183
  claimed = await db.claimBundleBuildLease(userId, owner)
147
184
  if (!claimed) throw new BundleBuildError(429, 'build-busy')
148
185
  // Account for a slow/lost claim response or a suspended invocation before
@@ -164,10 +201,52 @@ export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId:
164
201
  // Parsing repositories and compressing bundles stays off the HTTP event loop.
165
202
  // Cap concurrent builds, terminate disconnected/timed-out work, and share no
166
203
  // credentials or mutable Stasis state between requests.
167
- export async function buildRepositoryBundle(userId: string, request: BuildRequest, signal: AbortSignal): Promise<BuiltBundle> {
168
- if (active.has(userId) || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
204
+ export function buildRepositoryBundle(userId: string, request: BuildRequest, signal: AbortSignal): Promise<BuiltBundle> {
205
+ const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, directory: request.input.directory, entryCount: request.input.entries.length }
206
+ return runBuild<BuiltBundle & { bytes: Uint8Array }, BuiltBundle>(userId, request, context, signal, message => {
207
+ // A view of the bytes the worker handed over, not a copy of them.
208
+ const { bytes } = message
209
+ return { value: { bytes: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), directory: message.directory, filename: message.filename }, logged: { byteSize: bytes.length } }
210
+ })
211
+ }
212
+
213
+ // A Stasis lockfile's dependencies in place of a bundle, for a repository's
214
+ // dependency review (stasis-dependencies.ts), built behind no request, under
215
+ // the deployment's lease as its one builder of them: in the same one slot,
216
+ // which it gives up to a build asked for, with its lease (`build-yielded`),
217
+ // and is refused while another holds (`build-busy`), to be built later.
218
+ export async function buildRepositoryLockfile(db: BundleBuildLeaseStore, request: LockfileRequest, signal: AbortSignal): Promise<StasisDependency[]> {
219
+ if (behind || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
220
+ const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, config: request.input.config, branch: request.input.branch, lockfileOnly: true }
221
+ const asked = { ...request, lockfileOnly: true }
222
+ const yielding = new AbortController()
223
+ let gone = () => {}
224
+ behind = { yield: () => yielding.abort(new BundleBuildError(429, 'build-yielded')), gone: new Promise(resolve => { gone = resolve }) }
225
+ try {
226
+ return await withBundleBuildLease(db, LOCKFILE_BUILDER, AbortSignal.any([signal, yielding.signal]), leased => runBuild<{ dependencies: StasisDependency[] }, StasisDependency[]>(
227
+ LOCKFILE_BUILDER, asked, context, leased, ({ dependencies }) => ({ value: dependencies, logged: { dependencies: dependencies.length } }), true))
228
+ } finally {
229
+ behind = null
230
+ gone()
231
+ }
232
+ }
233
+
234
+ // What a build's worker told last, by its type: its progress, memory or a
235
+ // note, its failure, else what it built.
236
+ type WorkerMessage<M> = M & { type?: string; stage?: BundleBuildStage; error?: string; status?: number; diagnostic?: BundleBuildDiagnostic
237
+ memory?: Record<string, number>; event?: string; details?: Record<string, unknown> }
238
+
239
+ // `request` built in a worker of its own, `owner`'s one build at a time, what
240
+ // it built told by `built` of its last message, with what its log keeps of
241
+ // it; `background`, behind no request.
242
+ async function runBuild<M, T>(owner: string, request: { token: string | null }, about: Record<string, unknown>, signal: AbortSignal,
243
+ built: (message: M) => { value: T; logged: Record<string, unknown> }, background = false): Promise<T> {
244
+ const { token } = request
245
+ // One asked for takes the slot of one running behind no request, where its lease didn't already.
246
+ if (!background && behind) await yielded()
247
+ if (active.has(owner) || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
169
248
  signal.throwIfAborted()
170
- active.add(userId)
249
+ active.add(owner)
171
250
  let worker: Worker | undefined
172
251
  let workerUrl: URL | undefined
173
252
  let stage: BundleBuildStage = 'worker-start'
@@ -175,8 +254,7 @@ export async function buildRepositoryBundle(userId: string, request: BuildReques
175
254
  const heapLimitMib = buildHeapLimitMib()
176
255
  // How this Node was built, as it decides what a heap holds the same objects in.
177
256
  const { v8_enable_pointer_compression: pointerCompression, v8_enable_sandbox: v8Sandbox } = process.config.variables as Record<string, unknown>
178
- const context = { buildId, repoId: request.input.repoId, github: request.github, commit: request.input.commit,
179
- directory: request.input.directory, entryCount: request.input.entries.length, node: process.version, v8: process.versions.v8, pointerCompression, v8Sandbox,
257
+ const context = { buildId, ...about, node: process.version, v8: process.versions.v8, pointerCompression, v8Sandbox,
180
258
  memoryMib: Math.round(processMemory() / 1024 ** 2), heapLimitMib }
181
259
  const log = (event: string, details: Record<string, unknown> = {}) => {
182
260
  const write = event === 'failed' ? console.error : console.info
@@ -203,16 +281,15 @@ export async function buildRepositoryBundle(userId: string, request: BuildReques
203
281
  if (settled) return
204
282
  settled = true
205
283
  cleanup()
206
- log(code === 'build-cancelled' ? 'cancelled' : 'failed', { code, ...details })
284
+ log(code === 'build-cancelled' || code === 'build-yielded' ? 'cancelled' : 'failed', { code, ...details })
207
285
  reject(new BundleBuildError(status, code))
208
286
  }
209
287
  const timer = setTimeout(() => fail(504, 'build-timeout'), BUNDLE_BUILD_TIMEOUT_MS)
210
288
  const abort = () => signal.reason instanceof BundleBuildError ? fail(signal.reason.status, signal.reason.code) : fail(499, 'build-cancelled')
211
289
  signal.addEventListener('abort', abort, { once: true })
212
290
  // The worker's memory and notes are the log's alone: the response tells
213
- // the bundle, or the error's code, and nothing of them.
214
- running.on('message', (message: Omit<BuiltBundle, 'bytes'> & { bytes: Uint8Array; type?: string; stage?: BundleBuildStage; error?: string; status?: number;
215
- diagnostic?: BundleBuildDiagnostic; memory?: Record<string, number>; event?: string; details?: Record<string, unknown> }) => {
291
+ // what it built, or the error's code, and nothing of them.
292
+ running.on('message', (message: WorkerMessage<M>) => {
216
293
  if (settled) return
217
294
  if (message.type === 'progress' && message.stage) { stage = message.stage; log('progress', { memory: message.memory }); return }
218
295
  if (message.type === 'memory') { log('memory', { memory: message.memory }); return }
@@ -220,25 +297,24 @@ export async function buildRepositoryBundle(userId: string, request: BuildReques
220
297
  if (message.error) { fail(message.status ?? 422, message.error, { diagnostic: message.diagnostic, memory: message.memory }); return }
221
298
  settled = true
222
299
  cleanup()
223
- log('completed', { byteSize: message.bytes.length })
224
- // A view of the bytes the worker handed over, not a copy of them.
225
- const { bytes } = message
226
- resolve({ bytes: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), directory: message.directory, filename: message.filename })
300
+ const { value, logged } = built(message)
301
+ log('completed', logged)
302
+ resolve(value)
227
303
  })
228
304
  // Past its heap (heapLimitMib), Node terminates the worker with ERR_WORKER_OUT_OF_MEMORY.
229
305
  running.once('error', error => {
230
306
  const outOfMemory = (error as { code?: unknown }).code === 'ERR_WORKER_OUT_OF_MEMORY'
231
- fail(outOfMemory ? 413 : 422, outOfMemory ? 'build-memory' : 'build-failed', { diagnostic: bundleBuildDiagnostic(error, request.token) })
307
+ fail(outOfMemory ? 413 : 422, outOfMemory ? 'build-memory' : 'build-failed', { diagnostic: bundleBuildDiagnostic(error, token) })
232
308
  })
233
309
  running.once('exit', exitCode => fail(422, 'build-failed', { exitCode }))
234
310
  if (signal.aborted) abort()
235
311
  })
236
312
  } catch (error) {
237
313
  if (!(error instanceof BundleBuildError)) {
238
- log('failed', { code: 'build-failed', diagnostic: bundleBuildDiagnostic(error, request.token) })
314
+ log('failed', { code: 'build-failed', diagnostic: bundleBuildDiagnostic(error, token) })
239
315
  }
240
316
  throw error
241
317
  } finally {
242
- try { await worker?.terminate() } finally { active.delete(userId) }
318
+ try { await worker?.terminate() } finally { active.delete(owner) }
243
319
  }
244
320
  }
@@ -5,7 +5,7 @@ import { brotliDecompress } from 'node:zlib'
5
5
  import { promisify } from 'node:util'
6
6
  import { bundleEdges } from '@preventive/sourcemap/edges.js'
7
7
  import { BUNDLE_METADATA_VERSION, type BundleDetails, createBundleMetadata, createBundleSummary, parseBundleContents, parseBundleMetadata } from '../common/bundle-metadata.js'
8
- import { bundleReasons } from '../common/bundle-reasons.js'
8
+ import { bundleReasons, bundleScopes, scopeLabel } from '../common/bundle-reasons.js'
9
9
  import { sourcemapEdges } from '../common/bundle-sourcemap.js'
10
10
  import { type BundleAdvisoryInventory, bundleAdvisoryInventory } from './bundle-advisory-inventory.ts'
11
11
  import { decodeUtf8 } from '../common/utf8.js'
@@ -46,7 +46,19 @@ export interface BundleCacheStorage {
46
46
  }
47
47
 
48
48
  const filename = `v${BUNDLE_METADATA_VERSION}-metadata.json.br`
49
- const packagesFilename = 'v6-advisory-inventory.json'
49
+ const packagesFilename = 'v7-advisory-inventory.json'
50
+
51
+ // An entry point's inventory is rows of the bundle's own, a package's versions
52
+ // in order and then the skipped: kept as a 0 or 1 for each, since spelled out,
53
+ // as a reason's is, many entry points' would not fit the budget.
54
+ const rowKeys = ({ packages, skipped }: BundleAdvisoryInventory) => [
55
+ ...packages.flatMap(pkg => pkg.versions.map(version => JSON.stringify([pkg.ecosystem, pkg.ecosystem === 'github' ? pkg.name.toLowerCase() : pkg.name, version]))),
56
+ ...skipped.map(pkg => JSON.stringify([pkg.ecosystem, pkg.name, pkg.version, 'skipped']))]
57
+ function keptRows(all: BundleAdvisoryInventory, rows: string): BundleAdvisoryInventory {
58
+ let row = 0
59
+ const kept = () => rows[row++] === '1'
60
+ return { packages: all.packages.map(pkg => ({ ...pkg, versions: pkg.versions.filter(kept) })).filter(pkg => pkg.versions.length > 0), skipped: all.skipped.filter(kept) }
61
+ }
50
62
 
51
63
  // All scopes share one bounded derivative. Never decode full bundle metadata
52
64
  // on advisory requests, including when selecting a reason. Persist null when
@@ -77,8 +89,16 @@ function encodePackageInventory(details: BundleDetails): Buffer {
77
89
  return append('{"packages":') && rows(packages) && append(',"skipped":') && rows(skipped) && append('}')
78
90
  }
79
91
  const whole = append('{"all":') && inventory(null)
80
- && list(',"reasons":{', bundleReasons(details), ([reason, paths]) => append(`${JSON.stringify(reason)}:`) && inventory(paths), '}}')
81
- return Buffer.from(whole ? parts.join('') : 'null')
92
+ && list(',"reasons":{', bundleReasons(details), ([reason, paths]) => append(`${JSON.stringify(reason)}:`) && inventory(paths), '}')
93
+ if (!whole) return Buffer.from('null')
94
+ // Entry points last: where they don't fit, they alone are left out.
95
+ const all = rowKeys(bundleAdvisoryInventory(details)), fit = parts.length, fitSize = size, scopes = bundleScopes(details)
96
+ const entries = list(',"entries":{', scopes.ids.filter(id => id.startsWith('entry:')), id => {
97
+ const kept = new Set(rowKeys(bundleAdvisoryInventory(details, scopes.files(id))))
98
+ return append(`${JSON.stringify(scopeLabel(id))}:"${all.map(key => kept.has(key) ? 1 : 0).join('')}"`)
99
+ }, '}')
100
+ if (!entries) { parts.length = fit; size = fitSize }
101
+ return Buffer.from(append('}') ? parts.join('') : 'null')
82
102
  }
83
103
 
84
104
  // What a catalog sends of a bundle before it opens. A Stasis bundle's
@@ -177,14 +197,16 @@ export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, st
177
197
  const decoded = await decompress(await readBytes(await openCached(record, filename)), { maxOutputLength: MAX_DECODED_BYTES })
178
198
  return parseBundleMetadata(JSON.parse(decodeUtf8(decoded)), record.integrity).edges
179
199
  },
180
- async advisoryInventory(record: ManagedBundle, reason = ''): Promise<BundleAdvisoryInventory | null | undefined> {
200
+ // The whole bundle's, one `reason`'s, or one `entry` point's instead: undefined for one it has none of.
201
+ async advisoryInventory(record: ManagedBundle, reason = '', entry = ''): Promise<BundleAdvisoryInventory | null | undefined> {
181
202
  if (record.kind !== 'stasis') return { packages: [], skipped: [] }
182
203
  const cached = await openCached(record, packagesFilename)
183
204
  if (cached.size != null && cached.size > MAX_PACKAGE_INVENTORY_BYTES) { cached.stream.destroy(); return null }
184
205
  const bytes = await readCachedBytes(cached, MAX_PACKAGE_INVENTORY_BYTES)
185
206
  if (!bytes) return null
186
207
  const inventory = JSON.parse(decodeUtf8(bytes))
187
- if (inventory === null) return null
208
+ if (inventory === null || (entry && !inventory.entries)) return null
209
+ if (entry) return Object.hasOwn(inventory.entries, entry) ? keptRows(inventory.all, inventory.entries[entry]) : undefined
188
210
  return reason ? (Object.hasOwn(inventory.reasons, reason) ? inventory.reasons[reason] : undefined) : inventory.all
189
211
  },
190
212
  async delete(id: string) {