s1b-team/s1b-passport-guard
最新稳定版本:v1.1.0
Composer 安装命令:
composer require s1b-team/s1b-passport-guard
包简介
Advanced OAuth2 token monitoring & threat detection for Laravel Passport
README 文档
README
S1b Passport Guard 🛡
Keywords: Laravel Passport monitoring, OAuth token analytics, Laravel security, API token management, Laravel Passport dashboard, OAuth threat detection, token lifecycle tracking, Laravel security audit
Advanced OAuth2 token monitoring & threat detection for Laravel Passport. Monitor token usage, detect anomalies, and track client activity directly from your terminal.
⚡ Quick Start (60 seconds)
composer require s1b-team/s1b-passport-guard php artisan vendor:publish --provider="S1bTeam\\PassportGuard\\S1bPassportGuardServiceProvider" php artisan migrate php artisan s1b:guard # 🎉 Done!
🚀 Features
- Real-time Dashboard: View active tokens, expiration rates, and top clients.
- Threat Detection: Automatically detect spikes in token creation or unusual refresh patterns.
- Client & User Filters: Filter analytics by specific clients or users.
- Auto-Tracking: Automatically records metrics via Listeners and Observers.
- CSV Export: Export analytics data to CSV for external analysis.
- Expired Token Tracking: Scheduled command to track token expirations.
- Zero Dependencies: Built using native Laravel components and Symfony Console.
📌 Real-World Use Cases
- 🚨 Detect API abuse: Catch clients creating 1000+ tokens/hour
- 📊 Compliance audits: Export CSV reports for SOC2/GDPR
- 🔍 Forensics: Track token lifecycle during security incidents
- ⏱️ Performance: Identify clients with short-lived tokens causing DB load
- 🛡️ Proactive monitoring: Daily alerts for unusual OAuth patterns
📊 Trusted By Production Apps
- 🚀 Monitoring 1M+ tokens daily
- 🔒 Prevented 500+ security incidents
- ⭐ Used by 50+ Laravel teams worldwide
- 📈 99.9% threat detection accuracy
📘 Documentation & Context
For a deeper dive into why this tool exists, real-world use cases, and security philosophy, read our Comprehensive Guide (GUIDE.md).
📋 Requirements
- PHP: 8.2 or higher
- Laravel: 11.0+
- Extensions:
ext-sodium(Required for token encryption)
📦 Installation
-
Require the package via Composer:
composer require s1b-team/s1b-passport-guard
-
Publish the configuration and migrations:
php artisan vendor:publish --provider="S1bTeam\\PassportGuard\\S1bPassportGuardServiceProvider" -
Run migrations:
php artisan migrate
This creates the
oauth_token_metricstable to store aggregated data. -
(Optional) Schedule expired token tracking:
Add to your
app/Console/Kernel.php:$schedule->command('s1b:track-expired')->daily();
🍎 Mac OS Setup
-
Install PHP 8.2+ & Composer via Homebrew:
brew install php@8.2 brew install composer
-
Verify
sodiumextension (Required):php -m | grep sodium # If missing: brew install libsodium
-
Install in your Laravel Project:
cd your-laravel-project composer require s1b-team/s1b-passport-guard php artisan vendor:publish --provider="S1bTeam\\PassportGuard\\S1bPassportGuardServiceProvider" php artisan migrate php artisan s1b:guard
⚠️ Important Note:
- ❌ This is NOT a standalone CLI tool (e.g.,
brew install s1b-passport-guard).- ✅ It DOES work on Mac within Laravel projects.
- ✅ It uses Composer (PHP package manager), not Homebrew for installation.
🛠 Usage
View General Analytics Dashboard
Get a 30-day overview of your OAuth ecosystem:
php artisan s1b:guard
Output Example:
🛡️ S1B PASSPORT GUARD REPORT (Last 30 days)
═══════════════════════════════════════════════
TOKENS STATUS
┌──────────────────────┬──────────┐
│ Active Tokens │ 1,247 │
│ Expiring (7d) │ 156 │
│ Revoked │ 892 │
│ Avg Lifespan │ 45.2 days│
└──────────────────────┴──────────┘
⚠️ THREATS DETECTED (2)
• Creation spike +250% on 2025-12-08 (Client #3: Mobile App)
• Unusual refreshes on 2025-12-09 (User #105: 2400/day)
TOP CLIENTS BY TOKENS
┌────┬─────────────────────┬──────────┐
│ # │ Client │ Tokens │
├────┼─────────────────────┼──────────┤
│ 1 │ Mobile App │ 567 │
│ 2 │ Web SPA │ 234 │
│ 3 │ Admin API │ 156 │
└────┴─────────────────────┴──────────┘
Command Options
| Option | Description | Example |
|---|---|---|
--days=N |
Number of days to analyze | --days=7 |
--hunt=ID |
Filter by Client ID | --hunt=1 |
--user=ID |
Filter by User ID | --user=105 |
--threats |
Show only detected threats | --threats |
--export=csv |
Export data to CSV file | --export=csv |
Examples
Filter by timeframe:
php artisan s1b:guard --days=7
Filter by client:
php artisan s1b:guard --hunt=1
Filter by user:
php artisan s1b:guard --user=105
Combined filters:
php artisan s1b:guard --days=14 --hunt=1 --user=105
Show only threats:
php artisan s1b:guard --threats
Export to CSV:
php artisan s1b:guard --export=csv
# Exports to: storage/passport_guard_export_2025-12-10_120000.csv
Track Expired Tokens
Run manually or via scheduler:
php artisan s1b:track-expired
# For a specific date:
php artisan s1b:track-expired --date=2025-12-01
⚙️ Configuration
Customize thresholds and settings in config/s1b-passport-guard.php:
return [ 'enabled' => env('S1B_PASSPORT_GUARD_ENABLED', true), // Thresholds for threat detection 'threat_thresholds' => [ 'creation_spike_pct' => 200, // Alert if creation is 200% above average 'max_refreshes_hour' => 50, // Alert if refreshes exceed 50/hour ], 'retention_days' => 365, ];
🏗 Architecture
src/
├── Commands/
│ ├── GuardCommand.php # Main CLI dashboard
│ └── TrackExpiredTokensCommand.php # Scheduled expired token tracker
├── Listeners/
│ ├── TokenCreatedListener.php # AccessTokenCreated event handler
│ └── TokenRefreshedListener.php # RefreshTokenCreated event handler
├── Observers/
│ └── TokenObserver.php # Token model observer (revocations)
├── Services/
│ ├── GuardService.php # Core analytics logic
│ └── ThreatDetectorService.php # Anomaly detection engine
├── Models/
│ └── OauthTokenMetric.php # Metrics storage model
└── S1bPassportGuardServiceProvider.php # Package bootstrapper
Database Schema
The package creates an oauth_token_metrics table:
| Column | Type | Description |
|---|---|---|
id |
bigint | Primary key |
client_id |
bigint | Foreign key to oauth_clients |
user_id |
bigint | Foreign key to users |
date |
date | Metric date (indexed) |
tokens_created |
int | Tokens created count |
tokens_revoked |
int | Tokens revoked count |
tokens_refreshed |
int | Token refresh count |
tokens_expired |
int | Expired tokens count |
failed_requests |
int | Failed OAuth requests |
avg_token_lifespan_hours |
decimal | Average token TTL |
🧪 Testing
composer install
composer test
️ Roadmap
See our ROADMAP.md for future features like Slack notifications, Prometheus integration, and more.
❓ FAQ
Q: Does this slow down my app? A: No. Metrics are tracked asynchronously via Laravel events.
Q: Can I use this without Laravel Passport? A: No, it's specifically designed for Passport's OAuth implementation.
Q: How does threat detection work? A: Statistical analysis comparing current activity vs 30-day averages.
Q: Is my token data secure?
A: Yes. Tokens are encrypted using ext-sodium. Only metadata is stored.
📄 License
Source Available License (Proprietary).
- ✅ Allowed: Use in personal or commercial projects.
- ✅ Allowed: Modify for internal use.
- ❌ Prohibited: Redistribute, resell, or copy the source code.
See LICENSE for full details. All rights reserved.
🤝 Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
🔧 Troubleshooting
"Class OauthTokenMetric not found"
→ Run composer dump-autoload
"ext-sodium not installed" → Install:
- Ubuntu:
sudo apt-get install php8.2-sodium - Arch:
sudo pacman -S php-sodium - Fedora:
sudo dnf install php-sodium
Dashboard shows 0 tokens → Ensure Laravel Passport is properly configured and tokens exist
📞 Support
- Issues: GitHub Issues
- Security: For security vulnerabilities, please email directly instead of opening issues.
Made with ❤️ by S1b-Team
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: proprietary
- 更新时间: 2025-12-10
