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

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 (145) hide show
  1. package/common/bundle-sources.d.ts +2 -0
  2. package/common/bundle-sources.js +19 -2
  3. package/common/finding-duplicates.js +5 -0
  4. package/common/finding-filters.js +45 -4
  5. package/common/line-diff.d.ts +2 -2
  6. package/common/line-diff.js +20 -8
  7. package/common/managed/finding-detail.js +1 -1
  8. package/common/managed/review-view-routes.js +23 -0
  9. package/common/managed/risk-routes.js +30 -0
  10. package/common/managed/routes.js +11 -6
  11. package/common/managed/team-app.d.ts +8 -6
  12. package/common/managed/team-app.js +15 -3
  13. package/common/stasis-files.d.ts +5 -0
  14. package/common/stasis-files.js +20 -0
  15. package/common/stasis-tgz.d.ts +6 -0
  16. package/common/stasis-tgz.js +27 -0
  17. package/common/workspace-app.js +20 -0
  18. package/out/activity.js +2 -4
  19. package/out/{chunk-2F3CYNPZ.js → chunk-2IHCVA3Y.js} +1 -1
  20. package/out/{chunk-HAZKDK4M.js → chunk-2V6Q4ZOZ.js} +1 -1
  21. package/out/{chunk-RRBIJL2B.js → chunk-4IW3VD3H.js} +1 -1
  22. package/out/chunk-4YZOXAXR.js +2 -0
  23. package/out/chunk-5NUDNLJA.js +6 -0
  24. package/out/chunk-5YP7P5KA.js +1 -0
  25. package/out/chunk-6VOB5WXX.js +2 -0
  26. package/out/chunk-74JZTGTO.js +11 -0
  27. package/out/chunk-7YFJUT2P.js +1 -0
  28. package/out/chunk-A4BBBHQU.js +1 -0
  29. package/out/{chunk-4ISO5F7Y.js → chunk-ADMVRLNP.js} +1 -1
  30. package/out/chunk-BIWPZT4E.js +52 -0
  31. package/out/{chunk-HETCVNO4.js → chunk-BLPHP4U3.js} +1 -1
  32. package/out/{chunk-Y5ZHFNBD.js → chunk-BXQCCW7F.js} +1 -1
  33. package/out/{chunk-JFL7WLRV.js → chunk-CU3FPB3P.js} +1 -1
  34. package/out/chunk-CXVBTUK3.js +4 -0
  35. package/out/{chunk-M37X4LCF.js → chunk-EXQQ5VQJ.js} +1 -1
  36. package/out/{chunk-NXATZJQ2.js → chunk-GSNSP3EF.js} +1 -1
  37. package/out/chunk-GV5U7OLP.js +40 -0
  38. package/out/{chunk-JOXLZXMI.js → chunk-GX5UXWT4.js} +1 -1
  39. package/out/{chunk-YF4M5OCI.js → chunk-I6UQQKAH.js} +1 -1
  40. package/out/{chunk-UCP3JRE2.js → chunk-LVW7WWV4.js} +1 -1
  41. package/out/chunk-NEFCZAIY.js +11 -0
  42. package/out/{chunk-TOXMUOIW.js → chunk-OQS2USZM.js} +1 -1
  43. package/out/chunk-PQPKHAI5.js +15 -0
  44. package/out/chunk-PX5DLFSD.js +1 -0
  45. package/out/chunk-QBFT2DDR.js +1 -0
  46. package/out/{chunk-GZ46SSTF.js → chunk-RGNF4OH6.js} +1 -1
  47. package/out/chunk-RLLA4GHZ.js +1 -0
  48. package/out/chunk-ROHACH7V.js +3 -0
  49. package/out/chunk-ROWUGPID.js +1 -0
  50. package/out/{chunk-QMVOEBWC.js → chunk-S2ZIKK45.js} +1 -1
  51. package/out/chunk-SSPDMA6D.js +1 -0
  52. package/out/chunk-TD7RVUTT.js +2 -0
  53. package/out/{chunk-4XIH7YTX.js → chunk-UH6NZBSU.js} +1 -1
  54. package/out/{chunk-M3Y6SLC4.js → chunk-UJP4PQJA.js} +1 -1
  55. package/out/{chunk-PAD2JHZT.js → chunk-UJSJMXEG.js} +1 -1
  56. package/out/{chunk-E3LFSUDJ.js → chunk-VYYUMYVW.js} +1 -1
  57. package/out/{chunk-VRX2APNA.js → chunk-XVKDPU4D.js} +1 -1
  58. package/out/chunk-Y2XGV3RC.js +8 -0
  59. package/out/chunk-YCEMQETS.js +255 -0
  60. package/out/client-managed-import.js +3 -3
  61. package/out/client-managed.js +30 -27
  62. package/out/compare.js +16 -25
  63. package/out/dialogs.js +38 -38
  64. package/out/graph.js +14 -14
  65. package/out/index.html +32 -52
  66. package/out/scan.js +2 -2
  67. package/out/terminal.js +239 -240
  68. package/out/view.css +1 -1
  69. package/out/view.js +15 -15
  70. package/package.json +21 -13
  71. package/risk/actions/resolve.js +56 -19
  72. package/risk/actions/uses.js +27 -9
  73. package/risk/actions/workflow.js +75 -2
  74. package/risk/files/characters.js +11 -0
  75. package/risk/files/hosts.js +4 -4
  76. package/risk/files/readability.js +5 -2
  77. package/risk/files/runs-code.js +12 -25
  78. package/risk/files/script.js +141 -19
  79. package/risk/files/source-map-link.js +43 -0
  80. package/risk/index.d.ts +24 -7
  81. package/risk/index.js +1 -0
  82. package/risk/npm/assess.js +1 -1
  83. package/risk/npm/compare.js +9 -30
  84. package/risk/npm/diff.js +1 -1
  85. package/risk/npm/held.js +6 -2
  86. package/risk/npm/registry.js +5 -2
  87. package/risk/npm/tarball.js +79 -22
  88. package/server-managed/bundle-advisories.ts +12 -36
  89. package/server-managed/bundle-build-worker.js +29 -11
  90. package/server-managed/bundle-build.ts +4 -3
  91. package/server-managed/bundle-cache.ts +53 -13
  92. package/server-managed/bundle.ts +45 -13
  93. package/server-managed/comparison.ts +3 -3
  94. package/server-managed/db-methods.ts +54 -17
  95. package/server-managed/db-neon.ts +9 -2
  96. package/server-managed/db-schema.ts +12 -2
  97. package/server-managed/db.ts +4 -1
  98. package/server-managed/dependency-reviews.ts +8 -5
  99. package/server-managed/github-errors.ts +22 -0
  100. package/server-managed/github-requests.ts +4 -2
  101. package/server-managed/http.ts +336 -76
  102. package/server-managed/management.ts +10 -4
  103. package/server-managed/npm-delta.ts +17 -2
  104. package/server-managed/npm-kept.ts +6 -0
  105. package/server-managed/npm-packages.ts +30 -29
  106. package/server-managed/npm-patch.ts +9 -9
  107. package/server-managed/package-entry-points.ts +54 -6
  108. package/server-managed/pull-dependencies.ts +4 -1
  109. package/server-managed/rename-diff-worker.js +11 -7
  110. package/server-managed/rename-diff.ts +5 -4
  111. package/server-managed/report-opening.ts +77 -0
  112. package/server-managed/report-sources.ts +2 -1
  113. package/server-managed/repository-aliases.ts +34 -0
  114. package/server-managed/repository-browser.ts +87 -32
  115. package/server-managed/repository-code.ts +6 -3
  116. package/server-managed/repository-dependency-reviews.ts +21 -0
  117. package/server-managed/repository-issues.ts +15 -9
  118. package/server-managed/repository-risk-read.ts +50 -4
  119. package/server-managed/repository-risk.ts +9 -2
  120. package/server-managed/stasis-config.ts +97 -5
  121. package/server-managed/stasis-dependencies.ts +7 -4
  122. package/server-managed/team-reports.ts +5 -3
  123. package/server-managed/type-only-proof.js +26 -4
  124. package/server-managed/upstream-cache.ts +18 -12
  125. package/server-managed/workspace-shares.ts +4 -4
  126. package/out/chunk-2HGKTQ5Q.js +0 -52
  127. package/out/chunk-45HTR22K.js +0 -4
  128. package/out/chunk-4RS3NDOG.js +0 -1
  129. package/out/chunk-7GJNLCXF.js +0 -15
  130. package/out/chunk-CGRIZ5M5.js +0 -1
  131. package/out/chunk-CQIT5UNK.js +0 -1
  132. package/out/chunk-D6NVKGGG.js +0 -10
  133. package/out/chunk-DTAR2BB6.js +0 -247
  134. package/out/chunk-MPXVKVPF.js +0 -3
  135. package/out/chunk-NB4JBTKK.js +0 -2
  136. package/out/chunk-QPGM3DTI.js +0 -42
  137. package/out/chunk-VFWMQ3LG.js +0 -2
  138. package/out/chunk-VG5RH6KN.js +0 -2
  139. package/out/chunk-WFDXHPT2.js +0 -12
  140. package/out/chunk-WMFDQS2L.js +0 -11
  141. package/out/chunk-WREU7JAG.js +0 -1
  142. /package/out/{chunk-JMG5DXII.js → chunk-7HP2VYIC.js} +0 -0
  143. /package/out/{chunk-HOB3YPS5.js → chunk-K4XJHM2T.js} +0 -0
  144. /package/out/{chunk-4EMM6UCD.js → chunk-QI66YA4F.js} +0 -0
  145. /package/out/{chunk-G3LY2FV4.js → chunk-WCDYSIKG.js} +0 -0
@@ -7,7 +7,7 @@ export const ADVISORIES_TIMEOUT_MS = 30_000
7
7
  function advisoryGithubClient(token: string | null, signal: AbortSignal): Client {
8
8
  const authenticated = createClient({ token, userAgent: USER_AGENT })
9
9
  let client = authenticated
10
- // Published advisories, and whether a repository is public, remain
10
+ // Published advisories, and where a moved repository is now, remain
11
11
  // readable after a token is revoked. Reuse anonymous access for subsequent
12
12
  // repositories in this audit as well.
13
13
  async function retried<T>(ask: (current: Client) => Promise<T>): Promise<T> {
@@ -26,43 +26,19 @@ function advisoryGithubClient(token: string | null, signal: AbortSignal): Client
26
26
  }
27
27
  }
28
28
 
29
- // How many repositories GitHub is asked at once whether they are public, as
30
- // upstream asks for their listings.
31
- const REPOS_AT_ONCE = 4
32
-
33
- // Whether GitHub says anyone may read `repo`: not one private, nor one it
34
- // has none of for this client (gone, or not the caller's to read). Any other
35
- // failure is thrown, as the audit then fails.
36
- async function isPublicRepo(github: Client, repo: string): Promise<boolean> {
37
- try { return (await github.getRepo({ repo, followRedirect: true }) as { private?: unknown } | null)?.private === false } catch (error) {
38
- if (error instanceof HttpError && [404, 410, 451].includes(error.status)) return false
39
- throw error
40
- }
41
- }
42
-
43
- // The packages as upstream is asked of them. Upstream asks OSV of every
44
- // `github` package by its name, as an Action, but of one `internal`: each is
45
- // internal but where GitHub says its repository is public, so a private one,
46
- // or one GitHub has none of, has its own published advisories read alone, as
47
- // a private npm package's name never reaches OSV either. One that says
48
- // (`internal`, as its caller knows) is taken as it says.
49
- async function markInternal(packages: Package[], github: Client): Promise<Package[]> {
50
- const internal = new Set(packages.flatMap(pkg => pkg.ecosystem === 'github' && pkg.internal === undefined ? [pkg.name] : []))
51
- const repos = [...internal]
52
- for (let at = 0; at < repos.length; at += REPOS_AT_ONCE) {
53
- await Promise.all(repos.slice(at, at + REPOS_AT_ONCE).map(async repo => { if (await isPublicRepo(github, repo)) internal.delete(repo) }))
54
- }
55
- return packages.map(pkg => pkg.ecosystem === 'github' && internal.has(pkg.name) ? { ...pkg, internal: true } : pkg)
56
- }
57
-
58
29
  // The managed caller supplies its user's token when available; public shares
59
30
  // remain anonymous. Upstream sends this credential only to GitHub and returns
60
31
  // published advisories, matching versions across npm, OSV and repository rows:
61
32
  // OSV's for npm packages anyone may read too, the malicious packages' records
62
33
  // among them, which npm's registry hasn't, each row of malware told so
63
- // (`malware`). `cache` keeps each repository's listing, and the npm packages
64
- // anyone may read (upstream-cache.ts), across audits; `github`, a client of
65
- // the caller's, asks GitHub in place of one with `githubToken`.
34
+ // (`malware`); and of a `github` package, OSV's only where github.com serves
35
+ // its repository to anyone (asked with no credentials), so a private one, or
36
+ // one gone, has its own published advisories read alone, as a private npm
37
+ // package's name never reaches OSV either. One the caller says is
38
+ // `internal` is never asked of OSV. `cache` keeps each repository's listing,
39
+ // and the npm packages and github.com's repositories anyone may read
40
+ // (upstream-cache.ts), across audits; `github`, a client of the caller's, asks
41
+ // GitHub in place of one with `githubToken`.
66
42
  export async function fetchBundleAdvisories(packages: Package[], signal: AbortSignal,
67
43
  { debug = false, repoAdvisories = false, details = false, githubToken = null, github, cache }: {
68
44
  debug?: boolean; repoAdvisories?: boolean; details?: boolean; githubToken?: string | null; github?: Client; cache?: CacheStore | undefined
@@ -82,13 +58,13 @@ export async function fetchBundleAdvisories(packages: Package[], signal: AbortSi
82
58
  // npm packages anyone may read are asked of OSV too (upstream's `osv`),
83
59
  // for the malicious packages' records npm's registry hasn't: upstream
84
60
  // sends OSV only the names npm's registry serves without a token, so a
85
- // private one's never leaves for OSV, as it never does for Socket; nor an
86
- // internal `github` package's (markInternal). Kept
61
+ // private one's never leaves for OSV, as it never does for Socket; nor a
62
+ // `github` package's github.com serves to no one without credentials. Kept
87
63
  // in the caller's store, or without one in upstream's disk cache, where
88
64
  // the server set one (auditCache).
89
65
  const client = github ?? advisoryGithubClient(githubToken, signal)
90
66
  const options = { github: client, repoAdvisories, details, osv: true, ...(cache && { cache }) }
91
- return { status: 200, body: await Promise.race([markInternal(packages, client).then(asked => advisories(asked, options)), deadline]) }
67
+ return { status: 200, body: await Promise.race([advisories(packages, options), deadline]) }
92
68
  } catch (error) {
93
69
  // Answered as upstream's failure alone: logged, its message, or with
94
70
  // `debug` the whole error, but for a request its client gave up on. One
@@ -5,14 +5,14 @@ import { mkdir, readFile, readdir, rename, rm, stat, statfs, writeFile } from 'n
5
5
  import { join, posix } from 'node:path'
6
6
  import { brotliCompressSync } from 'node:zlib'
7
7
  import { isEvidenceFile } from '@exodus/stasis/audit-corrections'
8
- import { buildGitHubBundle, setCacheDir } from '@exodus/stasis/vfs-bundle'
8
+ import { buildGitHubBundle, bundleFileBytes, setCacheDir } from '@exodus/stasis/vfs-bundle'
9
9
  import { brotliOptions } from '@exodus/stasis-core/brotli'
10
10
  import { LOCK_FILE, dependencyEcosystem, integrityHex } from '@exodus/stasis-core/util'
11
11
  import { HttpError, createClient } from '@preventive/upstream/github.js'
12
12
  import { githubBundleFilename } from './bundle-build.ts'
13
13
  import { isDirectoryPackage } from '../common/managed/directory-packages.ts'
14
14
  import { bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
15
- import { MAX_STASIS_CONFIG_BYTES, STASIS_CONFIG, namesLockfiles, parseStasisConfig } from './stasis-config.ts'
15
+ import { MAX_STASIS_CONFIG_BYTES, STASIS_CONFIG, namesEntry, namesLockfiles, parseStasisConfig } from './stasis-config.ts'
16
16
 
17
17
  // A bundle's JSON, before compression, at most: a project producing it is
18
18
  // what a build's heap is sized for (bundle-build.ts buildHeapLimitMib).
@@ -64,6 +64,17 @@ async function directoryConfig(configText, directory) {
64
64
  }
65
65
  }
66
66
 
67
+ // Whether the stasis.config.json in `directory`, whose entries are `config`,
68
+ // names `entry`: by its path, or by a pattern matching it. One naming it twice
69
+ // Stasis refuses, config-invalid.
70
+ function namesSelected(config, directory, entry) {
71
+ try {
72
+ return config !== null && namesEntry(config, posix.relative(`/${directory}`, `/${entry}`))
73
+ } catch (error) {
74
+ throw new Error('config-invalid', { cause: error })
75
+ }
76
+ }
77
+
67
78
  // The directory of the stasis.config.json listing the selected entries: for
68
79
  // each entry, the nearest one at or above it whose `entries` names it. null
69
80
  // where none lists any. Stasis reads the one in the directory it builds from
@@ -72,8 +83,7 @@ async function directoryConfig(configText, directory) {
72
83
  async function listingConfig(input, configText) {
73
84
  const found = await Promise.all(input.entries.map(async entry => {
74
85
  for (let directory = parentOf(entry); ; directory = parentOf(directory)) {
75
- const config = await directoryConfig(configText, directory)
76
- if (config?.has(posix.relative(`/${directory}`, `/${entry}`))) return { entry, directory }
86
+ if (namesSelected(await directoryConfig(configText, directory), directory, entry)) return { entry, directory }
77
87
  if (!directory) return { entry, directory: null }
78
88
  }
79
89
  }))
@@ -158,8 +168,11 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
158
168
  const named = packageManager !== undefined && !namesLockfiles(await configText(project) ?? '{}')
159
169
  note('project', { project, configured: configured !== null, ...(named && { packageManager }) })
160
170
  // The branch the commit was picked by, where it was, Stasis asks first of
161
- // whether the commit is the repo's own (bundle-build.ts).
162
- const { bundle } = await buildGitHubBundle({
171
+ // whether the commit is the repo's own (bundle-build.ts). It tells the
172
+ // format `stasis github-bundle` writes the bundle in, by the
173
+ // stasis.config.json it builds from: a stasis.code.br but where that names
174
+ // tgz, a .stasis.tgz.
175
+ const { bundle, format } = await buildGitHubBundle({
163
176
  github, sha: input.commit, ...(input.branch !== undefined && { branch: input.branch }), directory: project || undefined,
164
177
  entries: input.entries.map(entry => posix.relative(project || '.', entry)),
165
178
  ...options, ...(named && { packageManager }), client: buildClient, ...await cacheOf(cacheDir, instanceDir),
@@ -171,7 +184,8 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
171
184
  if (!allowed(directory)) throw new Error('build-scope')
172
185
  progress('serialize')
173
186
  // Its JSON as bytes, a module at a time, never one string on the heap; a
174
- // module too large for V8 to hold as one is too large too.
187
+ // module too large for V8 to hold as one is too large too. A .stasis.tgz's
188
+ // too: its contents are served as this JSON (bundle-cache.ts).
175
189
  let serialized
176
190
  try { serialized = bundle.serializedBytes() } catch (error) {
177
191
  // A failure's code, as buildErrorCode reads it, not a value of the wrong type.
@@ -181,10 +195,11 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
181
195
  }
182
196
  if (serialized.length > MAX_SERIALIZED_BYTES) throw new Error('too-large')
183
197
  progress('compress')
184
- const bytes = brotliCompressSync(serialized, brotliOptions())
198
+ // As Stasis writes the bundle's file in its format (bundleFileBytes).
199
+ const bytes = format === 'tgz' ? await bundleFileBytes(bundle, format) : brotliCompressSync(serialized, brotliOptions())
185
200
  if (bytes.length > maxBytes) throw new Error('too-large')
186
201
  const name = await packageName(input, github, project, bundle, buildClient)
187
- return { bytes, directory, filename: githubBundleFilename(github, project, input.commit, name) }
202
+ return { bytes, directory, filename: githubBundleFilename(github, project, input.commit, name, format) }
188
203
  }
189
204
 
190
205
  // The npm package versions a Stasis lockfile holds code of (an evidence
@@ -286,7 +301,10 @@ export async function buildStasisLockfile({ input, github, token, cacheDir = nul
286
301
  // or its excludeModules excludes (an entry in such a package among them), the
287
302
  // config's or an entry's, is the policy's, as is one broken at load by
288
303
  // imports excludeModules excludes alone; one it can't read, build with
289
- // its options, or lay out the lockfiles it names of, is the config's. A build
304
+ // its options, or lay out the lockfiles it names of, is the config's, as is
305
+ // one whose scope, lock, bundle, format or fs Stasis's config refuses (its
306
+ // `Invalid <option>: <value>`, naming no file: a server build sets none of
307
+ // them but by its stasis.config.json). A build
290
308
  // the repository's stasis.lock.json disagrees with, or that its lock mode
291
309
  // holds to one that isn't there, is the stasis.lock.json's. A commit Stasis
292
310
  // finds in the history of none of the repo's branches or tags (a fork's,
@@ -299,7 +317,7 @@ export function buildErrorCode(error, message) {
299
317
  if (message.endsWith(': bundle either the entries it names or others, not both')) return 'config-mixed'
300
318
  if (/\bstasis\.config\.json(?:: entries .*?)?: (?:(?:allowed|disallowed)(?:Paths|Modules) (?:refuses|does not allow|allows none of)|excludeModules excludes) /u.test(message)) return 'config-policy'
301
319
  if (brokenByExclusion(message)) return 'config-policy'
302
- if (/\bstasis\.config\.json(?: is not valid JSON|: |'s lockfiles )/u.test(message)) return 'config-invalid'
320
+ if (/\bstasis\.config\.json(?: is not valid JSON|: |'s lockfiles )|^Invalid (?:scope|lock|bundle|format|fs): /u.test(message)) return 'config-invalid'
303
321
  if (/\bstasis\.lock\.json(?::| isn't there,| \(lock = )/u.test(message)) return 'stasis-lock'
304
322
  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'
305
323
  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'
@@ -105,10 +105,11 @@ function packageBase(name: string): string | null {
105
105
 
106
106
  // Same portable name and 255-character limit as Stasis's githubBundleFile
107
107
  // (src/cmd/github-bundle.js), which is not a public package export, except
108
- // that a usable `packageName` replaces both the repo and the directory.
109
- export function githubBundleFilename(github: string, directory: string, commit: string, packageName: string | null = null): string {
108
+ // that a usable `packageName` replaces both the repo and the directory; a
109
+ // .stasis.tgz's (`format` tgz) ends in `.stasis.tgz`, as Stasis's does.
110
+ export function githubBundleFilename(github: string, directory: string, commit: string, packageName: string | null = null, format: 'br' | 'tgz' = 'br'): string {
110
111
  const portable = (value: string) => value.replaceAll(/[^\w.-]/gu, '_')
111
- const tail = `.${portable(commit.slice(0, 7))}.stasis.code.br`
112
+ const tail = `.${portable(commit.slice(0, 7))}.${format === 'tgz' ? 'stasis.tgz' : 'stasis.code.br'}`
112
113
  const named = packageName === null ? null : packageBase(packageName)
113
114
  if (named !== null) return `${portable(named)}${tail}`
114
115
  const repo = portable(github.replace('/', '-'))
@@ -1,5 +1,6 @@
1
1
  // Metadata is cached as Brotli. Contents use the stored Brotli bytes directly:
2
- // unchanged Stasis uploads or sourcemaps compressed once at upload.
2
+ // unchanged Stasis uploads or sourcemaps compressed once at upload. A
3
+ // .stasis.tgz's are its bundle's JSON, made from it once and cached as Brotli.
3
4
  import { Buffer } from 'node:buffer'
4
5
  import { brotliDecompress } from 'node:zlib'
5
6
  import { promisify } from 'node:util'
@@ -9,6 +10,8 @@ import { bundleReasons, bundleScopes, scopeLabel } from '../common/bundle-reason
9
10
  import { sourcemapEdges } from '../common/bundle-sourcemap.js'
10
11
  import { type BundleAdvisoryInventory, bundleAdvisoryInventory } from './bundle-advisory-inventory.ts'
11
12
  import { decodeUtf8 } from '../common/utf8.js'
13
+ import { isStasisTgzName } from '../common/stasis-files.js'
14
+ import { readStasisTgz } from '../common/stasis-tgz.js'
12
15
  import { type OpenedBlob, readBytes } from './blob-store.ts'
13
16
  import type { BundleStore } from './bundle-store.ts'
14
17
  import { encodeBrotli } from './brotli.ts'
@@ -28,13 +31,17 @@ export async function readBundleDetails(record: BundleCacheRecord, store: Bundle
28
31
  }
29
32
 
30
33
  // As readBundleDetails, with the bytes the bundle decoded to: about what
31
- // holding its details takes.
34
+ // holding its details takes. A Stasis bundle's name tells a .stasis.tgz's.
32
35
  export async function readSizedBundleDetails(record: BundleCacheRecord, store: BundleStore) {
33
36
  const bytes = await store.get(record.id, record.kind)
34
37
  if (!bytes) return null
38
+ if (record.kind === 'stasis' && isStasisTgzName(record.filename)) {
39
+ const { bundle, size } = await readStasisTgz(bytes, { limit: MAX_DECODED_BYTES })
40
+ return { details: { integrity: record.integrity, kind: record.kind, size: record.byteSize, bundle } as BundleDetails, decodedBytes: size, tgz: true }
41
+ }
35
42
  const decoded = record.kind === 'stasis' || record.kind === 'sourcemap' ? await decompress(bytes, { maxOutputLength: MAX_DECODED_BYTES }) : bytes
36
43
  if (decoded.length > MAX_DECODED_BYTES) throw new Error('Decoded bundle too large')
37
- return { details: parseBundleContents(decodeUtf8(decoded), { integrity: record.integrity, kind: record.kind, size: record.byteSize }), decodedBytes: decoded.length }
44
+ return { details: parseBundleContents(decodeUtf8(decoded), { integrity: record.integrity, kind: record.kind, size: record.byteSize }), decodedBytes: decoded.length, tgz: false }
38
45
  }
39
46
 
40
47
  export interface BundleCacheStorage {
@@ -46,6 +53,8 @@ export interface BundleCacheStorage {
46
53
  }
47
54
 
48
55
  const filename = `v${BUNDLE_METADATA_VERSION}-metadata.json.br`
56
+ // A .stasis.tgz's bundle as a stasis.code.br holds it: its JSON, as Brotli.
57
+ const contentsFilename = 'v1-contents.json.br'
49
58
  const packagesFilename = 'v8-advisory-inventory.json'
50
59
 
51
60
  // An entry point's inventory is rows of the bundle's own, a package's versions
@@ -123,13 +132,24 @@ function readSourcemapEdges(details: BundleDetails) {
123
132
 
124
133
  // As readBundleDetails, thrown where the bundle's bytes are gone.
125
134
  async function storedDetails(record: BundleCacheRecord, store: BundleStore) {
126
- const details = await readBundleDetails(record, store)
127
- if (!details) throw new Error('Bundle bytes unavailable')
128
- return details
135
+ const read = await readSizedBundleDetails(record, store)
136
+ if (!read) throw new Error('Bundle bytes unavailable')
137
+ return read
138
+ }
139
+
140
+ // A .stasis.tgz's contents (contentsFilename), of its bundle as read.
141
+ const encodeContents = (details: BundleDetails) => encodeBrotli((details.bundle as { serializedBytes(): Uint8Array }).serializedBytes())
142
+
143
+ // What a build wrote is removed where another instance deleted the row
144
+ // meanwhile, so its cleanup cannot be undone by us.
145
+ async function reconcile(record: BundleCacheRecord, storage: BundleCacheStorage, db: ManagedDb) {
146
+ if (await db.getBundle(record.id)) return
147
+ await storage.delete(record.id)
148
+ throw new Error('Bundle deleted')
129
149
  }
130
150
 
131
151
  async function build(record: BundleCacheRecord, storage: BundleCacheStorage, db: ManagedDb, store: BundleStore) {
132
- const details = await storedDetails(record, store)
152
+ const { details, tgz } = await storedDetails(record, store)
133
153
  readSourcemapEdges(details)
134
154
  const metadata = { ...await createBundleMetadata(details), id: record.id, filename: record.filename }
135
155
  const body = await encodeBrotli(Buffer.from(JSON.stringify(metadata)))
@@ -140,14 +160,12 @@ async function build(record: BundleCacheRecord, storage: BundleCacheStorage, db:
140
160
  const written = await Promise.allSettled([
141
161
  storage.put(record.id, filename, body),
142
162
  ...record.kind === 'stasis' ? [storage.put(record.id, packagesFilename, encodePackageInventory(details))] : [],
163
+ ...tgz ? [encodeContents(details).then(contents => storage.put(record.id, contentsFilename, contents))] : [],
143
164
  storage.put(record.id, SUMMARY_FILENAME, Buffer.from(JSON.stringify(summary))),
144
165
  ])
145
166
  // A different instance may have deleted the row while these writes ran.
146
167
  // Reconcile after publishing so its cleanup cannot be undone by us.
147
- if (!(await db.getBundle(record.id))) {
148
- await storage.delete(record.id)
149
- throw new Error('Bundle deleted')
150
- }
168
+ await reconcile(record, storage, db)
151
169
  const failed = written.find(result => result.status === 'rejected')
152
170
  if (failed) throw failed.reason
153
171
  return summary
@@ -157,7 +175,7 @@ export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, st
157
175
  const pending = new Map<string, Promise<void>>()
158
176
  // The database deduplicates by integrity, so each hash has one persistent
159
177
  // bundle/cache directory, shared across teams and repeated uploads.
160
- const summaries = createBundleSummaryCache(storage, async record => bundleSummary(await storedDetails(record, store)), id => db.getBundle(id))
178
+ const summaries = createBundleSummaryCache(storage, async record => bundleSummary((await storedDetails(record, store)).details), id => db.getBundle(id))
161
179
  let queue = Promise.resolve()
162
180
  async function ensure(record: BundleCacheRecord): Promise<void> {
163
181
  const existing = pending.get(record.id)
@@ -171,6 +189,26 @@ export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, st
171
189
  pending.set(record.id, job)
172
190
  try { await job } finally { if (pending.get(record.id) === job) pending.delete(record.id) }
173
191
  }
192
+ // A .stasis.tgz's contents as cached, else made from it, as a build of
193
+ // the rest makes them beside its metadata, each made once at a time.
194
+ async function openContents(record: BundleCacheRecord) {
195
+ try { return await storage.open(record.id, contentsFilename) }
196
+ catch (error) { if (!(error instanceof CacheMissError)) throw error }
197
+ const key = `${record.id}\0contents`
198
+ let job = pending.get(key)
199
+ if (!job) {
200
+ job = (async () => {
201
+ const body = await encodeContents((await storedDetails(record, store)).details)
202
+ if (!(await db.getBundle(record.id))) throw new Error('Bundle deleted')
203
+ await storage.put(record.id, contentsFilename, body)
204
+ await reconcile(record, storage, db)
205
+ })()
206
+ pending.set(key, job)
207
+ job.finally(() => { if (pending.get(key) === job) pending.delete(key) }).catch(() => {})
208
+ }
209
+ await job
210
+ return storage.open(record.id, contentsFilename)
211
+ }
174
212
  async function openCached(record: BundleCacheRecord, file: string) {
175
213
  try { return await storage.open(record.id, file) }
176
214
  catch (error) { if (!(error instanceof CacheMissError)) throw error }
@@ -185,6 +223,8 @@ export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, st
185
223
  async open(record: ManagedBundle, part: BundleCachePart) {
186
224
  if (part === 'contents') {
187
225
  if (record.kind !== 'stasis' && record.kind !== 'sourcemap') throw new Error('Unsupported bundle')
226
+ // A .stasis.tgz's: its bundle's JSON in its place.
227
+ if (record.kind === 'stasis' && isStasisTgzName(record.filename)) return openContents(record)
188
228
  const stored = await store.open(record.id, record.kind)
189
229
  if (!stored) throw new Error('Bundle bytes unavailable')
190
230
  return stored
@@ -212,7 +252,7 @@ export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, st
212
252
  async delete(id: string) {
213
253
  // Call after deleting the row. Waiting prevents an in-flight builder
214
254
  // from recreating its files after deletion has completed.
215
- await pending.get(id)?.catch(() => {})
255
+ await Promise.all([id, `${id}\0contents`].map(key => pending.get(key)?.catch(() => {})))
216
256
  await summaries.forget(id)
217
257
  await storage.delete(id)
218
258
  },
@@ -8,9 +8,12 @@
8
8
  import { createHash } from 'node:crypto'
9
9
  import type { Buffer } from 'node:buffer'
10
10
  import { StringDecoder } from 'node:string_decoder'
11
- import { brotliDecompress, createBrotliDecompress } from 'node:zlib'
11
+ import { brotliDecompress, createBrotliDecompress, createGunzip } from 'node:zlib'
12
12
  import { promisify } from 'node:util'
13
+ import { unpackStream } from '@preventive/archive/tar.js'
13
14
  import { parseBundleContents } from '../common/bundle-metadata.js'
15
+ import { isStasisBundleName, isStasisTgzName } from '../common/stasis-files.js'
16
+ import { parseStasisTgz } from '../common/stasis-tgz.js'
14
17
  import { bundleFilesAsMap } from '../common/bundle-sources.js'
15
18
  import { commonFileDirectory } from '../common/managed/repository-alias.ts'
16
19
  import { decodeUtf8 } from '../common/utf8.js'
@@ -25,13 +28,15 @@ export function bundleIntegrity(bytes: Buffer): string {
25
28
  }
26
29
 
27
30
  // Classify an uploaded bundle by filename — mirrors ui/view/ingest.js
28
- // `bundleKind`: sourcemap (.map) or stasis (stasis.code.br / .stasis.code.br).
29
- // null for anything else (stored anyway; the kind is informational).
31
+ // `bundleKind`: sourcemap (.map) or stasis (stasis.code.br / .stasis.code.br,
32
+ // stasis.tgz / .stasis.tgz). null for anything else (stored anyway; the kind
33
+ // is informational). A stasis bundle's format is told by its name, as Stasis
34
+ // tells it (isStasisTgzName).
30
35
  export function bundleKind(filename: string): 'sourcemap' | 'stasis' | null {
31
36
  // Browsers insert a duplicate-download counter before the final extension.
32
37
  const lower = filename.toLowerCase().replace(/ \(\d+\)(?=\.[^.]*$)/u, '')
33
38
  if (lower.endsWith('.map')) return 'sourcemap'
34
- if (lower === 'stasis.code.br' || lower.endsWith('.stasis.code.br')) return 'stasis'
39
+ if (isStasisBundleName(lower)) return 'stasis'
35
40
  return null
36
41
  }
37
42
 
@@ -64,10 +69,7 @@ function headerRepo(text: string): BundleRepo | null | undefined {
64
69
  depth++
65
70
  if (depth === 1) expectKey = true
66
71
  } else if (depth === 1 && (c === ',' || c === '}')) {
67
- if (key === 'repo') {
68
- const repo: unknown = JSON.parse(text.slice(valueStart, i))
69
- return repo != null && typeof repo === 'object' && !Array.isArray(repo) ? repo as BundleRepo : null
70
- }
72
+ if (key === 'repo') return plainRepo(JSON.parse(text.slice(valueStart, i)))
71
73
  if (c === '}') return null
72
74
  expectKey = true
73
75
  } else if (c === '}' || c === ']') depth--
@@ -77,9 +79,38 @@ function headerRepo(text: string): BundleRepo | null | undefined {
77
79
  return undefined
78
80
  }
79
81
 
82
+ const plainRepo = (repo: unknown) => repo != null && typeof repo === 'object' && !Array.isArray(repo) ? repo as BundleRepo : null
83
+
84
+ // A .stasis.tgz's repo, as its stasis.lock.json records it: the first entry
85
+ // of its tar, as Stasis requires one (Bundle.fromTar refuses a tar it isn't
86
+ // first in), read alone, its gunzipped bytes bounded as the lockfile's own are.
87
+ const MAX_TGZ_LOCKFILE_BYTES = 64 * 1024 * 1024
88
+ async function tgzRepo(bytes: Buffer): Promise<BundleRepo | null> {
89
+ const stream = createGunzip({ chunkSize: 64 * 1024 })
90
+ stream.end(bytes)
91
+ async function* bounded() {
92
+ let size = 0
93
+ for await (const chunk of stream) {
94
+ size += (chunk as Buffer).length
95
+ if (size > MAX_TGZ_LOCKFILE_BYTES) throw new Error('Lockfile too large')
96
+ yield chunk as Buffer
97
+ }
98
+ }
99
+ try {
100
+ for await (const entry of unpackStream(bounded())) {
101
+ if (entry.name !== 'stasis.lock.json') return null
102
+ return plainRepo((JSON.parse(decodeUtf8(entry.data)) as { repo?: unknown } | null)?.repo)
103
+ }
104
+ return null
105
+ } catch { return null }
106
+ finally { stream.destroy() }
107
+ }
108
+
80
109
  // Decode only a bounded prefix, stopping as soon as repo is read or the
81
- // header ends. Unknown/malformed archives remain uploadable as opaque bytes.
82
- export async function bundleRepo(bytes: Buffer): Promise<BundleRepo | null> {
110
+ // header ends: a stasis.code.br's, but where `filename` names a .stasis.tgz,
111
+ // its stasis.lock.json (tgzRepo). Unknown or malformed archives remain uploadable as opaque bytes.
112
+ export async function bundleRepo(bytes: Buffer, filename = ''): Promise<BundleRepo | null> {
113
+ if (isStasisTgzName(filename)) return tgzRepo(bytes)
83
114
  const stream = createBrotliDecompress({ chunkSize: 4096 })
84
115
  const decoder = new StringDecoder('utf8')
85
116
  let size = 0, text = ''
@@ -100,10 +131,11 @@ export async function bundleRepo(bytes: Buffer): Promise<BundleRepo | null> {
100
131
  const decompress = promisify(brotliDecompress)
101
132
  // Same decoded size bound as the bundle metadata cache; only reached when an
102
133
  // alias can use a shared file suffix. Invalid/opaque bundles keep header defaults.
103
- export async function bundleFilePrefix(bytes: Buffer): Promise<string> {
134
+ export async function bundleFilePrefix(bytes: Buffer, filename = ''): Promise<string> {
104
135
  try {
105
- const decoded = await decompress(bytes, { maxOutputLength: 512 * 1024 * 1024 })
106
- const details = parseBundleContents(decodeUtf8(decoded), { integrity: '', kind: 'stasis', size: bytes.length })
136
+ const identity = { integrity: '', kind: 'stasis', size: bytes.length }
137
+ const details = isStasisTgzName(filename) ? { ...identity, bundle: await parseStasisTgz(bytes) }
138
+ : parseBundleContents(decodeUtf8(await decompress(bytes, { maxOutputLength: 512 * 1024 * 1024 })), identity)
107
139
  return commonFileDirectory(bundleFilesAsMap(details).keys())
108
140
  } catch { return '' }
109
141
  }
@@ -23,13 +23,13 @@ import { opened } from './pretty-print.ts'
23
23
  export const emptySide = (): BundleDetails => ({ integrity: '(empty)', kind: 'sourcemap', size: 0, json: { version: 3, sources: [], sourcesContent: [] } })
24
24
 
25
25
  // A version's files as the viewer reads them for a comparison (ui/view/npm-package.js
26
- // npmPackageDetails): its texts, and those that are not text by their size and digest.
27
- export function npmComparedSide(integrity: string, files: NpmPackageFile[]): BundleDetails & { npmBinaries: Map<string, { size: number; digest: string }> } {
26
+ // npmPackageDetails): its texts, and those that are not text by their size and digest, a symlink's target too.
27
+ export function npmComparedSide(integrity: string, files: NpmPackageFile[]): BundleDetails & { npmBinaries: Map<string, { size: number; digest: string; link?: string }> } {
28
28
  const rows = npmFileRows(files)
29
29
  return {
30
30
  integrity, kind: 'sourcemap', size: 0,
31
31
  json: { version: 3, sources: rows.map(([path]) => path), sourcesContent: rows.map(([, , text]) => text) },
32
- npmBinaries: new Map(rows.flatMap(([path, size, text, digest]) => (text === null ? [[path, { size, digest: digest! }] as const] : []))),
32
+ npmBinaries: new Map(rows.flatMap(([path, size, text, digest, link]) => (text === null ? [[path, { size, digest: digest!, ...link === undefined ? {} : { link } }] as const] : []))),
33
33
  }
34
34
  }
35
35