import { existsSync, promises as fs } from 'node:fs' import path from 'node:path' import { spawn } from '@socketsecurity/registry/lib/spawn' import { assembleFacts } from './assemble.mts' import { resolveBuildToolBin, socketFactsFileName } from './build-tool.mts' import { serializeExcludePathPatterns } from './exclude-paths-glob.mts' import { parseRecords } from './records.mts' import constants from '../../../constants.mts' import { isStandaloneSea } from '../../../sea/runtime.mts' import { withTmpDir } from '../../../utils/fs.mts' import { getOrInsert } from '../../../utils/get-or-insert.mts' import { camelToKebab } from '../../../utils/strings.mts' import type { BuildTool } from './build-tool.mts' import type { ResolvedArtifactPaths, SocketFactsSbom, SocketFactsSbomProject, } from './facts.mts' import type { ResolutionReport } from './resolution-report.mts' export type ManifestScriptOptions = { projectDir: string // Unset ⇒ resolved to the project wrapper, else PATH (resolveBuildToolBin). bin?: string | undefined // The file in projectDir to build: Maven's POM (unset leaves Maven's // default), dotnet's solution or project (required). entryFile?: string | undefined // Reachability-only: also materialize resolved artifact paths (artifactPaths). withFiles?: boolean | undefined // sbt only: caller-supplied directory to use as sbt's isolated global base. // sbt provisions the project's Scala toolchain (compiler/library/reflect) // under `/boot`, which withFiles' artifactPaths point into, so // the directory must outlive this call; the caller owns creating it and // deleting it once those paths are no longer needed. Unset ⇒ an ephemeral // dir is created and cleaned up before this call returns (the withFiles-less // default, and the case for a standalone `socket manifest sbt --facts`). tmpDir?: string | undefined // Newline-delimited GAV file scoping withFiles materialization; absent ⇒ all. populateFilesFor?: string | undefined includeConfigs?: string | undefined excludeConfigs?: string | undefined // `--exclude-paths`, relative to excludeBase. Passed to the build script, which // skips resolving a wholly excluded subproject. Source-file-level exclusion is // left to the reachability analysis (coana's --exclude-dirs), not applied here. excludePaths?: string[] | undefined // The scan root, which a build's modules can lie outside of (Maven `../x` // modules); projectDir when unset. excludeBase?: string | undefined toolOpts?: string[] | undefined stdio?: 'inherit' | 'pipe' | undefined env?: NodeJS.ProcessEnv | undefined signal?: AbortSignal | undefined } export type ManifestRunResult = { code: number facts: SocketFactsSbom // Undefined when the build did not report it. buildRoot: string | undefined // Undefined when a file-addressed build did not report its entry file. factsFileName: string | undefined report: ResolutionReport artifactPaths: ResolvedArtifactPaths // Captured build-tool output (empty when stdio is 'inherit', which streams it // to stderr). stderr: string stdout: string } type RunOutput = { code: number; stdout: string; stderr: string } const FACTS_TASK = 'socketFacts' const WORKSPACES_TASK = 'socketWorkspaces' // Destination filename inside sbt's isolated plugins/ dir; unrelated to the source filename, which // is whatever socket-facts.plugin.scala / socket-workspaces.plugin.scala are called on disk. const SBT_FACTS_PLUGIN_FILENAME = 'SocketFactsPlugin.scala' const SBT_WORKSPACES_PLUGIN_FILENAME = 'SocketWorkspacesPlugin.scala' export type WorkspaceEnumerationResult = { // Absolute; what each project's subprojectDir and manifestFiles are relative to. buildRoot: string | undefined code: number projects: SocketFactsSbomProject[] stderr: string stdout: string } // Bundled emitter assets, copied into dist by the rollup build. function manifestScriptsPath(...parts: string[]): string { return path.join(constants.distPath, 'manifest-scripts', ...parts) } // Streamed build output is a diagnostic: it goes to stderr so the command's own // stdout (e.g. --json) stays machine-readable. const STREAM_TO_STDERR = ['inherit', 2, 'inherit'] as const // Don't throw on a non-zero exit: the script emits failure records, so a usable // records file still exists. A non-exit spawn error (e.g. missing executable) // propagates. async function runNeverThrow( bin: string, args: string[], opts: ManifestScriptOptions, ): Promise { try { const result = await spawn(bin, args, { cwd: opts.projectDir, stdio: opts.stdio === 'pipe' ? 'pipe' : [...STREAM_TO_STDERR], ...(opts.env ? { env: opts.env } : {}), ...(opts.signal ? { signal: opts.signal } : {}), }) return { code: result.code, stdout: typeof result.stdout === 'string' ? result.stdout : '', stderr: typeof result.stderr === 'string' ? result.stderr : '', } } catch (e) { // A build tool that exits non-zero rejects with the spawn-result shape: a // numeric exit `code` plus captured stdout/stderr. Return it so the caller // can assemble failure records / surface the output. Anything else — e.g. a // missing executable, whose `code` is a string like 'ENOENT' — propagates. // This mirrors how utils/dlx.mts classifies spawn failures (a numeric `code` // is a real process exit); the registry's isSpawnError is avoided here // because it is currently broken and never matches. if ( e !== null && typeof e === 'object' && typeof (e as { code?: unknown }).code === 'number' ) { const err = e as { code: number; stdout?: unknown; stderr?: unknown } return { code: err.code, stdout: typeof err.stdout === 'string' ? err.stdout : '', stderr: typeof err.stderr === 'string' ? err.stderr : '', } } throw e } } async function writeSbtPlugin( globalBase: string, sourceFilename: string, destFilename: string, ): Promise { const src = await fs.readFile(manifestScriptsPath(sourceFilename), 'utf8') const pluginsDir = path.join(globalBase, 'plugins') await fs.mkdir(pluginsDir, { recursive: true }) await fs.writeFile(path.join(pluginsDir, destFilename), src) } async function assembleFromRecords( tool: BuildTool, out: RunOutput, recordsFile: string, ): Promise { return assembleRecords(tool, out, await readRecordsFile(recordsFile)) } async function readRecordsFile(recordsFile: string): Promise { return existsSync(recordsFile) ? await fs.readFile(recordsFile, 'utf8') : '' } function assembleRecords( tool: BuildTool, out: RunOutput, text: string, ): ManifestRunResult { const parsed = parseRecords(text) const factsFileName = socketFactsFileName(tool, parsed.entry || undefined) const { artifactPaths, facts, report } = assembleFacts(parsed) return { buildRoot: parsed.buildRoot || undefined, code: out.code, facts, factsFileName, report, artifactPaths, stderr: out.stderr, stdout: out.stdout, } } // Missing only in an unbuilt local checkout. Fail loudly: without the // extension, Maven silently emits an empty SBOM. function assertBundledAssetBuilt( assetPath: string, description: string, // The package.json script that builds it, as the dist build names it too. buildScript: string, ): void { if (existsSync(assetPath)) { return } throw new Error( `${description} not found at ${assetPath}. It is bundled in the published CLI; for local dev build it with: pnpm run ${buildScript}`, ) } // Runs the build-tool script (which emits a records file) and assembles it. // Writes no files; the caller persists facts or consumes artifactPaths. export async function runManifestScript( tool: BuildTool, opts: ManifestScriptOptions, ): Promise { switch (tool) { case 'dotnet': return await runDotnet(opts) case 'gradle': return await runGradle(opts) case 'sbt': return await runSbt(opts) case 'maven': return await runMaven(opts) } } // Emits only `project` records, never resolving dependencies, for discovery // before committing to a full `runManifestScript` resolution cost. export async function enumerateWorkspaces( tool: BuildTool, opts: ManifestScriptOptions, ): Promise { const result = await (tool === 'dotnet' ? runDotnet(opts, '--workspaces') : tool === 'gradle' ? enumerateGradleWorkspaces(opts) : tool === 'sbt' ? enumerateSbtWorkspaces(opts) : enumerateMavenWorkspaces(opts)) return { buildRoot: result.buildRoot, code: result.code, projects: result.facts.projects ?? [], stderr: result.stderr, stdout: result.stdout, } } // The options every build script reads, each in its own argument syntax. function scriptOptions( opts: ManifestScriptOptions, ): Array<[string, string | true]> { const options: Array<[string, string | true]> = [] if (opts.withFiles) { options.push(['withFiles', true]) } if (opts.populateFilesFor) { options.push(['populateFilesFor', opts.populateFilesFor]) } if (opts.includeConfigs) { options.push(['includeConfigs', opts.includeConfigs]) } if (opts.excludeConfigs) { options.push(['excludeConfigs', opts.excludeConfigs]) } // Globs compile to regex pattern sources HERE (exclude-paths-glob.mts is // the single glob implementation); the scripts just compile what they // receive. const excludePatterns = serializeExcludePathPatterns(opts.excludePaths) if (excludePatterns) { options.push(['excludePaths', excludePatterns]) options.push(['excludeBase', opts.excludeBase ?? opts.projectDir]) } return options } function commonProps( opts: ManifestScriptOptions, prefix: '-D' | '-P', ): string[] { return scriptOptions(opts).map( ({ 0: name, 1: value }) => `${prefix}socket.${name}=${value === true ? 'true' : value}`, ) } // The dotnet tool's flags are the kebab-cased script option names. function dotnetToolArgs(opts: ManifestScriptOptions): string[] { if (opts.populateFilesFor) { throw new Error('The dotnet manifest tool does not scope --with-files.') } return scriptOptions(opts).flatMap(({ 0: name, 1: value }) => { const flag = `--${camelToKebab(name)}` return value === true ? [flag] : [flag, value] }) } async function invokeGradle( opts: ManifestScriptOptions, initScriptFilename: string, task: string, tmpDirPrefix: string, ): Promise { const bin = resolveBuildToolBin( 'gradle', opts.projectDir, opts.bin, isStandaloneSea(), ) const initScript = manifestScriptsPath(initScriptFilename) return await withTmpDir(tmpDirPrefix, async tmp => { const recordsFile = path.join(tmp, 'records.tsv') // Disable the configuration cache: the init script's legacy // resolvedConfiguration API and shared accumulator aren't cache-safe. const args = [ '--init-script', initScript, '-Dorg.gradle.configuration-cache=false', // Names each artifact's own verification problem, so a checksum missing // from the metadata can be told apart from a mismatch. '-Porg.gradle.dependency.verification.console=verbose', `-Psocket.recordsFile=${recordsFile}`, ...commonProps(opts, '-P'), ...(opts.toolOpts ?? []), task, '--no-daemon', '--console=plain', ] const out = await runNeverThrow(bin, args, opts) return await assembleFromRecords('gradle', out, recordsFile) }) } async function runGradle( opts: ManifestScriptOptions, ): Promise { return await invokeGradle( opts, 'socket-facts.init.gradle', FACTS_TASK, 'socket-gradle-facts-', ) } async function enumerateGradleWorkspaces( opts: ManifestScriptOptions, ): Promise { return await invokeGradle( opts, 'socket-workspaces.init.gradle', WORKSPACES_TASK, 'socket-gradle-workspaces-', ) } async function invokeSbtIn( globalBase: string, opts: ManifestScriptOptions, pluginSourceFilename: string, pluginDestFilename: string, task: string, ): Promise { const bin = resolveBuildToolBin( 'sbt', opts.projectDir, opts.bin, isStandaloneSea(), ) await writeSbtPlugin(globalBase, pluginSourceFilename, pluginDestFilename) const recordsFile = path.join(globalBase, 'records.tsv') // The global base is shared across sbt roots: a build that dies before // writing must not be read as the previous root's records. await fs.rm(recordsFile, { force: true }) // Fresh per-run global base (not ~/.sbt): sbt executes everything under // plugins/, so a shared path is a code-injection surface. BSP off for this // run. sbt also provisions the project's Scala toolchain under // /boot; when opts.tmpDir was supplied, the caller keeps this // directory (and that toolchain) alive until it's done with withFiles' // artifactPaths, so no special-casing is needed here. const props = [ `-Dsbt.global.base=${globalBase}`, '-Dsbt.server.autostart=false', `-Dsocket.recordsFile=${recordsFile}`, ...commonProps(opts, '-D'), ] // sbt's launcher doesn't always honor JAVA_HOME; never override a // caller-supplied --java-home. const javaHome = opts.env?.['JAVA_HOME'] ?? process.env['JAVA_HOME'] const javaHomeOpt = javaHome && !(opts.toolOpts ?? []).includes('--java-home') ? ['--java-home', javaHome] : [] const args = [ ...javaHomeOpt, ...props, ...(opts.toolOpts ?? []), '--batch', task, ] const out = await runNeverThrow(bin, args, opts) return await assembleFromRecords('sbt', out, recordsFile) } async function runSbt(opts: ManifestScriptOptions): Promise { const run = (globalBase: string) => invokeSbtIn( globalBase, opts, 'socket-facts.plugin.scala', SBT_FACTS_PLUGIN_FILENAME, FACTS_TASK, ) if (opts.tmpDir) { return await run(opts.tmpDir) } return await withTmpDir('socket-sbt-facts-', run) } async function enumerateSbtWorkspaces( opts: ManifestScriptOptions, ): Promise { const run = (globalBase: string) => invokeSbtIn( globalBase, opts, 'socket-workspaces.plugin.scala', SBT_WORKSPACES_PLUGIN_FILENAME, WORKSPACES_TASK, ) if (opts.tmpDir) { return await run(opts.tmpDir) } return await withTmpDir('socket-sbt-workspaces-', run) } async function invokeMaven( opts: ManifestScriptOptions, coanaTask: string, tmpDirPrefix: string, ): Promise { const bin = resolveBuildToolBin( 'maven', opts.projectDir, opts.bin, isStandaloneSea(), ) const jarPath = manifestScriptsPath( 'maven-extension', 'coana-maven-extension.jar', ) assertBundledAssetBuilt( jarPath, 'Maven manifest extension jar', 'build:maven-extension', ) return await withTmpDir(tmpDirPrefix, async tmp => { const recordsFile = path.join(tmp, 'records.tsv') // `validate` is the cheapest phase that triggers the extension; no compile // needed (analysis uses configured paths, not classes). const props = [ `-Dmaven.ext.class.path=${jarPath}`, `-Dcoana.task=${coanaTask}`, `-Dsocket.recordsFile=${recordsFile}`, ...commonProps(opts, '-D'), ] const fileOpts = opts.entryFile ? ['--file', opts.entryFile] : [] const args = [ ...props, ...fileOpts, ...(opts.toolOpts ?? []), '--batch-mode', 'validate', ] const out = await runNeverThrow(bin, args, opts) return await assembleFromRecords('maven', out, recordsFile) }) } async function runMaven( opts: ManifestScriptOptions, ): Promise { return await invokeMaven(opts, 'socket-facts', 'socket-maven-facts-') } async function enumerateMavenWorkspaces( opts: ManifestScriptOptions, ): Promise { return await invokeMaven( opts, 'socket-workspaces', 'socket-maven-workspaces-', ) } // The global.json the dotnet host applies in `dir`: the first one in it or // any parent directory, the filesystem root included, which findUp skips. // https://github.com/dotnet/runtime/blob/b4548da6edfce1996a1d6ffe1521c9ce6128be2e/src/native/corehost/fxr/sdk_resolver.cpp#L296-L321 function nearestGlobalJson(dir: string): string { for (let current = path.resolve(dir); ; ) { const file = path.join(current, 'global.json') if (existsSync(file)) { return file } const parent = path.dirname(current) if (parent === current) { return '' } current = parent } } // Keyed by the nearest global.json, the only per-directory input to the // host's SDK selection; a failed probe is shared too. const sdkVersionByPin = new Map>() function dotnetSdkVersion( bin: string, opts: ManifestScriptOptions, ): Promise { // A relative path names a different host in each directory. const host = path.isAbsolute(bin) || path.basename(bin) === bin ? bin : path.resolve(opts.projectDir, bin) const key = `${host}\0${nearestGlobalJson(opts.projectDir)}` return getOrInsert(sdkVersionByPin, key, () => readDotnetSdkVersion(bin, opts), ) } async function readDotnetSdkVersion( bin: string, opts: ManifestScriptOptions, ): Promise { const out = await runNeverThrow(bin, ['--version'], { ...opts, stdio: 'pipe', }) if (out.code !== 0) { throw new Error( out.stderr.trim() || out.stdout.trim() || `\`${bin} --version\` exited with code ${out.code}`, ) } return out.stdout.trim() } // Runs the bundled tool against the build's own dotnet, in `mode` (none: a // full facts run), and returns its exit and records. async function invokeDotnetTool( opts: ManifestScriptOptions, mode: '--members' | '--workspaces' | undefined, ): Promise<{ out: RunOutput; records: string }> { if (!opts.entryFile) { throw new Error('A dotnet build needs a solution or project file.') } const toolDll = manifestScriptsPath('dotnet-tool', 'socket-facts-dotnet.dll') assertBundledAssetBuilt(toolDll, 'dotnet manifest tool', 'build:dotnet-tool') const bin = resolveBuildToolBin('dotnet', opts.projectDir, opts.bin) const sdkVersion = await dotnetSdkVersion(bin, opts) // The tool runs on the newest installed runtime (RollForward=LatestMajor), // which must be able to load the selected SDK's MSBuild; a preview SDK // needs a preview runtime, which roll-forward only picks when told to. const env = sdkVersion.includes('-') ? { ...(opts.env ?? process.env), DOTNET_ROLL_FORWARD_TO_PRERELEASE: '1', } : opts.env return await withTmpDir('socket-dotnet-facts-', async tmp => { const recordsFile = path.join(tmp, 'records.tsv') const args = [ toolDll, '--records', recordsFile, '--entry', opts.entryFile!, '--dotnet', bin, ...(mode ? [mode] : []), ...dotnetToolArgs(opts), ...(opts.stdio === 'inherit' ? ['--verbose'] : []), '--', ...(opts.toolOpts ?? []), ] const out = await runNeverThrow(bin, args, { ...opts, env }) return { out, records: await readRecordsFile(recordsFile) } }) } async function runDotnet( opts: ManifestScriptOptions, mode?: '--workspaces' | undefined, ): Promise { const { out, records } = await invokeDotnetTool(opts, mode) return assembleRecords('dotnet', out, records) } const entryProjectsByRun = new Map>() // Undefined when the SDK cannot read the entry (a .slnx before SDK 9.0.200); // empty when the listing fails, which the build itself then reports. export function listDotnetEntryProjects( opts: ManifestScriptOptions, ): Promise { const key = JSON.stringify([ opts.bin, opts.projectDir, opts.entryFile, opts.excludePaths, opts.excludeBase, opts.toolOpts, ]) return getOrInsert(entryProjectsByRun, key, () => readDotnetEntryProjects(opts), ) } async function readDotnetEntryProjects( opts: ManifestScriptOptions, ): Promise { let listing try { listing = await invokeDotnetTool({ ...opts, stdio: 'pipe' }, '--members') } catch { return [] } const { out, records } = listing if (out.code !== 0) { return [] } const parsed = parseRecords(records) if (parsed.failures.length) { return undefined } return parsed.members.map(m => path.resolve(opts.projectDir, m)) }