import path from 'node:path' import { logger } from '@socketsecurity/registry/lib/logger' import { assertValidExcludePaths } from './exclude-paths.mts' import { handleScanReach } from './handle-scan-reach.mts' import { resolveReachAdvisories } from './reach-advisories.mts' import { DYNAMIC_SBOM_INFERENCE_DESCRIPTION, dynamicSbomInferenceEcosystemsFlags, excludePathsFlag, parseDynamicSbomInferenceFlags, reachabilityFlags, } from './reachability-flags.mts' import { suggestTarget } from './suggest_target.mts' import { validateReachabilityTarget } from './validate-reachability-target.mts' import { warnSocketJsonOnlyFlags } from './warn-socket-json-only-flags.mts' import constants from '../../constants.mts' import { commonFlags, outputFlags } from '../../flags.mts' import { checkCommandInput } from '../../utils/check-input.mts' import { cmdFlagValueToArray } from '../../utils/cmd.mts' import { determineOrgSlug } from '../../utils/determine-org-slug.mts' import { parseReachEcosystems } from '../../utils/ecosystem.mts' import { getOutputKind } from '../../utils/get-output-kind.mts' import { meowOrExit } from '../../utils/meow-with-subcommands.mts' import { getFlagApiRequirementsOutput, getFlagListOutput, } from '../../utils/output-formatting.mts' import { hasDefaultApiToken } from '../../utils/sdk.mts' import type { MeowFlags } from '../../flags.mts' import type { CliCommandConfig, CliCommandContext, } from '../../utils/meow-with-subcommands.mts' export const CMD_NAME = 'reach' const description = 'Compute full application reachability' const hidden = false // Not in reachabilityFlags: on `scan create` it is a general flag the --reach // guard must not reject. Reachability is always on here, so the description // drops that command's --reach caveat. const reachabilityFlagsForReach: MeowFlags = { ...reachabilityFlags, dynamicSbomInference: { type: 'boolean', default: false, description: `${DYNAMIC_SBOM_INFERENCE_DESCRIPTION} The reachability analysis is split per project/module accordingly.`, }, ...dynamicSbomInferenceEcosystemsFlags, // Fallback targets scan creation, which this command never performs. reachFallbackToRegularScan: { type: 'boolean', default: false, hidden: true, description: 'No-op: only `socket scan create --reach` falls back to a regular SCA scan on reachability failure.', }, } const generalFlags: MeowFlags = { ...commonFlags, ...outputFlags, cwd: { type: 'string', default: '', description: 'working directory, defaults to process.cwd()', }, org: { type: 'string', default: '', description: 'Force override the organization slug, overrides the default org from config', }, output: { type: 'string', default: '', description: 'Path to write the reachability report to (must end with .json). Defaults to .socket.facts.json in the current working directory.', shortFlag: 'o', }, } export const cmdScanReach = { description, hidden, run, } async function run( argv: string[] | readonly string[], importMeta: ImportMeta, { parentName }: CliCommandContext, ): Promise { const config: CliCommandConfig = { commandName: CMD_NAME, description, hidden, flags: { ...generalFlags, ...excludePathsFlag, ...reachabilityFlagsForReach, }, help: command => ` Usage $ ${command} [options] [CWD=.] API Token Requirements ${getFlagApiRequirementsOutput(`${parentName}:${CMD_NAME}`)} Options ${getFlagListOutput(generalFlags)} Reachability Options ${getFlagListOutput({ ...excludePathsFlag, ...reachabilityFlagsForReach })} Runs the Socket reachability analysis without creating a scan in Socket. The output is written to .socket.facts.json in the current working directory unless the --output flag is specified. Note: Manifest files are uploaded to Socket's backend services because the reachability analysis requires creating a Software Bill of Materials (SBOM) from these files before the analysis can run. Examples $ ${command} $ ${command} ./proj $ ${command} ./proj --reach-ecosystems npm,pypi $ ${command} ./monorepo --dynamic-sbom-inference $ ${command} --output custom-report.json $ ${command} ./proj --output ./reports/analysis.json `, } const cli = meowOrExit({ argv, config, importMeta, parentName, }) warnSocketJsonOnlyFlags(cli.flags, `${parentName} ${CMD_NAME}`) const { cwd: cwdOverride, interactive = true, json, markdown, org: orgFlag, output: outputPath, reachAnalysisMemoryLimit, reachAnalysisTimeout, reachConcurrency, reachContinueOnAnalysisErrors, reachContinueOnInstallErrors, reachContinueOnMissingLockFiles, reachContinueOnNoSourceFiles, reachDebug, reachDetailedAnalysisLogFile, reachDisableAnalysisSplitting: _reachDisableAnalysisSplitting, reachDisableAnalytics, reachDisableDependencyDownloads, reachDisableExternalToolChecks, reachEnableAnalysisSplitting, reachLazyMode: _reachLazyMode, reachRetainFactsFile, reachSkipCache, reachUseOnlyPregeneratedSboms, reachVersion, } = cli.flags as { cwd: string interactive: boolean json: boolean markdown: boolean org: string output: string reachAnalysisMemoryLimit: string reachAnalysisTimeout: string reachConcurrency: number reachContinueOnAnalysisErrors: boolean reachContinueOnInstallErrors: boolean reachContinueOnMissingLockFiles: boolean reachContinueOnNoSourceFiles: boolean reachDebug: boolean reachDetailedAnalysisLogFile: boolean reachDisableAnalysisSplitting: boolean reachDisableAnalytics: boolean reachDisableDependencyDownloads: boolean reachDisableExternalToolChecks: boolean reachEnableAnalysisSplitting: boolean reachLazyMode: boolean reachRetainFactsFile: boolean reachSkipCache: boolean reachUseOnlyPregeneratedSboms: boolean reachVersion: string | undefined } const dryRun = !!cli.flags['dryRun'] // Process comma-separated values for isMultiple flags. const excludePaths = cmdFlagValueToArray(cli.flags['excludePaths']) const reachAdvisoriesRaw = cmdFlagValueToArray(cli.flags['reachAdvisories']) const reachEcosystemsRaw = cmdFlagValueToArray(cli.flags['reachEcosystems']) const reachExcludePaths = cmdFlagValueToArray(cli.flags['reachExcludePaths']) assertValidExcludePaths(excludePaths) // Validate ecosystem values against the reachability-supported set. const reachEcosystems = parseReachEcosystems(reachEcosystemsRaw) const dynamicSbomInference = parseDynamicSbomInferenceFlags(cli.flags) const processCwd = process.cwd() const cwd = cwdOverride && cwdOverride !== '.' && cwdOverride !== processCwd ? path.resolve(processCwd, cwdOverride) : processCwd // Accept zero or more paths. Default to cwd() if none given. let targets = cli.input.length ? cli.input : [cwd] // Use suggestTarget if no targets specified and in interactive mode if (!targets.length && !dryRun && interactive) { targets = await suggestTarget() } const { 0: orgSlug } = await determineOrgSlug(orgFlag, interactive, dryRun) const hasApiToken = hasDefaultApiToken() const outputKind = getOutputKind(json, markdown) // Validate target constraints for reachability analysis. const targetValidation = await validateReachabilityTarget(targets, cwd) const wasValidInput = checkCommandInput( outputKind, { nook: true, test: !!orgSlug, message: 'Org name by default setting, --org, or auto-discovered', fail: 'missing', }, { nook: true, test: dryRun || hasApiToken, message: 'This command requires an API token for access', fail: 'try `socket login`', }, { nook: true, test: !json || !markdown, message: 'The json and markdown flags cannot be both set, pick one', fail: 'omit one', }, { nook: true, test: !outputPath || outputPath.endsWith('.json'), message: 'The --output path must end with .json', fail: 'use a path ending with .json', }, { nook: true, test: targetValidation.isValid, message: 'Reachability analysis requires exactly one target directory', fail: 'provide exactly one directory path', }, { nook: true, test: targetValidation.isDirectory, message: 'Reachability analysis target must be a directory', fail: 'provide a directory path, not a file', }, { nook: true, test: targetValidation.targetExists, message: 'Target directory must exist', fail: 'provide an existing directory path', }, { nook: true, test: targetValidation.isInsideCwd, message: 'Target directory must be inside the current working directory', fail: 'provide a path inside the working directory', }, ) if (!wasValidInput) { return } if (dryRun) { logger.log(constants.DRY_RUN_BAILING_NOW) return } const reachAdvisories = await resolveReachAdvisories(reachAdvisoriesRaw) await handleScanReach({ cwd, interactive, orgSlug, outputKind, outputPath: outputPath || '', reachabilityOptions: { dynamicSbomInference, excludePaths, reachAdvisories, reachAnalysisMemoryLimit, reachAnalysisTimeout, reachConcurrency: Number(reachConcurrency), reachContinueOnAnalysisErrors: Boolean(reachContinueOnAnalysisErrors), reachContinueOnInstallErrors: Boolean(reachContinueOnInstallErrors), reachContinueOnMissingLockFiles: Boolean(reachContinueOnMissingLockFiles), reachContinueOnNoSourceFiles: Boolean(reachContinueOnNoSourceFiles), reachDebug: Boolean(reachDebug), reachDetailedAnalysisLogFile: Boolean(reachDetailedAnalysisLogFile), reachDisableAnalytics: Boolean(reachDisableAnalytics), reachDisableDependencyDownloads: Boolean(reachDisableDependencyDownloads), reachDisableExternalToolChecks: Boolean(reachDisableExternalToolChecks), reachEcosystems, reachEnableAnalysisSplitting: Boolean(reachEnableAnalysisSplitting), reachExcludePaths, reachRetainFactsFile: Boolean(reachRetainFactsFile), reachSkipCache: Boolean(reachSkipCache), reachUseOnlyPregeneratedSboms: Boolean(reachUseOnlyPregeneratedSboms), reachVersion, }, targets, }) }