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

Core Laravel Package

laravel-chronicle/core

Chronicle provides cryptographically verifiable audit logging for Laravel. It records events in an append-only, hash-chained ledger to make tampering detectable, with features like verifiable exports, signed checkpoints, key rotation, and external anchoring.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require laravel-chronicle/core
   php artisan chronicle:install
  • Run migrations (--migrate flag if needed) and configure .env with signing keys.
  • Verify CHRONICLE_PRIVATE_KEY and CHRONICLE_PUBLIC_KEY are set (or use chronicle:key:generate to create a new keypair).
  1. First Record:

    use Chronicle\Facades\Chronicle;
    
    Chronicle::record()
        ->actor(auth()->user())
        ->action('user.login')
        ->subject(null) // No subject if irrelevant
        ->commit();
    
  2. Automatic Model Auditing: Add HasChronicle trait to a model (e.g., User):

    use Chronicle\Eloquent\HasChronicle;
    
    class User extends Model
    {
        use HasChronicle;
    }
    

    Now created, updated, and deleted events are auto-logged.


Implementation Patterns

Core Workflows

  1. Structured Logging:

    • Use Chronicle::record() for custom events with metadata/tags:
      Chronicle::record()
          ->actor($adminUser)
          ->action('payment.processed')
          ->subject($payment)
          ->metadata(['amount' => $payment->amount])
          ->tags(['finance', 'audit'])
          ->commit();
      
    • Tip: Group related actions under a single tag (e.g., ['finance']) for filtering.
  2. Model Observers: For third-party models, register observers:

    Chronicle::observe(Order::class, function ($model) {
        return [
            'action' => match ($model->event) {
                'created' => 'order.created',
                'updated' => 'order.updated',
                'deleted' => 'order.deleted',
            },
            'subject' => $model,
        ];
    });
    
  3. Querying:

    • Filter by actor/subject/action/tags:
      // Find all actions by a user
      Chronicle\Entry\Entry::forActor($user)->get();
      
      // Stream large datasets
      Chronicle\Entry\Entry::stream()->each(fn ($entry) => /* ... */);
      
  4. Checkpoints & Anchoring:

    • Schedule chronicle:checkpoint via cron (e.g., daily) to create verifiable snapshots:
      * * * * * php artisan chronicle:checkpoint --anchor
      
    • Anchoring: Enable RFC 3161 TSA anchoring in config/chronicle.php for external tamper-proofing.
  5. Verification:

    • Validate ledger integrity periodically:
      php artisan chronicle:verify --since-last-checkpoint
      
    • For compliance, use --checkpoints-only --anchors for a lightweight audit.

Integration Tips

  1. Event Dispatching: Tie Chronicle to Laravel events (e.g., OrderPaid):

    event(new OrderPaid($order));
    // In EventServiceProvider:
    protected $listen = [
        OrderPaid::class => [\App\Listeners\LogOrderPayment::class],
    ];
    
    // Listener
    public function handle(OrderPaid $event) {
        Chronicle::record()
            ->actor($event->user)
            ->action('order.paid')
            ->subject($event->order)
            ->commit();
    }
    
  2. API Audit Trails: Use middleware to log API requests:

    public function handle($request, Closure $next) {
        $response = $next($request);
        Chronicle::record()
            ->actor($request->user())
            ->action('api.request')
            ->subject($request->route())
            ->metadata(['method' => $request->method(), 'path' => $request->path()])
            ->commit();
        return $response;
    }
    
  3. Retention Policies: Prune old entries (e.g., older than 2 years):

    php artisan chronicle:prune --older-than=2years --dry-run
    
    • Test with --dry-run first, then remove flag for execution.
  4. Key Rotation: Rotate keys during deployments:

    # Generate new key
    php artisan chronicle:key:generate --id=chronicle-key-2
    
    # Rotate (creates boundary checkpoint)
    php artisan chronicle:key:rotate chronicle-key-2
    
    # Update config/chronicle.php:
    'active' => 'chronicle-key-2'
    
  5. Exports for Compliance: Generate verifiable exports for auditors:

    php artisan chronicle:export storage/app/chronicle-export-$(date +%Y%m%d)
    
    • Share entries.ndjson, manifest.json, and signature.json for offline verification.

Gotchas and Tips

Pitfalls

  1. Missing ext-sodium/ext-openssl:

    • Error: Class 'Chronicle\Signing\Ed25519SigningProvider' not found.
    • Fix: Enable PHP extensions (sudo apt install php-sodium php-openssl or equivalent).
  2. Key Configuration:

    • Gotcha: Forgetting to set CHRONICLE_ACTIVE_KEY or including private_key in retired keys.
    • Fix: Use chronicle:key:list to verify the ring:
      php artisan chronicle:key:list --with-counts
      
    • Tip: Retired keys should have private_key: null but keep public_key.
  3. Database Transactions:

    • Gotcha: Chronicle wraps records in transactions. Long-running operations (e.g., bulk inserts) may time out.
    • Fix: Batch records or increase DB_TRANSACTION_TIMEOUT in .env.
  4. ULID Collisions:

    • Gotcha: Rare but possible if generating ULIDs outside Chronicle’s control.
    • Fix: Use Chronicle’s built-in ULID generator (e.g., Chronicle::record()->ulid()).
  5. Anchoring Failures:

    • Gotcha: TSA anchoring may fail due to network issues or certificate revocation.
    • Fix: Retry with chronicle:anchor:retry and monitor chronicle:anchor:verify.
  6. Metadata Serialization:

    • Gotcha: Complex metadata (e.g., closures, resources) may not serialize.
    • Fix: Ensure metadata is JSON-serializable or use ->withoutMetadata() for problematic fields.

Debugging

  1. Verify Ledger:

    • Start with incremental checks:
      php artisan chronicle:verify --since-last-checkpoint
      
    • For specific entries:
      php artisan chronicle:verify --entry=01H5Z...
      
  2. Inspect Entries:

    • View raw entry data:
      php artisan chronicle:show 01H5Z...
      
    • Check chain integrity:
      php artisan chronicle:stats
      
  3. Logs:

    • Enable debug logging in config/chronicle.php:
      'logging' => [
          'level' => 'debug',
      ],
      
    • Check storage/logs/chronicle.log for errors.

Extension Points

  1. Custom Signing Providers:

    • Implement Chronicle\Signing\SigningProviderInterface for KMS/HSM:
      class GcpKmsSigningProvider implements SigningProviderInterface {
          public function sign(string $data): string { /* ... */ }
          public function verify(string $data, string $signature): bool { /* ... */ }
      }
      
    • Register in config/chronicle.php:
      'keys' => [
          'gcp-kms-key' => [
              'provider' => App\Providers\GcpKmsSigningProvider::class,
              'algorithm' => 'ed25519',
              'private_key' => null, // Handled by KMS
              'public_key' => env('GCP_KMS_PUBLIC_KEY'),
          ],
      ],
      
  2. Anchoring Providers:

    • Add support for Blockchain (e.g., Ethereum) or other WORM storage:
      class EthereumAnchor implements AnchoringProviderInterface {
          public function anchor(string $digest): ?string { /* ... */ }
          public function verify(string $anchorId, string $digest): bool { /* ... */ }
      }
      
  3. Query Scopes:

    • Extend the query builder:
      use Chronicle\Entry\Entry;
      
      Entry::macro('forIp', function ($ip) {
          return $this->whereHas('metadata', fn ($q) => $q->where('ip', $ip));
      });
      
  4. Event Modifiers:

    • Over
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky