/

Angular Integration

ByteHide Shield provides a powerful plugin for Angular projects that enables JavaScript obfuscation to enhance the security of your codebase. This plugin integrates seamlessly with your Angular build process to obfuscate sensitive files, protecting your intellectual property.

Features

  • Code Obfuscation: Protect your JavaScript code from reverse engineering
  • Angular CLI Integration: Works seamlessly with Angular CLI build process
  • Customizable Options: Configure obfuscation settings to suit your needs
  • File Exclusion: Exclude specific files from obfuscation
  • Framework Detection: Automatically detects Angular framework and version

Installation

Install the plugin using npm or yarn:

npm install @bytehide/angular-shield --save-dev

Or with yarn:

yarn add --dev @bytehide/angular-shield

Usage

Method 1: Post-Build Script (Recommended)

Create a post-build script to obfuscate your Angular build output:

// scripts/obfuscate.ts
import { createAngularShield } from '@bytehide/angular-shield';

const shield = createAngularShield({
  projectToken: 'your-project-token', // Required: Your ByteHide project token
  replace: true,                      // Optional: Replace original files
  controlFlowFlattening: true,        // Optional: Enable control flow flattening
  debugProtection: false,             // Optional: Enable debug protection
  devtoolsBlocking: false,            // Optional: Enable devtools blocking
  exclude: ['main.js'],               // Optional: Exclude specific files
  obfuscatedExtension: '.obf',        // Optional: Extension for obfuscated files
});

// Apply obfuscation to the dist folder
await shield.applyShield();

Add to your package.json:

{
  "scripts": {
    "build": "ng build",
    "build:prod": "ng build --configuration production",
    "postbuild:prod": "ts-node scripts/obfuscate.ts"
  }
}

Method 2: Custom Builder

Create a custom Angular builder:

// builders/bytehide-builder.ts
import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect';
import { createAngularShield } from '@bytehide/angular-shield';

interface ByteHideOptions {
  projectToken: string;
  replace?: boolean;
  controlFlowFlattening?: boolean;
  debugProtection?: boolean;
  devtoolsBlocking?: boolean;
  exclude?: string[];
  obfuscatedExtension?: string;
}

export default createBuilder<ByteHideOptions>(async (options, context) => {
  try {
    const shield = createAngularShield({
      projectToken: options.projectToken,
      replace: options.replace ?? true,
      controlFlowFlattening: options.controlFlowFlattening ?? true,
      debugProtection: options.debugProtection ?? false,
      devtoolsBlocking: options.devtoolsBlocking ?? false,
      exclude: options.exclude ?? [],
      obfuscatedExtension: options.obfuscatedExtension ?? '.obf',
    });

    await shield.applyShield();
    
    return { success: true };
  } catch (error) {
    context.logger.error('ByteHide Shield obfuscation failed:', error);
    return { success: false, error: error.message };
  }
});

Method 3: Angular CLI Hook

Use Angular CLI hooks in your angular.json:

{
  "projects": {
    "your-app": {
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/your-app"
          },
          "configurations": {
            "production": {
              "optimization": true,
              "outputHashing": "all"
            }
          }
        },
        "obfuscate": {
          "builder": "./builders/bytehide-builder",
          "options": {
            "projectToken": "your-project-token"
          }
        }
      }
    }
  }
}

Configuration Options

OptionTypeDefaultDescription
projectTokenstringRequiredYour ByteHide project token
replacebooleanfalseWhether to replace original files
obfuscatedExtensionstring.obfExtension for obfuscated files
controlFlowFlatteningbooleantrueEnable control flow flattening
debugProtectionbooleanfalseEnable debug protection
devtoolsBlockingbooleanfalseEnable devtools blocking
excludestring[][]Files to exclude from obfuscation

Excluded Files

The plugin automatically excludes common Angular files that shouldn't be obfuscated:

  • main.js - Application entry point
  • polyfills.js - Browser polyfills
  • runtime.js - Webpack runtime
  • styles.js - Compiled styles
  • vendor.js - Third-party libraries
  • common.js - Common modules

Angular-Specific Considerations

File Exclusions

The plugin automatically excludes common Angular files that shouldn't be obfuscated:

  • main.js - Application entry point
  • polyfills.js - Browser polyfills
  • runtime.js - Webpack runtime
  • styles.js - Compiled styles
  • vendor.js - Third-party libraries

Build Output Structure

Angular CLI typically generates files in this structure:

dist/your-app/
├── main.js
├── polyfills.js
├── runtime.js
├── styles.js
├── vendor.js
├── common.js
└── [hash].js (chunk files)

Production Build

For production builds, ensure you're using:

ng build --configuration production

This enables:

  • Code optimization
  • Tree shaking
  • Minification
  • Output hashing

Integration with Angular CLI

Using with ng build

# Build your Angular app
ng build --configuration production

# Run obfuscation
npm run postbuild:prod

Using with custom builders

# Build and obfuscate in one command
ng run your-app:obfuscate

Example Output

Here's how an obfuscated Angular file is generated:

  • Input: dist/your-app/main.js
  • Output: dist/your-app/main.obf.js (if replace is false) or replaces the original file

If you have an main.js file with this content:

console.log("Hello, Angular!");

The processed result will include a unique marker and the obfuscated code:

// _0xBHSHLD_<uniqueId>_marker
console.log(_0x123456("Hello, Angular!"));

Troubleshooting

Common Issues

Network Error

If you encounter network errors during the build process:

  • Ensure you have an active internet connection as the plugin uses a remote service for code obfuscation
  • Check if your network firewall is blocking requests to the ByteHide service

Invalid Token

If you see an error about an invalid token:

  • Verify that your project token is valid and correctly typed
  • Make sure the token has permissions for JavaScript projects

Build Base Path Issues

If you encounter "Build base path is not defined" errors:

  • Check that outputPath is correctly set in your angular.json
  • Default is dist for Angular CLI

Files Not Being Obfuscated

If files are not being obfuscated:

  • Check if files are in the exclusion list
  • Verify the build output path
  • Ensure the file extensions are supported

Debug Mode

Enable debug logging by setting:

const shield = createAngularShield({
  projectToken: process.env.BYTEHIDE_TOKEN!,
  replace: false, // Keep original files for comparison
  // ... other options
});

Best Practices

  1. Always test in development first
  2. Keep main.js and polyfills.js readable for debugging
  3. Use environment variables for sensitive tokens
  4. Run obfuscation only in production builds
  5. Test the obfuscated build thoroughly

Limitations

  • Requires a valid ByteHide project token
  • Obfuscation might slightly increase build time
  • Some Angular-specific files are automatically excluded for compatibility

Next Steps

Previous
Webpack