The AST CLI JavaScript Wrapper Runtime CLI is a Node.js/TypeScript library that provides a wrapper layer for the Checkmarx AST (Application Security Testing) CLI. It enables JavaScript developers to interact with the AST CLI programmatically, abstracting the CLI interface and providing a type-safe, well-structured API.
Status: Active development and maintenance
Package: @Checkmarx/ast-cli-javascript-wrapper-runtime-cli
Repository: https://github.com/Checkmarx/ast-cli-javascript-wrapper-runtime-cli
This wrapper serves as a bridge between JavaScript/Node.js applications and the AST CLI binary, handling:
- AST CLI binary installation and version management
- Configuration management (credentials, endpoints, proxy settings)
- Execution and output parsing
- Error handling and logging
- Support for multiple security scanning features (SAST, SCA, KICS, ASCA, etc.)
The project follows a modular architecture with clear separation of concerns:
CxWrapper (Main Entry Point)
├── CxConfig (Configuration Management)
├── CxInstaller (Binary Installation & Management)
├── ExecutionService (CLI Execution)
├── AstClient (HTTP Client for Downloads)
└── Feature Modules
├── Scan (CxScan)
├── Project (CxProject)
├── Results (CxResult, CxData, etc.)
├── SAST (via CxResult)
├── SCA (CxScaRealTime, CxScaPackageData)
├── KICS (CxKicsRealTime, CxKicsRemediation)
├── ASCA (CxAsca)
├── BFL (CxBFL)
├── Mask (CxMask, CxMaskedSecret)
├── Chat (CxChat)
└── Other Features (CodeBashing, LearnMore, Predicates)
- Multiton Pattern:
CxWrapperuses instance pooling to manage multiple wrapper instances - Semaphore Pattern: Thread-safe execution with async-mutex for concurrent operations
- Configuration Pattern: Centralized configuration through
CxConfig - Service Locator: Feature modules accessed through the main wrapper instance
.
├── src/
│ ├── main/ # Main source code
│ │ ├── wrapper/ # Core wrapper and execution engine
│ │ │ ├── CxWrapper.ts # Main wrapper class
│ │ │ ├── CxWrapperFactory.ts # Wrapper instance factory
│ │ │ ├── CxConfig.ts # Configuration management
│ │ │ ├── CxConstants.ts # Constants
│ │ │ ├── ExecutionService.ts
│ │ │ ├── CxCommandOutput.ts
│ │ │ ├── CxParamType.ts
│ │ │ └── loggerConfig.ts
│ │ ├── client/ # HTTP client
│ │ │ └── AstClient.ts # Download and HTTP utilities
│ │ ├── osinstaller/ # Binary installation
│ │ │ └── CxInstaller.ts
│ │ ├── errors/ # Custom error types
│ │ │ └── CxError.ts
│ │ ├── scan/ # Scan operations
│ │ │ └── CxScan.ts
│ │ ├── project/ # Project management
│ │ │ └── CxProject.ts
│ │ ├── results/ # Scan results handling
│ │ │ ├── CxResult.ts
│ │ │ ├── CxData.ts
│ │ │ ├── CxCvss.ts
│ │ │ ├── CxNode.ts
│ │ │ ├── CxDependencyPaths.ts
│ │ │ ├── CxPackageData.ts
│ │ │ ├── CxScaPackageData.ts
│ │ │ ├── CxResultType.ts
│ │ │ └── CxVulnerabilityDetails.ts
│ │ ├── scaRealtime/ # Software Composition Analysis
│ │ │ ├── CxScaRealTime.ts
│ │ │ └── CxScaRealTimeErrors.ts
│ │ ├── kicsRealtime/ # KICS (Infrastructure as Code Scanning)
│ │ │ └── CxKicsRealTime.ts
│ │ ├── asca/ # Application Security Code Analysis
│ │ │ ├── CxAsca.ts
│ │ │ └── AscaScanDetail.ts
│ │ ├── remediation/ # Remediation suggestions
│ │ │ └── CxKicsRemediation.ts
│ │ ├── bfl/ # Business Flow Language
│ │ │ └── CxBFL.ts
│ │ ├── mask/ # Secret masking
│ │ │ ├── CxMask.ts
│ │ │ └── CxMaskedSecret.ts
│ │ ├── chat/ # Chat integration
│ │ │ └── CxChat.ts
│ │ ├── codebashing/ # CodeBashing integration
│ │ │ └── CxCodeBashing.ts
│ │ ├── learnmore/ # Learning resources
│ │ │ ├── CxLearnMoreDescriptions.ts
│ │ │ └── CxLearnMoreSamples.ts
│ │ └── predicates/ # Predicate operations
│ │ └── CxPredicate.ts
│ └── tests/
│ ├── *.test.ts # Test files (AuthTest, ChatTest, MaskTest, etc.)
│ ├── unit/ # Additional unit tests
│ └── data/ # Test fixtures and data
├── dist/ # Compiled JavaScript output
├── coverage/ # Code coverage reports
├── .github/workflows/ # GitHub Actions CI/CD
├── tsconfig.json # TypeScript configuration
├── jest.config.js # Jest test configuration
├── package.json # NPM package configuration
├── README.md # User-facing documentation
└── CLAUDE.md # This file
- Language: TypeScript 5.6.3
- Runtime: Node.js (ES2015 target)
- Module System: CommonJS (compiled from TypeScript)
- Compiler: TypeScript 5.6.3
- Build Process: tsc (TypeScript compiler)
- Build Output:
dist/directory with source maps
- Test Framework: Jest 29.7.0
- Test Runner Configuration: ts-jest
- Mocking: ts-mockito 2.6.1
- Coverage Threshold: Lines 80%, Functions 80%, Branches 60%, Statements 80%
- Linter: ESLint 8.57.1
- Parser: @typescript-eslint/parser 5.29.0
- Plugins: @typescript-eslint/eslint-plugin 5.29.0
- Preset: eslint:recommended + typescript-eslint recommended
- async-mutex: ^0.5.0 - Synchronization primitives for async code
- azure-pipelines-tool-lib: ^2.0.8 - Azure Pipelines tools (file downloads, caching)
- https-proxy-agent: ^7.0.6 - Proxy support for HTTPS requests
- log4js: ^6.9.1 - Structured logging
- node-fetch: ^3.3.2 - Fetch API for Node.js
- tar: ^7.5.11 - TAR archive handling
- unzipper: ^0.12.3 - ZIP archive extraction
- tunnel: (direct import in AstClient) - HTTPS over HTTP tunneling for proxies (should be added as direct dependency)
- Babel: @babel/core, @babel/preset-typescript, @babel/preset-env - Code transformation
- Type Definitions: @types/node, @types/jest, @types/adm-zip, @types/tunnel, @types/unzipper
- Transpilation: babel-jest 29.7.0
- File Utilities: copyfiles 2.4.1
- Node.js: 14.x or higher (LTS recommended)
- npm: 6.x or higher
- Git: For version control
-
Clone the repository
git clone https://github.com/Checkmarx/ast-cli-javascript-wrapper-runtime-cli.git cd ast-cli-javascript-wrapper-runtime-cli -
Install dependencies
npm ci
-
Verify installation
npm run build
- Build:
npm run build- Compiles TypeScript to JavaScript - Build with postbuild: Automatically copies test data to dist
- Lint:
npm run lint- Check code style and issues - Lint & Fix:
npm run lint-and-fix- Auto-fix linting issues - Test:
npm run test- Run all tests with coverage - Unit Tests Only:
npm run test:unit- Run unit tests without coverage
For integration tests, set these environment variables:
Linux/macOS:
export CX_CLIENT_ID="your-client-id"
export CX_CLIENT_SECRET="your-client-secret"
export CX_APIKEY="your-api-key"
export CX_BASE_URI="https://ast.checkmarx.net"
export CX_BASE_AUTH_URI="https://auth.checkmarx.net"
export CX_TENANT="your-tenant"
export PATH_TO_EXECUTABLE="/path/to/ast-cli"Windows PowerShell:
setx CX_CLIENT_ID "your-client-id"
setx CX_CLIENT_SECRET "your-client-secret"
setx CX_APIKEY "your-api-key"
setx CX_BASE_URI "https://ast.checkmarx.net"
setx CX_BASE_AUTH_URI "https://auth.checkmarx.net"
setx CX_TENANT "your-tenant"
setx PATH_TO_EXECUTABLE "C:\path\to\ast-cli.exe"- Target: ES2015
- Module: CommonJS
- Declaration Files: Generated automatically
- Source Maps: Enabled for debugging
- Strict Settings:
noImplicitAny: true - All types must be explicitforceConsistentCasingInFileNames: truenoUnusedLocals: true - No unused variables allowed
-
Naming Conventions:
- Classes: PascalCase (e.g.,
CxWrapper,AstClient) - Functions/Methods: camelCase (e.g.,
downloadFile,createProxyRequestHandler) - Constants: UPPER_SNAKE_CASE (e.g.,
MAX_ATTEMPTS,DEFAULT_TIMEOUT) - Private members: Prefix with
_or use TypeScriptprivatekeyword - Interfaces: PrefixCamelCase or I-prefix (e.g.,
CxConfig,IConfigurable)
- Classes: PascalCase (e.g.,
-
File Organization:
- One main class per file (named matching the file)
- Related types/interfaces in the same file as the main class
- Imports grouped: external, then relative imports
- Exports at end of file
-
Formatting:
- 2-space indentation (configured in ESLint)
- 120-character line length (soft limit)
- Trailing commas in multi-line structures
- Single quotes for strings (no template literals unless needed)
- Prefer
constoverlet, avoidvar
- JSDoc Comments: Use for public APIs and complex logic
- Inline Comments: Only for non-obvious implementation details
- No Over-Documentation: Self-documenting code is preferred; comments explain WHY, not WHAT
- Use ES6 module syntax
- Explicit imports (no wildcard imports unless necessary)
- Named exports preferred for multiple exports per file
- Default export for main class per module
- Always throw
CxErrorfor custom errors - Wrap external errors with context information
- Log errors before throwing (use
loggerfrom loggerConfig) - Include stack traces in logs for debugging
-
Never Commit Secrets
- No API keys, tokens, or credentials in code
- Use environment variables and
.gitignorefor sensitive data - Review all commits for accidental secret inclusion
-
Proxy Support is Mandatory
- All HTTP requests must respect
HTTP_PROXYenvironment variable - Use
AstClientfor downloads with proxy support - Test proxy scenarios in PR reviews
- All HTTP requests must respect
-
Type Safety First
- No
anytypes without explicit justification - Strict TypeScript compilation required
- Use discriminated unions and type guards where possible
- No
-
Test Coverage Requirements
- Minimum 80% line coverage required (enforced by Jest)
- 60% branch coverage minimum
- New features must include unit tests
- Integration tests for CLI interactions
-
No Breaking Changes Without Review
- Document API changes in PR description
- Semver versioning: MAJOR.MINOR.PATCH
- Deprecation period for major changes
-
Async/Await for Concurrency
- Use
async/awaitinstead of callbacks - Respect
CxWrappersemaphore for CLI execution - No concurrent CLI invocations without synchronization
- Use
-
Dependency Management
- Use npm for all dependency management
- Override rules in package.json for security patches
- Minimize external dependencies
- TypeScript compilation succeeds (
npm run build) - All tests pass (
npm run test) - ESLint passes (
npm run lint) - Coverage thresholds met
- No console.log statements (use logger)
- No hardcoded paths or credentials
- Base all work on
mainbranch - Feature branch naming:
feature/description,fix/issue-description - Commit messages: descriptive and present tense
- Squash commits before merge when appropriate
- Require PR review before merging to main
Tests are located in src/tests/ with the following structure:
*.test.ts- Test files for individual modules (AuthTest, ChatTest, MaskTest, ProjectTest, ResultTest, ScanTest, etc.)unit/- Additional unit testsdata/- Test fixtures and mock data (copied to dist during build)
# Run all tests with coverage
npm run test
# Run unit tests only (no coverage)
npm run test:unit
# Run specific test file
npm run test -- --testPathPattern=CxWrapper
# Watch mode
npm run test -- --watch- Lines: 80%
- Functions: 80%
- Branches: 60%
- Statements: 80%
-
Use ts-mockito for Mocking
- Mock external dependencies (AstClient, ExecutionService)
- Verify method calls and arguments
- Avoid mocking internal state when possible
-
Test Data Management
- Store test fixtures in
src/tests/data/ - Reference fixtures with relative paths
- Keep fixtures small and focused
- Document fixture purpose with comments
- Store test fixtures in
-
Async Testing
- Use
async/awaitin test functions - Handle rejections properly
- Don't forget to await promises
- Use
-
Environment Variables
- Mock via
process.envbefore tests - Restore original values after tests
- Document required env vars in tests
- Mock via
-
Error Cases
- Test both success and failure paths
- Verify error messages and types
- Test timeout scenarios where applicable
-
Single AST CLI Binary Per Process
- Only one version of AST CLI can be active at a time
- Downloading a different version replaces the existing one
- Multiple parallel scans must use the same CLI version
-
Proxy Configuration
- Only
HTTP_PROXYenvironment variable is supported HTTPS_PROXYandNO_PROXYnot yet implemented- Proxy authentication requires URL-encoded credentials
- Only
-
Cross-Platform Binary Management
- Binary installation varies by OS (Windows, Linux, macOS)
- Resource paths are OS-specific
- Testing cross-platform scenarios is challenging in CI
-
CLI Version Management
- No automatic version resolution
- Must specify exact version or use PATH_TO_EXECUTABLE
- Version mismatches may cause unexpected behavior
-
Semaphore Bottleneck
- Single semaphore slot limits concurrent CLI executions
- Sequential execution may impact performance
- Blocking design for thread safety
- Version Issues: Pin specific CLI versions in consumer applications
- Proxy Support: Use corporate proxy at OS level as fallback
- Cross-Platform: Test on multiple OS before releases
- Concurrency: Queue scan requests externally if parallelism needed
The package is published to GitHub Packages (npm.pkg.github.com):
{
"publishConfig": {
"registry": "https://npm.pkg.github.com"
}
}- Update version in
package.json - Merge to main with PR approval
- Tag release:
git tag v1.0.x - Push tags:
git push origin --tags - GitHub Actions release workflow handles publication
- File:
checkmarx-ast-cli.version- Tracks CLI version - Format: Simple text file with version string
- Location: Root directory
- Usage: Referenced by CxInstaller for binary management
Located in .github/workflows/:
ci.yml- Runs on every push and PRrelease.yml- Creates releases and publishes packagecheckmarx-one-scan.yml- Security scanning on PRsupdate-cli.yml- Updates AST CLI binary referencenightly.yml- Nightly build and test runauto-merge-pr.yml- Auto-merges dependency updatesdependabot-auto-merge.yml- Dependabot PR automationdelete-packages-and-releases.yml- Deletes old packages and releasespr-automation.yml- Pull request automation
The main external dependency is the Checkmarx AST CLI binary:
- Purpose: Performs actual security scanning
- Installation: Automatic via CxInstaller
- Configuration: Through CxConfig environment variables
- API: Command-line interface with JSON output parsing
- Library: azure-pipelines-tool-lib
- Usage: File downloading, caching, tool management
- Benefit: Handles retries and proxy automatically
- Actions: CI/CD automation
- Packages: NPM package hosting
- Releases: Automated version tagging and release notes
-
Binary Caching
- AST CLI binary cached after download
- Reused across multiple scans in same process
- Reduces download time for subsequent runs
-
Lazy Loading
- Feature modules loaded on-demand
- Reduces initial memory footprint
- Only required modules instantiated
-
Async Execution
- CLI execution non-blocking
- Multiple scans queued (not parallel)
- Prevents resource exhaustion
-
Retry Logic
- AstClient implements exponential backoff
- Max 3 attempts for downloads by default
- Configurable retry interval (2 seconds)
- CLI Execution: Sequential (semaphore-limited)
- Download Speed: Network-dependent
- Disk I/O: Binary extraction and resource copying
- JSON Parsing: Large result sets
- Logger: log4js provides timing information
- Coverage: Jest reports execution time
- No Built-in Metrics: Use external APM for production
class CxWrapper {
static async getInstance(cxScanConfig: CxConfig, logFilePath: string): Promise<CxWrapper>
config: CxConfig
cxInstaller: CxInstaller
// Scan methods
scanCreate(params: CxParamType[]): Promise<CxCommandOutput>
scanCancel(params: CxParamType[]): Promise<CxCommandOutput>
scanShow(params: CxParamType[]): Promise<CxCommandOutput>
scanList(params: CxParamType[]): Promise<CxCommandOutput>
// Other feature methods accessed through instance
}Each feature module exports a main class following the Cx[Feature] naming convention:
CxScan- Scan operationsCxProject- Project managementCxResult- Result parsingCxScaRealTime- SCA real-time scanningCxKicsRealTime- KICS real-time scanningCxAsca- Application Security Code AnalysisCxBFL- Business Flow LanguageCxMask- Secret maskingCxChat- Chat functionalityCxCodeBashing- CodeBashing integrationCxLearnMoreDescriptions/CxLearnMoreSamples- Learning resourcesCxPredicate- Predicate operationsCxKicsRemediation- KICS remediation suggestions
Main configuration object properties:
apiKey: API key for authenticationclientId+clientSecret: OAuth credentialsbaseUri: AST API endpointbaseAuthUri: Authentication endpointtenant: Tenant identifierpathToExecutable: Path to AST CLI binaryadditionalParameters: Extra CLI arguments
-
API Key (recommended for CI/CD)
const config = new CxConfig(); config.apiKey = process.env.CX_APIKEY;
-
OAuth 2.0 Client Credentials
config.clientId = process.env.CX_CLIENT_ID; config.clientSecret = process.env.CX_CLIENT_SECRET;
- Never commit credentials to the repository
- Use environment variables or secure vaults
- Rotate credentials regularly
- Use service accounts for CI/CD
- HTTP_PROXY environment variable support
- URL-encoded authentication in proxy URL
- HTTPS tunneling for encrypted communication
- Error handling for invalid proxy URLs
- All HTTPS endpoints require valid certificates
- Certificate validation cannot be disabled
- Self-signed certificates will fail
- Configure corporate CA if needed
- Enforced by AST API
- Client credentials determine accessible projects/scans
- API key permissions managed in Checkmarx platform
- Wrapper does not implement additional RBAC
- All operations logged via log4js
- Configurable log levels (debug, info, warn, error)
- Sensitive data (credentials) never logged
- Logs can be written to file or stdout
Located in src/main/wrapper/loggerConfig.ts:
import { getLoggerWithFilePath, logger } from './loggerConfig';
// Default logger
logger.info('Message');
logger.error('Error message');
logger.debug('Debug message');
// File-based logger
getLoggerWithFilePath('/path/to/logfile.log');- DEBUG: Detailed internal operations
- INFO: Important events (started scan, downloaded CLI)
- WARN: Potentially problematic situations
- ERROR: Error conditions requiring attention
- FATAL: Unrecoverable errors
- Default Output: Console (stdout/stderr)
- File Output: Optional via
getLoggerWithFilePath() - Appenders: Configurable in loggerConfig
- Layout: Timestamp, level, category, message
- Use appropriate log level for context
- Include relevant contextual information
- Never log sensitive data (credentials, tokens)
- Use logger instance, not console.log
- Consider performance impact of debug logging
import log4js from 'log4js';
// Configure debug level
log4js.configure({
appenders: { console: { type: 'console' } },
categories: { default: { appenders: ['console'], level: 'debug' } }
});
const wrapper = await CxWrapper.getInstance(config);Issue: CxInstaller cannot locate the AST CLI binary
Solutions:
- Ensure PATH_TO_EXECUTABLE points to valid binary
- Check PATH environment variable includes binary location
- On Windows, verify binary is not blocked (Properties > Unblock)
- Try re-downloading: delete cached binary and reinitialize
Issue: HTTP_PROXY environment variable set but not working
Solutions:
- Verify proxy URL format: http://[user:pass@]host:port
- Test proxy manually: curl -x [proxy] https://google.com
- Check proxy authentication (username/password encoding)
- Ensure https-proxy-agent configuration is correct
Issue: Invalid credentials or endpoint configuration
Solutions:
- Verify CX_CLIENT_ID and CX_CLIENT_SECRET are set
- Or verify CX_APIKEY is set (not both)
- Ensure CX_BASE_AUTH_URI and CX_BASE_URI are correct
- Check credentials haven't expired in Checkmarx platform
- Verify tenant configuration matches Checkmarx setup
Issue: CLI execution blocked by semaphore (another scan in progress)
Solutions:
- Wait for previous scans to complete
- Check for hung processes: ps aux | grep ast-cli
- Restart Node.js process if hung
- Consider queuing scans externally if parallelism needed
Issue: TypeScript strict mode errors
Solutions:
- Avoid casting to 'any'
- Create specific types/interfaces
- Use type guards or discriminated unions
- Check types in dependent modules
-
Enable Verbose Logging
getLoggerWithFilePath('./debug.log'); // Logs will show detailed execution flow
-
Use Node Debugger
node --inspect-brk dist/main/wrapper/CxWrapper.js # Opens Chrome DevTools debugging interface -
Inspect Configuration
const wrapper = await CxWrapper.getInstance(config); console.log('Config:', wrapper.config); console.log('CLI Path:', wrapper.cxInstaller.getExecutablePath());
-
Test CLI Directly
# Run AST CLI directly to isolate wrapper issues /path/to/ast-cli version /path/to/ast-cli scan help
-
Check Environment Variables
# Unix env | grep CX_ env | grep HTTP_PROXY # PowerShell Get-ChildItem env: | Where-Object { $_.Name -like 'CX_*' -or $_.Name -like '*PROXY*' }
Create .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Tests",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["--runInBand"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}Then press F5 to start debugging.
- Create feature branch from
main - Open Pull Request with clear description
- Ensure all checks pass (CI, coverage, lint)
- Request review from CODEOWNERS
- Merge only after approval
Primary maintainer: @cx-anurag-dalke
For PR reviews, mention codeowner for faster turnaround.
- Follow coding standards outlined above
- Add tests for new features
- Update documentation for API changes
- Keep commits atomic and descriptive
- Avoid committing build artifacts
- Update
package.jsonversion (semver) - Update
checkmarx-ast-cli.versionif CLI version changes - Merge to
mainwith PR - Tag release:
git tag v1.0.x - GitHub Actions handles publication
- Automated via Dependabot
- Auto-merge enabled for patch updates
- Manual review required for minor/major
- Security vulnerabilities trigger immediate PRs
- GitHub Repo: https://github.com/Checkmarx/ast-cli-javascript-wrapper-runtime-cli
- Issue Tracker: https://github.com/Checkmarx/ast-cli-javascript-wrapper-runtime-cli/issues
- Package: https://github.com/CheckmarxDev/packages?repo_name=ast-cli-javascript-wrapper-runtime-cli
- AST CLI: https://github.com/Checkmarx/ast-cli (main CLI binary)
- AST VSCode Extension: https://github.com/Checkmarx/ast-vscode-extension
- See README.md for user-facing usage documentation
- TypeScript/JavaScript docs in source code comments
- Type definitions in
dist/main/**/*.d.ts
- Checkmarx: https://checkmarx.com
- Security Issues: Follow responsible disclosure
npm run build # Compile TypeScript
npm run lint # Check code style
npm run lint-and-fix # Auto-fix issues
npm run test # Run all tests with coverage
npm run test:unit # Run unit tests only- Main Class:
src/main/wrapper/CxWrapper.ts - Configuration:
src/main/wrapper/CxConfig.ts - Installation:
src/main/osinstaller/CxInstaller.ts - Client:
src/main/client/AstClient.ts - Logging:
src/main/wrapper/loggerConfig.ts
import { CxWrapper } from '@Checkmarx/ast-cli-javascript-wrapper-runtime-cli';
import { CxConfig } from '@Checkmarx/ast-cli-javascript-wrapper-runtime-cli';
import { CxError } from '@Checkmarx/ast-cli-javascript-wrapper-runtime-cli';Last Updated: 2026-04-22 Version: Matches ast-cli-javascript-wrapper-runtime-cli v1.0.36