CLI and Node.js Integration
ByteHide Shield provides a flexible command-line interface (CLI) and Node.js API for protecting your JavaScript code. This approach offers the most control and can be integrated into any build process or workflow.
Installation
Install the ByteHide Shield CLI globally to use it from anywhere in your system:
npm install -g @bytehide/shield-cli
This is the recommended installation method as it allows you to run the shield
command from any directory.
Alternatively, you can install it as a project dependency:
npm install --save-dev @bytehide/shield-cli
CLI Usage
Basic Commands
# Basic usage
shield protect "src/**/*.js" --token YOUR_PROJECT_TOKEN
# Protect multiple patterns
shield protect "src/main.js" "src/utils/*.js" --token YOUR_PROJECT_TOKEN
# Use a custom configuration file
shield protect "src/**/*.js" --config ./shield.config.json
# Add an extension to obfuscated files
shield protect "src/**/*.js" --output-ext ".obf"
# Specify output file for a single file
shield protect "src/main.js" --output "dist/main.obfuscated.js"
# Specify output directory for multiple files
shield protect "src/**/*.js" --output-dir "dist/obfuscated"
# Generate source maps
shield protect "src/**/*.js" --source-map
# Create backups of original files
shield protect "src/**/*.js" --backup
# Dry run (preview which files would be obfuscated)
shield protect "src/**/*.js" --dry-run
# Display help
shield --help
shield protect --help
# Display version
shield --version
CLI Options
Option | Description |
---|---|
-t, --token <token> | ByteHide Shield project token |
-c, --config <path> | Path to custom configuration file (default: shield.config.json) |
-o, --output-ext <extension> | Extension for obfuscated files (default: "") |
-O, --output <path> | Output file path for single file obfuscation |
-D, --output-dir <directory> | Output directory for obfuscated files |
--source-map | Generate source map files (.map) |
--source-map-path <path> | Custom path for source map file (single file only) |
--symbols | Save identifier names cache (.symbols.json) |
--symbols-path <path> | Custom path for symbols cache file (single file only) |
-b, --backup | Create backup of original files before obfuscation |
--no-backup | Disable backup creation even if enabled in config |
-d, --dry-run | Show which files would be obfuscated without making changes |
-v, --version | Display version number |
-h, --help | Display help for command |
Token Configuration
You can provide your ByteHide Shield project token in multiple ways (in order of priority):
Using the
--token
flagshield protect "src/**/*.js" --token YOUR_PROJECT_TOKEN
Setting the
BYTEHIDE_SHIELD_TOKEN
environment variableexport BYTEHIDE_SHIELD_TOKEN=YOUR_PROJECT_TOKEN shield protect "src/**/*.js"
Setting the
BYTEHIDE_TOKEN
environment variable (backward compatibility)export BYTEHIDE_TOKEN=YOUR_PROJECT_TOKEN shield protect "src/**/*.js"
Adding it to your
shield.config.json
file{ "ProjectToken": "YOUR_PROJECT_TOKEN", "controlFlowFlattening": true, // ...other options }
If you don't have a project token yet, learn how to obtain one in the Get Project Token documentation.
Configuration Files
A configuration file is required unless specified with the --config
option. The CLI will look for a shield.config.json
file in the following locations (in order):
- The path specified with
--config
option - The current working directory
- The directory of the JavaScript files being obfuscated
If no configuration file is found, the CLI will exit with an error.
Example configuration file (shield.config.json
):
{
"ProjectToken": "YOUR_PROJECT_TOKEN",
"controlFlowFlattening": true,
"debugProtection": false,
"devtoolsBlocking": true,
"deadCodeInjection": false,
"selfDefending": true,
"stringArray": true,
"stringArrayEncoding": ["base64"],
"stringArrayThreshold": 0.8,
"transformObjectKeys": true,
"unicodeEscapeSequence": false
}
For a complete list of configuration options, see the Configuration Files documentation.
Source Maps
The Shield CLI supports source map generation, which helps with debugging obfuscated code:
# Generate source maps
shield protect "src/**/*.js" --source-map
# Generate source maps with custom path (single file only)
shield protect "src/main.js" --source-map --source-map-path "dist/maps/main.js.map"
For more information about working with source maps, see the Source Maps documentation.
Symbols for Consistent Obfuscation
To ensure consistent identifier renaming across multiple obfuscation runs or files:
# Save identifier names cache
shield protect "src/**/*.js" --symbols
# Save symbols with custom path (single file only)
shield protect "src/main.js" --symbols --symbols-path "dist/symbols/main.symbols.json"
Node.js API
You can also use Shield directly in your Node.js scripts.
Basic Usage
import { obfuscate } from '@bytehide/shield-cli';
const code = `function hello() { console.log("Hello world!"); }`;
const token = 'YOUR_PROJECT_TOKEN';
const config = {
controlFlowFlattening: true,
stringArray: true
};
// Basic usage - returns obfuscated code string
const obfuscatedCode = await obfuscate(code, token, config);
console.log(obfuscatedCode);
// Advanced usage - returns object with output, sourceMap, and symbols
const result = await obfuscate(code, token, config, {
includeSourceMap: true,
includeSymbols: true
});
console.log(result.output); // Obfuscated code
console.log(result.sourceMap); // Source map (if enabled in config)
console.log(result.symbols); // Identifier names cache
Advanced API Options
You can use the full API for more control:
import { obfuscateFile, loadConfig } from '@bytehide/shield-cli';
// Load config from file
const config = await loadConfig('./shield.config.json');
// Process a file with custom options
await obfuscateFile({
filePath: 'src/main.js',
token: 'YOUR_PROJECT_TOKEN',
config,
outputPath: 'dist/main.obfuscated.js',
generateSourceMap: true,
sourceMapPath: 'dist/maps/main.js.map',
saveSymbols: true,
symbolsPath: 'dist/symbols/main.symbols.json'
});
Processing Multiple Files
The CLI supports processing multiple files using glob patterns:
const { obfuscate } = require('@bytehide/shield-cli');
const glob = require('glob');
const path = require('path');
const fs = require('fs');
async function protectProject() {
try {
// Get all JS files
const files = glob.sync('src/**/*.js');
for (const file of files) {
// Skip excluded files
if (file.includes('node_modules') || file.includes('vendor')) {
continue;
}
// Create output path
const relativePath = path.relative('src', file);
const outputPath = path.join('dist', relativePath);
// Create directory if it doesn't exist
const outputDir = path.dirname(outputPath);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Read the file
const code = fs.readFileSync(file, 'utf8');
// Protect the code
const result = await obfuscate(code, process.env.BYTEHIDE_TOKEN, {
controlFlowFlattening: true,
stringArray: true
}, {
includeSourceMap: true
});
// Write the obfuscated code
fs.writeFileSync(outputPath, result.output);
// Write source map if enabled
if (result.sourceMap) {
fs.writeFileSync(`${outputPath}.map`, result.sourceMap);
}
console.log(`Protected: ${file} -> ${outputPath}`);
}
console.log('All files protected successfully!');
} catch (error) {
console.error('Protection failed:', error);
}
}
protectProject();
CI/CD Integration
With GitHub Actions
# .github/workflows/build.yml
name: Build and Protect
on:
push:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Protect JavaScript code
run: npx @bytehide/shield-cli protect "dist/**/*.js" --token ${{ secrets.BYTEHIDE_TOKEN }} --config shield.config.json
- name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: protected-app
path: dist/
With GitLab CI
# .gitlab-ci.yml
stages:
- build
- protect
- deploy
build:
stage: build
image: node:16
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
protect:
stage: protect
image: node:16
script:
- npm install -g @bytehide/shield-cli
- shield protect "dist/**/*.js" --token $BYTEHIDE_TOKEN --config shield.config.json
artifacts:
paths:
- dist/
CLI in npm Scripts
Add Shield to your package.json
scripts:
{
"scripts": {
"build": "webpack --mode production",
"protect": "shield protect --token $BYTEHIDE_TOKEN --config shield.config.json dist/bundle.js -o dist/bundle.protected.js",
"build:protected": "npm run build && npm run protect"
}
}
Then run:
npm run build:protected
Troubleshooting
Common Issues
Error: Invalid Token
If you see an error about an invalid token:
Error: Invalid project token provided
Make sure:
- You're using the correct project token from ByteHide Cloud
- The token is for a JavaScript project, not a .NET or other platform
- Your token has not expired or been revoked
See Get Project Token for help obtaining a valid token.
Large File Handling
For very large files, you may need to increase Node.js memory limit:
NODE_OPTIONS=--max-old-space-size=4096 shield protect large-file.js -o large-file.protected.js
Source Maps Issues
If you're having trouble with source maps:
- Ensure source maps are enabled both in Shield and your build tool
- Check that the paths in the source map are correct for your setup
For more information, see the Source Maps documentation.
Features
- Supports glob patterns for selecting files
- UTF-8 with BOM encoding for proper file encoding
- Project token configuration from multiple sources
- Custom output paths for source files, source maps, and symbol files
- Backup file creation (optional)
- Source map generation for debugging
- Symbols cache for consistent identifier naming
- Watermarking of obfuscated files to prevent re-obfuscation
- Detailed progress with success/failure reporting
- Colorful CLI interface with progress bars and symbols
- Looks for configuration files in multiple locations