dynamik-dev/cloak-laravel
Composer 安装命令:
composer require dynamik-dev/cloak-laravel
包简介
Laravel adapter for cloak-php - mask and unmask sensitive data
README 文档
README
Keep PII out of LLMs. Cloak masks sensitive data before sending text to AI APIs like ChatGPT or Claude, then restores the original data in responses.
Quick Start
// Mask PII before sending to an LLM $safe = cloak('Contact john@example.com or call 555-123-4567'); // "Contact {{EMAIL_x7k2m9_1}} or call {{PHONE_x7k2m9_1}}" // Restore the original data $original = uncloak($safe); // "Contact john@example.com or call 555-123-4567"
Why Cloak?
When building AI-powered features, user messages often contain sensitive information—emails, phone numbers, SSNs, credit cards. Sending this data to third-party LLM APIs creates privacy and compliance risks.
Cloak solves this by:
- Detecting PII using built-in or custom detectors
- Replacing sensitive data with placeholder tokens
- Storing the mapping temporarily (in-memory or cache)
- Restoring original data when you receive the LLM's response
The LLM never sees the actual PII, but your users get personalized responses.
Installation
composer require dynamik-dev/cloak-laravel
Optionally publish the config file:
php artisan vendor:publish --tag="cloak-config"
Configuration
// config/cloak.php return [ // false (default): In-memory storage, auto-cleared after request // true: Cache storage, persists across requests 'persist' => env('CLOAK_PERSIST', false), // Storage driver class when persist is true 'storage_driver' => DynamikDev\Cloak\Laravel\CacheStorage::class, // Cache store to use (null = default cache) 'cache_store' => env('CLOAK_CACHE_STORE'), // TTL for cached mappings in seconds 'default_ttl' => env('CLOAK_DEFAULT_TTL', 3600), ];
Encryption at Rest
This Laravel adapter integrates with cloak-php v0.2.0's encryption system using Laravel's Crypt facade. All sensitive data is encrypted before being stored, providing defense in depth—even if memory or cache is compromised, the original PII remains protected.
The encryption is handled through a custom LaravelEncryptor that implements cloak-php's EncryptorInterface, using Laravel's built-in encryption for seamless integration with your application's APP_KEY.
Persist Mode
-
persist: false(default) - In-memory storage with encryption. Perfect for single-request flows where you cloak → call LLM → uncloak in one request. Data is automatically garbage collected when the request ends. -
persist: true- Laravel cache storage with encryption. Use this when you need to uncloak in a different request (e.g., webhook responses, queued jobs). TTL is configurable viadefault_ttl.
Usage
Helper Functions
The simplest way to use Cloak:
$masked = cloak($text); $restored = uncloak($masked);
Facade
use DynamikDev\Cloak\Laravel\Facades\Cloak; $masked = Cloak::cloak($text); $restored = Cloak::uncloak($masked);
Dependency Injection
use DynamikDev\Cloak\Cloak; class ChatController extends Controller { public function send(Request $request, Cloak $cloak) { $safe = $cloak->cloak($request->input('message')); // ... } }
Real-World Example: OpenAI Integration
use OpenAI\Laravel\Facades\OpenAI; public function chat(Request $request) { $userMessage = $request->input('message'); // "Help me email john.doe@acme.com about invoice #1234. // My number is 555-867-5309 if they need to call back." // 1. Cloak PII before sending to OpenAI $safeMessage = cloak($userMessage); // "Help me email {{EMAIL_a1b2c3_1}} about invoice #1234. // My number is {{PHONE_a1b2c3_1}} if they need to call back." // 2. Send to OpenAI - no PII exposed to the API $response = OpenAI::chat()->create([ 'model' => 'gpt-4', 'messages' => [ ['role' => 'system', 'content' => 'You are a helpful assistant.'], ['role' => 'user', 'content' => $safeMessage], ], ]); // 3. Get the response (LLM uses placeholders naturally) $aiResponse = $response->choices[0]->message->content; // "Here's a draft email for {{EMAIL_a1b2c3_1}}: // Subject: Regarding Invoice #1234..." // 4. Restore PII for the user $finalResponse = uncloak($aiResponse); // "Here's a draft email for john.doe@acme.com: // Subject: Regarding Invoice #1234..." return response()->json(['response' => $finalResponse]); }
Built-in Detectors
Cloak automatically detects:
| Type | Example | Placeholder |
|---|---|---|
john@example.com |
{{EMAIL_x1y2z3_1}} |
|
| Phone | 555-123-4567 |
{{PHONE_x1y2z3_1}} |
| SSN | 123-45-6789 |
{{SSN_x1y2z3_1}} |
| Credit Card | 4111-1111-1111-1111 |
{{CREDIT_CARD_x1y2z3_1}} |
By default, all detectors run. To use specific detectors:
use DynamikDev\Cloak\Detector; // Only detect emails and phones $masked = cloak($text, [ Detector::email(), Detector::phone(), ]); // Phone detection with region hint (improves accuracy) $masked = cloak($text, [ Detector::phone('US'), ]);
Custom Detectors
Pattern Detector (Regex)
use DynamikDev\Cloak\Detector; // Detect database connection strings $masked = cloak($text, [ Detector::pattern( '/mysql:\/\/[^:]+:[^@]+@[^\s]+/', 'DB_CONNECTION' ), ]); // Detect API keys $masked = cloak($text, [ Detector::pattern( '/sk-[a-zA-Z0-9]{32,}/', 'API_KEY' ), ]);
Word Detector
use DynamikDev\Cloak\Detector; // Mask specific names or terms (case-insensitive) $masked = cloak($text, [ Detector::words(['John Doe', 'Jane Smith', 'Acme Corp'], 'NAME'), ]);
Callback Detector
For complex detection logic:
use DynamikDev\Cloak\Detector; $masked = cloak($text, [ Detector::using(function (string $text) { // Return array of ['match' => '...', 'type' => '...'] $matches = []; // Example: Find Laravel env variables if (preg_match_all('/\bDB_PASSWORD=\S+/', $text, $found)) { foreach ($found[0] as $match) { $matches[] = ['match' => $match, 'type' => 'ENV_VAR']; } } return $matches; }), ]);
Middleware Example
Auto-cloak sensitive data in request logs:
namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; class LogSafeRequests { public function handle(Request $request, Closure $next) { // Log request with PII masked Log::info('API Request', [ 'path' => $request->path(), 'body' => cloak(json_encode($request->all())), ]); return $next($request); } }
Testing
composer test
Version Compatibility
This package has been updated to work with cloak-php v0.2.0, which includes:
- New builder pattern API for configuring Cloak instances
- Pluggable encryption system via
EncryptorInterface - Enhanced lifecycle hooks and filtering capabilities
- Simplified storage interface (TTL handling moved to storage implementations)
What Changed in v0.2.0
Architecture improvements:
- Now uses cloak-php's
ArrayStorefor in-memory storage (instead of customEncryptedArrayStorage) - Implements a
LaravelEncryptorthat integrates with Laravel'sCryptfacade - Service provider uses the builder pattern:
Cloak::using($store)->withEncryptor($encryptor) - Uses
Cloak::resolveUsing()to integrate with Laravel's container - Helper functions now provided by core package (Laravel-specific helpers removed)
- TTL configuration is Laravel-specific and handled within
CacheStorageconstructor
Container Binding Strategy (Octane-safe):
Cloakinstances usebind()- fresh instance on every resolution (prevents state pollution)StoreInterfaceusessingleton()- shared storage for placeholder mappingsEncryptorInterfaceusessingleton()- stateless encryption service
This architecture prevents issues with filters, callbacks, and other stateful configurations, especially in Laravel Octane environments where state can leak between requests.
Breaking changes from previous versions:
EncryptedArrayStorageclass has been removed (now uses coreArrayStorewithLaravelEncryptor)StoreInterface::put()no longer accepts$ttlparameter (moved to storage implementation constructor)- Laravel-specific helper functions removed (now uses core package helpers via resolver)
The package maintains backward compatibility at the API level—all helpers, facades, and configuration options work the same way for end users.
Advanced Usage: Extending Cloak
The resolver pattern allows developers to customize Cloak behavior through the container:
// In your AppServiceProvider use DynamikDev\Cloak\Cloak; use DynamikDev\Cloak\Detector; $this->app->extend(Cloak::class, function ($cloak, $app) { return $cloak->withDetectors([ Detector::email(), Detector::phone('US'), // Add your custom detectors ])->filter(function ($detection) { // Filter out test emails return !str_ends_with($detection['match'], '@test.local'); }); });
Each call to cloak() or app(Cloak::class) gets a fresh instance with your customizations, preventing state pollution across requests.
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.
dynamik-dev/cloak-laravel 适用场景与选型建议
dynamik-dev/cloak-laravel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 11 月 25 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「cloak」 「Masking」 「pii」 「DynamikDev」 「sensitive-data」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 dynamik-dev/cloak-laravel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 dynamik-dev/cloak-laravel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 dynamik-dev/cloak-laravel 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Laravel Profanity Filter - Powerful PHP package for detecting, filtering, and masking profanity in multiple languages. Supports leet speak, custom word lists, case sensitivity, and seamless Laravel integration.
Abstraction library for code coverage analysis
PHP library for data redaction, masking, and sanitization with optional Monolog integration.
Cloaks sensitive data
Official PHP integration for Optidash - AI-powered image optimization and processing API. We will drastically speed-up your websites and save you money on bandwidth and storage.
Official Laravel Facade for Optidash - AI-powered image optimization and processing API. We will drastically speed-up your websites and save you money on bandwidth and storage.
统计信息
- 总下载量: 2
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 29
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-11-25
