Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Random Lib Laravel Package

ircmaxell/random-lib

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require ircmaxell/random-lib ircmaxell/security-lib
    
    • Note: security-lib is a required dependency for strength definitions.
  2. First Use Case: Replace insecure randomness (e.g., Str::random() or uniqid()) in a Laravel controller:

    use RandomLib\Factory;
    
    $factory = new Factory();
    $generator = $factory->getMediumStrengthGenerator();
    
    // Generate a secure token (e.g., for password reset)
    $token = $generator->generateString(32);
    
  3. Where to Look First:

    • Factory Class: RandomLib\Factory for creating generators.
    • Generator Methods: generate(), generateInt(), generateString() for specific needs.
    • Strength Constants: SecurityLib\Strength (e.g., MEDIUM, LOW) for risk-appropriate randomness.

Implementation Patterns

Usage Patterns

  1. Strength-Based Workflows:

    • Low Strength: Non-critical randomness (e.g., quiz questions, nonces).
      $lowGenerator = $factory->getLowStrengthGenerator();
      $nonce = $lowGenerator->generateString(16);
      
    • Medium Strength: Default for security-sensitive operations (e.g., tokens, salts).
      $mediumGenerator = $factory->getMediumStrengthGenerator();
      $token = $mediumGenerator->generateString(64);
      
    • High Strength: Opt-in for extreme security (e.g., master encryption keys).
      // Requires custom mixer setup (see "Gotchas")
      $highGenerator = $factory->getGenerator(new Strength(Strength::HIGH));
      
  2. Laravel Integration:

    • Service Provider Binding:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton('random-lib.factory', function () {
              return new Factory();
          });
      }
      
    • Facade for Convenience:
      // app/Facades/RandomLib.php
      public static function secureToken($length = 32)
      {
          return app('random-lib.factory')
              ->getMediumStrengthGenerator()
              ->generateString($length);
      }
      
      Usage:
      $token = RandomLib::secureToken();
      
  3. Dynamic Strength Selection:

    • Use environment variables or config to switch strengths:
      $strength = config('random-lib.default_strength', Strength::MEDIUM);
      $generator = $factory->getGenerator(new Strength($strength));
      
  4. Bulk Generation:

    • For performance-critical paths (e.g., bulk token creation), reuse generators:
      $generator = $factory->getLowStrengthGenerator();
      $tokens = collect(range(1, 100))->map(fn() => $generator->generateString(16));
      

Integration Tips

  1. Replace Laravel’s Str::random():

    • Override Str::random() in a macro for security-sensitive contexts:
      Str::macro('secureRandom', function ($length = 16) {
          return app('random-lib.factory')
              ->getMediumStrengthGenerator()
              ->generateString($length);
      });
      
  2. Database UUIDs:

    • Use generate() for UUIDs (if not using Laravel’s Str::uuid()):
      $uuid = bin2hex($generator->generate(16)); // 32-character UUID
      
  3. Testing:

    • Mock the generator in unit tests to avoid flakiness:
      $mockGenerator = Mockery::mock(RandomLib\Generator::class);
      $mockGenerator->shouldReceive('generateString')->andReturn('test-token');
      $this->app->instance('random-lib.factory', $factory);
      
  4. Custom Character Sets:

    • Restrict strings to specific character sets (e.g., URL-safe):
      $urlSafeChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
      $token = $generator->generateString(32, $urlSafeChars);
      

Gotchas and Tips

Pitfalls

  1. High Strength Limitations:

    • No Built-in Mixers: High-strength generators require manual setup (e.g., HmacGenerator or SHA256 mixers from security-lib).
      • Workaround: Avoid high strength unless absolutely necessary; use medium for most cryptographic needs.
    • Performance: High-strength generation can take minutes for large outputs (e.g., 256-byte keys). Benchmark in CI.
  2. Thread Safety:

    • Generators are stateless and thread-safe, but the factory may not be if custom mixers are added dynamically.
      • Fix: Use a singleton factory or synchronize access in multi-threaded environments (e.g., Laravel queues).
  3. PHP Version Constraints:

    • Requires PHP 5.3+ (due to security-lib). Laravel 10+ (PHP 8.1+) may introduce deprecation risks for legacy code.
      • Tip: Test with PHP 8.1+ early to catch issues (e.g., create_function() deprecations in security-lib).
  4. Entropy Source Dependencies:

    • Underlying entropy sources (e.g., /dev/urandom) may be unavailable in serverless or containerized environments.
      • Solution: Fall back to random_int() or openssl_random_pseudo_bytes() in such cases:
        try {
            return $generator->generateString(32);
        } catch (\Exception $e) {
            return bin2hex(random_bytes(16));
        }
        
  5. Strength Misconfiguration:

    • Using low strength for sensitive data (e.g., salts, tokens) can lead to security vulnerabilities.
      • Tip: Enforce medium as the default in config:
        // config/random-lib.php
        'default_strength' => \SecurityLib\Strength::MEDIUM,
        

Debugging

  1. Generator Failures:

    • If generate() throws exceptions, check:
      • Entropy Source: Ensure /dev/urandom or equivalent is available.
      • Strength Limits: High-strength generators may fail with RuntimeException if resources are insufficient.
      • Debugging Tip: Log the full exception and entropy source:
        try {
            $bytes = $generator->generate(32);
        } catch (\Exception $e) {
            \Log::error('RandomLib failure: ' . $e->getMessage(), [
                'entropy_source' => $generator->getEntropySource(),
            ]);
        }
        
  2. Non-Uniform Outputs:

    • If generated strings appear biased, verify:
      • Character Set: Ensure the input to generateString() includes all desired characters.
      • Mixer Configuration: Custom mixers may introduce bias if not properly seeded.
      • Test: Run statistical tests (e.g., NIST SP 800-22) on outputs.
  3. Performance Bottlenecks:

    • High-strength generators may cause timeouts in CI/CD or serverless environments.
      • Solution: Use low strength for non-critical paths or optimize mixer configurations.

Tips

  1. Laravel-Specific Optimizations:

    • Cache Generators: Reuse generators for repeated calls (e.g., in a loop):
      $generator = $factory->getLowStrengthGenerator();
      foreach ($users as $user) {
          $user->api_token = $generator->generateString(40);
      }
      
    • Environment-Aware Strengths:
      $strength = app()->environment('local') ? Strength::LOW : Strength::MEDIUM;
      
  2. Extension Points:

    • Custom Mixers: Add entropy sources (e.g., user input, HTTP headers) for additional randomness:
      $factory->addMixer(new \SecurityLib\Mixer\CustomMixer(
          fn() => $_SERVER['REMOTE_ADDR'] ?? ''
      ));
      
    • Strength Validation: Create a validator rule for secure randomness:
      use Illuminate\Validation\Rule;
      
      Rule::define('secure_random', function ($attribute, $value, $parameters) {
          $generator = app('random-lib.factory')->getMediumStrengthGenerator();
          return strlen($value) === 32 && preg_match('/^[a-zA-Z0-9+/]+={0,2}$/', $value);
      });
      
  3. Security Audits:

    • Token Validation: Ensure tokens are validated against expected patterns:
      public function validateToken($token)
      {
          $generator = app('random-lib.factory')->getMediumStrengthGenerator();
          $expectedLength = 32;
          return strlen($token)
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment