zappzarapp / security
Comprehensive PHP security library: CSP, Security Headers, CSRF, Cookies, Password Validation, Input Sanitization, Rate Limiting, SRI, and Audit Logging
Requires
- php: ^8.4
- ext-dom: *
- ext-libxml: *
- ext-sodium: *
Requires (Dev)
- ext-fileinfo: *
- captainhook/captainhook: *
- captainhook/plugin-composer: ^5.3
- cyclonedx/cyclonedx-php-composer: ^6.1
- deptrac/deptrac: ^4.5
- ekino/phpstan-banned-code: ^3.0
- friendsofphp/php-cs-fixer: ^3.91
- giorgiosironi/eris: ^1.0
- infection/infection: *
- phpdocumentor/phpdocumentor: ^3.6
- phpmd/phpmd: ^2.15
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^13.1
- psr/clock: ^1.0
- psr/http-client: ^1.0
- psr/http-factory: ^1.1
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
- psr/log: ^1.1 || ^3.0
- rector/rector: ^2.3
- roave/security-advisories: dev-latest
- vimeo/psalm: ^6.14
Suggests
- ext-memcached: For Memcached rate limit storage
- ext-pdo: For PDO rate limit and CSRF token storage (MySQL, PostgreSQL, SQLite)
- ext-redis: For Redis rate limit and CSRF token storage (phpredis extension)
- predis/predis: For Redis rate limit and CSRF token storage (pure PHP client)
- psr/clock: For deterministic time injection in SessionGuard (PSR-20)
- psr/http-client: For PSR-18 HTTP client support in PwnedPasswordChecker
- psr/http-factory: For PSR-17 HTTP factory support in PwnedPasswordChecker
- psr/http-message: For PSR-7 response analysis in SecurityHeaderAnalyzer
- psr/http-server-handler: For PSR-15 middleware support
- psr/http-server-middleware: For PSR-15 middleware support
- psr/log: For security event audit logging (PSR-3)
Provides
None
Conflicts
None
Replaces
None
README
Comprehensive PHP security library providing CSP, Security Headers, CSRF protection, Secure Cookies, Password Validation, Input Sanitization, Rate Limiting, SRI, Secrets Loading, Encryption, Session Security, TOTP two-factor authentication, Signed URLs, and Security Event Logging.
Highlights
- All-in-one — 17 security modules in a single, composable package
- Secure by default — strict CSP, no
unsafe-*, HTTPS-first - Framework-agnostic — works with any PHP 8.4+ application
- Immutable & type-safe — readonly classes, enums,
with*()API - Quality-backed — PHPStan Level 8, Psalm Level 1, 100% Mutation Score, Deptrac architecture enforcement
- PSR-compatible — PSR-3 (Logging), PSR-15 (Middleware), PSR-18 (HTTP Client)
Modules
| Module | Description | Key Classes |
|---|---|---|
| CSP | Content Security Policy header building and violation reporting | CspDirectives, HeaderBuilder, NonceGenerator, CspReportParser |
| Headers | Security headers (HSTS, Permissions-Policy, etc.) | SecurityHeaders, SecurityHeadersBuilder |
| CSRF | Cross-Site Request Forgery protection | CsrfProtection, CsrfConfig |
| Cookie | Secure cookie handling | SecureCookie, CookieBuilder, CookieOptions |
| Encryption | XChaCha20-Poly1305 authenticated encryption | SymmetricEncryptor, EnvelopeEncryptor, EncryptionKey, KeyRingEncryptor |
| Password | Password validation and hashing | PasswordPolicy, PwnedPasswordChecker, PepperedPasswordHasher |
| Sanitization | Input sanitization (HTML, SQL, URI, Path) and file upload validation | HtmlSanitizer, UriSanitizer, PathValidator, UploadValidator |
| RateLimiting | Rate limiting with multiple algorithms | DefaultRateLimiter, RateLimitConfig |
| SRI | Subresource Integrity hash generation | SriHashGenerator, IntegrityAttribute |
| Secrets | Docker/file-based secret loading | SecretLoader, SecretValue, FileSecretSource |
| Session | Session hardening and fixation protection | SessionGuard, SessionConfig, SessionConfigurator |
| SignedUrl | HMAC-signed URLs with mandatory expiry | UrlSigner, SigningKey |
| TOTP | Time-based one-time passwords (RFC 6238) | TotpAuthenticator, TotpSecret, ProvisioningUri, RecoveryCodeGenerator |
| Analyzer | Security header analysis and auditing | SecurityHeaderAnalyzer, AnalysisResult |
| Scanner | CLI security header scanner | ScanCommand, StreamHeaderFetcher |
| Middleware | PSR-15 middleware for drop-in framework integration | SecurityHeadersMiddleware, CspMiddleware, CspReportHandler, CsrfMiddleware, DoubleSubmitCsrfMiddleware, RateLimitMiddleware, CorsMiddleware |
| Logging | Security event logging | SecurityAuditLogger, SecurityEvent |
Requirements
- PHP ^8.4
ext-domext-libxmlext-sodium
Installation
composer require zappzarapp/security
Quick Start
Security Headers
use Zappzarapp\Security\Headers\Builder\SecurityHeadersBuilder; $headers = SecurityHeadersBuilder::recommended()->build(); foreach ($headers as $name => $value) { header("{$name}: {$value}"); }
CSP with Nonces
use Zappzarapp\Security\Csp\HeaderBuilder; use Zappzarapp\Security\Csp\Directive\CspDirectives; use Zappzarapp\Security\Csp\Nonce\NonceGenerator; $generator = new NonceGenerator(); $csp = HeaderBuilder::build(CspDirectives::strict(), $generator); header("Content-Security-Policy: {$csp}"); $nonce = $generator->get(); echo "<script nonce=\"{$nonce}\">console.log('Safe!');</script>";
CSRF Protection
use Zappzarapp\Security\Csrf\CsrfProtection; use Zappzarapp\Security\Csrf\Storage\SessionCsrfStorage; $csrf = new CsrfProtection(new SessionCsrfStorage()); // Generate token for form $token = $csrf->generateToken(); echo '<input type="hidden" name="_token" value="' . $token->value() . '">'; // Validate on submission if (!$csrf->validateToken($_POST['_token'])) { throw new Exception('CSRF validation failed'); }
Input Sanitization
use Zappzarapp\Security\Sanitization\Html\HtmlSanitizer; use Zappzarapp\Security\Sanitization\Path\PathValidationConfig; use Zappzarapp\Security\Sanitization\Path\PathValidator; // Sanitize HTML (removes dangerous tags/attributes) $sanitizer = new HtmlSanitizer(); $safe = $sanitizer->sanitize($userInput); // Validate file paths (prevent directory traversal) $validator = new PathValidator(new PathValidationConfig(basePath: '/var/www/uploads')); if (!$validator->isSafe($userPath)) { throw new Exception('Invalid path'); }
See the documentation for detailed examples of all modules.
Documentation
Each module has detailed API documentation with class references, configuration options, and code examples:
| Module | Description |
|---|---|
| CSP | Content Security Policy with nonces and violation reporting |
| Headers | HSTS, COOP, COEP, CORP, Permissions |
| CSRF | Token patterns and validation |
| Cookie | Secure cookie handling |
| Encryption | Authenticated encryption, envelopes |
| Password | Hashing, policies, breach detection |
| Sanitization | HTML, URI, path sanitization and file upload validation |
| Rate Limiting | Token bucket, sliding window |
| SRI | Subresource integrity hashes |
| Secrets | Docker/file-based secret loading |
| Session | Session hardening, fingerprinting |
| Signed URLs | HMAC-signed URLs with expiry |
| TOTP | One-time passwords, recovery codes |
| Analyzer | Security header auditing |
| Scanner | CLI header scanner for CI |
| Middleware | PSR-15 middleware |
| Logging | Security event logging |
| Glossary | Security terminology reference |
Versioning
This library follows Semantic Versioning 2.0.0.
All classes, interfaces, and methods in the Zappzarapp\Security namespace are
considered public API unless marked with @internal. Breaking changes only
happen in major versions, with deprecation warnings at least one minor version
before removal.
Releases are automated via release-please and GPG-signed. See CHANGELOG.md for release history.
Security
See SECURITY.md for vulnerability reporting and security considerations.
Contributing
See CONTRIBUTING.md for development setup and contribution guidelines.
License
MIT License - see LICENSE file for details.