CLI for Socket.dev security analysis
pnpm install -g socket
socket --help
socket npm [args...]
/socket npx [args...]
- Wrap npm/npx with security scanningsocket pnpm [args...]
/socket yarn [args...]
- Wrap pnpm/yarn with security scanningsocket pip [args...]
- Wrap pip with security scanningsocket scan
- Create and manage security scanssocket package <name>
- Analyze package security scoressocket fix
- Fix CVEs in dependenciessocket optimize
- Optimize dependencies with@socketregistry
overridessocket cdxgen [command]
- Run cdxgen for SBOM generation
socket organization
(alias:org
) - Manage organization settingssocket repository
(alias:repo
) - Manage repositoriessocket dependencies
(alias:deps
) - View organization dependenciessocket audit-log
(alias:audit
) - View audit logssocket analytics
- View organization analyticssocket threat-feed
(alias:feed
) - View threat intelligence
socket login
- Authenticate with Socket.devsocket logout
- Remove authenticationsocket whoami
- Show authenticated usersocket config
- Manage CLI configuration
All aliases support the flags and arguments of the commands they alias.
socket ci
- Alias forsocket scan create --report
(creates report and exits with error if unhealthy)socket org
- Alias forsocket organization
socket repo
- Alias forsocket repository
socket pkg
- Alias forsocket package
socket deps
- Alias forsocket dependencies
socket audit
- Alias forsocket audit-log
socket feed
- Alias forsocket threat-feed
--json
- Output as JSON--markdown
- Output as Markdown
--dry-run
- Run without uploading--debug
- Show debug output--help
- Show help--max-old-space-size
- Set Node.js memory limit--max-semi-space-size
- Set Node.js heap size--version
- Show version
Socket CLI reads socket.yml
configuration files.
Supports version 2 format with projectIgnorePaths
for excluding files from reports.
SOCKET_CLI_API_TOKEN
- Socket API tokenSOCKET_CLI_CONFIG
- JSON configuration objectSOCKET_CLI_GITHUB_API_URL
- GitHub API base URLSOCKET_CLI_GIT_USER_EMAIL
- Git user email (default:[email protected]
)SOCKET_CLI_GIT_USER_NAME
- Git user name (default:Socket Bot
)SOCKET_CLI_GITHUB_TOKEN
- GitHub token with repo access (alias:GITHUB_TOKEN
)SOCKET_CLI_NO_API_TOKEN
- Disable default API tokenSOCKET_CLI_NPM_PATH
- Path to npm directorySOCKET_CLI_ORG_SLUG
- Socket organization slugSOCKET_CLI_ACCEPT_RISKS
- Accept npm/npx risksSOCKET_CLI_VIEW_ALL_RISKS
- Show all npm/npx risks
Run locally:
pnpm install
pnpm run build
pnpm exec socket
SOCKET_CLI_API_BASE_URL
- API base URL (default:https://api.socket.dev/v0/
)SOCKET_CLI_API_PROXY
- Proxy for API requests (aliases:HTTPS_PROXY
,https_proxy
,HTTP_PROXY
,http_proxy
)SOCKET_CLI_API_TIMEOUT
- API request timeout in millisecondsSOCKET_CLI_CACHE_ENABLED
- Enable API response caching (default:false
)SOCKET_CLI_CACHE_TTL
- Cache TTL in milliseconds (default:300000
= 5 minutes)SOCKET_CLI_DEBUG
- Enable debug loggingDEBUG
- Enabledebug
package logging
The CLI supports granular debug logging via the DEBUG
environment variable:
Default categories (shown with SOCKET_CLI_DEBUG=1
):
error
- Critical errors that prevent operationwarn
- Important warnings that may affect behaviornotice
- Notable events and state changessilly
- Very verbose debugging info
Opt-in categories (require explicit DEBUG='category'
):
cache
- Cache hit/miss operationsnetwork
- HTTP requests with timingcommand
- External command executionauth
- Authentication flowperf
- Performance timingspinner
- Spinner state changesinspect
- Detailed object inspectionstdio
- Command execution logs
Examples:
DEBUG=cache socket scan # Cache debugging only
DEBUG=network,cache socket scan # Multiple categories
DEBUG=* socket scan # All categories
SOCKET_CLI_DEBUG=1 socket scan # Default categories
Track long-running operations with visual progress bars:
import { startSpinner, updateSpinnerProgress } from './src/utils/spinner.mts'
const stop = startSpinner('Processing files')
for (let i = 0; i < files.length; i++) {
updateSpinnerProgress(i + 1, files.length, 'files')
await processFile(files[i])
}
stop()
// Output: ⠋ Processing files ████████████░░░░░░░░ 60% (12/20 files)
Display structured data with professional table formatting:
import { formatTable, formatSimpleTable } from './src/utils/output-formatting.mts'
import colors from 'yoctocolors-cjs'
// Bordered table with box-drawing characters
const data = [
{ name: 'lodash', version: '4.17.21', issues: 0 },
{ name: 'react', version: '18.2.0', issues: 2 }
]
const columns = [
{ key: 'name', header: 'Package' },
{ key: 'version', header: 'Version', align: 'center' },
{
key: 'issues',
header: 'Issues',
align: 'right',
color: (v) => v === '0' ? colors.green(v) : colors.red(v)
}
]
console.log(formatTable(data, columns))
// Output:
// ┌─────────┬─────────┬────────┐
// │ Package │ Version │ Issues │
// ├─────────┼─────────┼────────┤
// │ lodash │ 4.17.21 │ 0 │
// │ react │ 18.2.0 │ 2 │
// └─────────┴─────────┴────────┘
// Simple table without borders
console.log(formatSimpleTable(data, columns))
// Output:
// Package Version Issues
// ─────── ─────── ──────
// lodash 4.17.21 0
// react 18.2.0 2
Track and optimize CLI performance with comprehensive monitoring utilities:
import { perfTimer, measure, perfCheckpoint, printPerformanceSummary } from './src/utils/performance.mts'
// Simple operation timing
const stop = perfTimer('fetch-packages')
await fetchPackages()
stop({ count: 50 })
// Function measurement
const { result, duration } = await measure('parse-manifest', async () => {
return parseManifest(file)
})
console.log(`Parsed in ${duration}ms`)
// Track complex operation progress
perfCheckpoint('start-scan')
perfCheckpoint('analyze-dependencies', { count: 100 })
perfCheckpoint('detect-issues', { issueCount: 5 })
perfCheckpoint('end-scan')
// Print performance summary
printPerformanceSummary()
// Performance Summary:
// fetch-packages: 1 calls, avg 234ms (min 234ms, max 234ms, total 234ms)
// parse-manifest: 5 calls, avg 12ms (min 8ms, max 20ms, total 60ms)
Enable with: DEBUG=perf socket <command>
Optimize API performance with smart caching based on data volatility:
import { getCacheStrategy, getRecommendedTtl, warmCaches } from './src/utils/cache-strategies.mts'
// Get recommended TTL for an endpoint
const ttl = getRecommendedTtl('/npm/lodash/4.17.21/score')
// Returns: 900000 (15 minutes for stable package info)
// Check cache strategy
const strategy = getCacheStrategy('/scans/abc123')
// Returns: { ttl: 120000, volatile: true } (2 minutes for active scans)
// Warm critical caches on startup
await warmCaches(sdk, [
'/users/me',
'/organizations/my-org/settings'
])
Built-in strategies:
- Package info: 15min (stable data)
- Package issues: 5min (moderate volatility)
- Scan results: 2min (high volatility)
- Org settings: 30min (very stable)
- User info: 1hr (most stable)
Handle errors with actionable recovery suggestions:
import { InputError, AuthError, getRecoverySuggestions } from './src/utils/errors.mts'
// Throw errors with recovery suggestions
throw new InputError('Invalid package name', 'Must be in format: @scope/name', [
'Use npm package naming conventions',
'Check for typos in the package name'
])
throw new AuthError('Token expired', [
'Run `socket login` to re-authenticate',
'Generate a new token at https://socket.dev/dashboard'
])
// Extract and display recovery suggestions
try {
await operation()
} catch (error) {
const suggestions = getRecoverySuggestions(error)
if (suggestions.length > 0) {
console.error('How to fix:')
suggestions.forEach(s => console.error(` - ${s}`))
}
}
