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

Otphp Laravel Package

spomky-labs/otphp

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strong RFC Compliance: Fully adheres to RFC 4226 (HOTP) and RFC 6238 (TOTP), ensuring interoperability with Google Authenticator, FreeOTP, and other standards-compliant clients.
  • Modular Design: Separates concerns via TOTP/HOTP interfaces, enabling flexible integration into Laravel’s authentication stack (e.g., replacing or augmenting Laravel’s built-in auth).
  • Immutable/Mutable API: Supports both functional (immutable) and object-oriented (mutable) patterns, aligning with Laravel’s dependency injection and service container paradigms.
  • Clock Abstraction: PSR-20 Clock interface (optional in v11.4+, mandatory in v12.0) enables time-agnostic testing and mocking, critical for CI/CD and edge-case validation.

Integration Feasibility

  • Laravel Ecosystem Synergy:
    • Service Provider Integration: Can be bootstrapped via Laravel’s ServiceProvider (e.g., register() for DI, boot() for middleware/validation).
    • Validation Rules: Extend Laravel’s Validator with custom rules for OTP verification (e.g., otp:secret,counter).
    • Middleware: Create VerifyOTPMiddleware to protect routes (e.g., /admin).
    • Artisan Commands: Generate provisioning URIs via CLI (e.g., php artisan otp:generate).
  • Database Storage: Secrets/counters can be stored in Laravel’s users table (e.g., otp_secret, otp_counter) or a dedicated otp_secrets table.
  • Caching: Leverage Laravel’s cache (Redis/Memcached) for TOTP drift handling (e.g., cache verified OTPs to reduce clock skew issues).

Technical Risk

  • Clock Dependency: Transition to PSR-20 Clock (v12.0) may require refactoring existing time-sensitive logic. Mitigation: Use a decorator pattern to wrap Laravel’s Carbon or now() with a Clock implementation.
  • Backward Compatibility: Breaking changes in v9.0+ (e.g., private constructors) necessitate migration testing. Use Laravel’s upgrade-helper or a feature flag for gradual adoption.
  • Cryptographic Assumptions: Default sha1 digest is insecure; enforce sha256/sha512 via Laravel’s config/otp.php with validation.
  • Performance: HOTP/TOTP generation is CPU-bound but negligible for most use cases. Benchmark under load if used for high-frequency validation (e.g., API rate limiting).

Key Questions

  1. Authentication Flow:
    • Will OTPs be used for 2FA (post-login) or primary auth (pre-login)? This dictates storage (session vs. database) and failure handling.
    • Should OTPs be time-bound (TOTP) or counter-bound (HOTP)? Hybrid approaches (e.g., TOTP for users, HOTP for devices) may be needed.
  2. Secret Management:
    • How will secrets be generated/distributed? Use Laravel’s Str::random(32) or integrate with a KMS (e.g., AWS KMS).
    • Should secrets be rotated? Implement a php artisan otp:rotate command with backward-compatible migration.
  3. User Experience:
    • Will you support QR code generation? Use libraries like endroid/qr-code to render provisioning URIs.
    • How will you handle OTP drift (e.g., user’s phone clock skew)? Configure a window size (e.g., 3 for TOTP) in Laravel’s config.
  4. Audit & Compliance:
    • Are OTP verification attempts logged? Extend Laravel’s auth.log or create a dedicated otp_attempts table.
    • Does your org require FIPS compliance? Ensure the PHP hash_algos() includes FIPS-approved algorithms (e.g., sha256).

Integration Approach

Stack Fit

  • PHP/Laravel Alignment:
    • PSR Standards: Compatible with Laravel’s PSR-4 autoloading, PSR-15 middleware, and PSR-20 Clock (future-proof).
    • Dependency Injection: Register the package via Laravel’s config/app.php and bind interfaces (OTPHP\TOTPInterface) to implementations.
    • Validation: Integrate with Laravel’s Validator via custom rules (e.g., app/Rules/ValidateOTP.php).
  • Database:
    • Schema: Add columns to users table or create a otp_secrets table:
      Schema::table('users', function (Blueprint $table) {
          $table->string('otp_secret')->nullable();
          $table->integer('otp_counter')->default(0);
          $table->boolean('otp_enabled')->default(false);
      });
      
    • Encryption: Encrypt secrets at rest using Laravel’s Crypt facade if compliance requires it.
  • Caching:
    • Cache verified OTPs (e.g., cache()->put('otp:user:123', $verifiedAt, now()->addMinutes(5))) to mitigate clock drift.
    • Cache provisioning URIs if generated dynamically (e.g., cache()->remember('otp:uri:123', ...)).

Migration Path

  1. Phase 1: Proof of Concept
    • Install via Composer: composer require spomky-labs/otphp.
    • Implement a manual OTP flow (e.g., php artisan make:controller OTPController).
    • Test with Google Authenticator and FreeOTP.
  2. Phase 2: Core Integration
    • Service Provider: Register the package and bind interfaces:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->bind(\OTPHP\TOTPInterface::class, function () {
              return \OTPHP\TOTP::createFromSecret(config('otp.secret'));
          });
      }
      
    • Validation Rule: Create app/Rules/ValidateOTP.php:
      public function passes($attribute, $value)
      {
          $user = auth()->user();
          $otp = app(\OTPHP\TOTPInterface::class);
          return $otp->verify($value, null, config('otp.window'));
      }
      
    • Middleware: Protect routes:
      Route::middleware(['auth', 'otp.verified'])->group(function () {
          // Admin routes
      });
      
  3. Phase 3: Full Feature Rollout
    • Artisan Commands: Add OTP management:
      php artisan make:command OTPGenerate
      php artisan make:command OTPRotate
      
    • Event Listeners: Log OTP attempts:
      event(new OTPVerified($user, $otp));
      
    • Testing: Write Pest/Laravel tests for edge cases (e.g., clock skew, brute force).

Compatibility

  • Laravel Versions: Tested on Laravel 8+ (PHP 7.4+). For Laravel 7.x, pin to otphp:^11.0 (PHP 7.1+).
  • PHP Extensions: Requires openssl and hash extensions (standard in PHP).
  • Third-Party Apps: Compatible with Google Authenticator, FreeOTP, Microsoft Authenticator, and Authy.
  • Legacy Systems: If integrating with older systems, ensure they support SHA-2 (not sha1).

Sequencing

  1. Prerequisites:
    • Upgrade PHP to 7.4+ (or 8.0+ for v12.0).
    • Configure Laravel’s config/otp.php:
      return [
          'window' => 3, // TOTP drift tolerance
          'digest' => 'sha256',
          'digits' => 6,
          'issuer' => env('OTP_ISSUER', 'MyApp'),
      ];
      
  2. Core Implementation:
    • Add OTP fields to the database.
    • Implement OTPController and ValidateOTP rule.
  3. User Flow:
    • Generate provisioning URIs for new users (e.g., after registration).
    • Enable OTP in user settings.
  4. Monitoring:
    • Log OTP failures to detect brute force or clock drift.
    • Set up alerts for failed verification spikes.

Operational Impact

Maintenance

  • Dependency Updates:
    • Monitor `spomky-l
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.
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
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours