PanagiotisKotsorgios/acme-security-kit
GitHub: PanagiotisKotsorgios/acme-security-kit
为 PHP 8.2+ 应用提供模块化安全组件,涵盖认证、授权、加密与审计的一站式防护能力。
Stars: 0 | Forks: 0
# acme/security-kit
[](https://php.net)
[](https://phpstan.org)
[](LICENSE)
[](https://github.com/acme/security-kit/actions)
## 模块
| Module | Description |
|--------|-------------|
| **Crypto** | 安全随机数、恒定时间比较、密钥集 + JWKS 导出 |
| **CSRF** | 无状态 HMAC token,支持表单上下文、TTL 和轮换 |
| **UrlSigner** | HMAC-SHA256 签名 URL,支持密钥轮换和规范查询排序 |
| **JWT** | RS256/ES256/HS256 token 签发与验证,严格声明检查 |
| **OAuth2** | 存储接口、PKCE 验证、token TTL 策略、刷新轮换 |
| **Password** | Argon2id 哈希、策略强制执行、登录时重哈希助手 |
| **TOTP** | 符合 RFC 6238,Base32,可配置步长/位数/算法 |
| **Authz** | RBAC 角色继承 + ABAC-lite 属性回调 |
| **Audit** | PSR-3 结构化安全事件日志 |
## 环境要求
- PHP 8.2+
- 扩展:`openssl`、`mbstring`
## 安装
```
composer require acme/security-kit
```
## 快速入门
### CSRF 防护
```
use Acme\SecurityKit\Crypto\{HashEquals, SecureRandom};
use Acme\SecurityKit\Csrf\{HmacCsrfManager, CsrfPolicy};
$manager = new HmacCsrfManager(
secret: 'your-32-byte-secret-here!!!!!!!!!',
random: new SecureRandom(),
constantTime: new HashEquals(),
policy: new CsrfPolicy(ttlSeconds: 3600),
);
$token = $manager->issue($sessionId, 'transfer_funds');
if (!$manager->validate($sessionId, 'transfer_funds', $submitted)) {
throw new \RuntimeException('CSRF validation failed');
}
```
### 签名 URL
```
use Acme\SecurityKit\Crypto\{InMemoryKeyProvider, Key, HashEquals};
use Acme\SecurityKit\UrlSigner\HmacUrlSigner;
$key = new Key('k1', 'HS256', 'your-signing-secret', isSymmetric: true);
$signer = new HmacUrlSigner(new InMemoryKeyProvider($key), new HashEquals());
$signed = $signer->sign('https://app.example.com/download/file.pdf', new \DateTimeImmutable('+1 hour'));
if (!$signer->verify($request->getUri())) {
// 403 Forbidden
}
```
### JWT
```
use Acme\SecurityKit\Jwt\{FirebaseJwtManager, JwtConfig};
$manager = new FirebaseJwtManager(
config: new JwtConfig(issuer: 'https://auth.example.com', audience: 'api'),
keyProvider: $keyProvider,
random: new SecureRandom(),
);
$jwt = $manager->mint(['sub' => 'user-42', 'roles' => ['editor']], new \DateTimeImmutable('+1 hour'));
$verified = $manager->parseAndValidate($jwt);
echo $verified->claim('sub'); // "user-42"
```
### 密码哈希
```
use Acme\SecurityKit\Password\{Argon2idHasher, PolicyAwareHasher, PasswordPolicy};
$hasher = new PolicyAwareHasher(new Argon2idHasher(), new PasswordPolicy(minLength: 12));
$hash = $hasher->hash($plaintext);
if ($hasher->needsRehash($hash)) {
$hash = $hasher->hash($plaintext); // upgrade on next login
}
```
### TOTP (双因素认证)
```
use Acme\SecurityKit\Totp\{RfcTotp, TotpConfig};
$totp = new RfcTotp(new SecureRandom(), new TotpConfig(digits: 6, step: 30));
$secret = $totp->generateSecret();
$uri = $totp->provisioningUri('user@example.com', 'MyApp', $secret);
if (!$totp->verify($secret, $submittedCode)) {
// 401 Unauthorized
}
```
### RBAC 授权
```
use Acme\SecurityKit\Authz\{RbacAuthorizer, Role, InMemoryRoleRepository, InMemoryAssignmentRepository};
$roles = new InMemoryRoleRepository();
$assigns = new InMemoryAssignmentRepository();
$roles->add(new Role('viewer', permissions: ['read:posts']));
$roles->add(new Role('editor', parents: ['viewer'], permissions: ['edit:posts']));
$assigns->assign('user-42', ['editor']);
$authz = new RbacAuthorizer($roles, $assigns);
$decision = $authz->can('user-42', 'read', 'posts');
if (!$decision->allowed) {
// 403 Forbidden — $decision->reason explains why
}
```
## PSR-15 中间件
将这些放入任何兼容 PSR-15 的中间件堆栈中(Slim、Mezzio、Laravel Pipeline 等):
```
$app->pipe(new CsrfMiddleware($csrfManager, $responseFactory, $auditor));
$app->pipe(new SignedUrlMiddleware($urlSigner, $responseFactory, $auditor));
```
完整的框架集成示例位于 [`examples/`](examples/) 中。
## 安全保障
- 所有随机值均使用 `random_bytes()` (CSPRNG)。
- 所有秘密/令牌比较均使用 `hash_equals()` (恒定时间)。
- Argon2id 是默认的密码哈希算法 (内存密集型,抗 GPU)。
- JWT:算法在 `JwtConfig` 中进行服务端配置 — 切勿从 token 头部读取。
- PKCE:仅接受 `S256`;拒绝 `plain` 方法。
- CSRF token 作用于 `(sessionId, context)` 对,以防止跨表单重放。
## 非目标
完整的威胁模型请参阅 [`docs/threat-model.md`](docs/threat-model.md)。
- TLS / 传输安全
- 速率限制 / DDoS 防护
- 完整的 OAuth2 授权服务器 (请使用 [`league/oauth2-server`](https://oauth2.thephpleague.com))
- 硬件安全模块 (HSM) 密钥管理
## 开发
```
composer install
vendor/bin/phpunit # tests
vendor/bin/phpstan analyse # static analysis (level 8)
vendor/bin/php-cs-fixer check --diff # code style check
vendor/bin/rector process --dry-run # upgrade suggestions
vendor/bin/infection --min-msi=70 # mutation testing
```
CI 在每次推送到 `main` 时,会在 PHP 8.2、8.3 和 8.4 上运行 PHPUnit,在级别 8 运行 PHPStan,以及运行 CS Fixer 和变异测试。
## 安全
**切勿公开提 GitHub issue 来报告安全漏洞。**
请遵循 [SECURITY.md](SECURITY.md) 中的负责任披露流程。
## 许可证
MIT。请参阅 [LICENSE](LICENSE)。
[](https://php.net)
[](https://phpstan.org)
[](LICENSE)
[](https://github.com/acme/security-kit/actions)
## 模块
| Module | Description |
|--------|-------------|
| **Crypto** | 安全随机数、恒定时间比较、密钥集 + JWKS 导出 |
| **CSRF** | 无状态 HMAC token,支持表单上下文、TTL 和轮换 |
| **UrlSigner** | HMAC-SHA256 签名 URL,支持密钥轮换和规范查询排序 |
| **JWT** | RS256/ES256/HS256 token 签发与验证,严格声明检查 |
| **OAuth2** | 存储接口、PKCE 验证、token TTL 策略、刷新轮换 |
| **Password** | Argon2id 哈希、策略强制执行、登录时重哈希助手 |
| **TOTP** | 符合 RFC 6238,Base32,可配置步长/位数/算法 |
| **Authz** | RBAC 角色继承 + ABAC-lite 属性回调 |
| **Audit** | PSR-3 结构化安全事件日志 |
## 环境要求
- PHP 8.2+
- 扩展:`openssl`、`mbstring`
## 安装
```
composer require acme/security-kit
```
## 快速入门
### CSRF 防护
```
use Acme\SecurityKit\Crypto\{HashEquals, SecureRandom};
use Acme\SecurityKit\Csrf\{HmacCsrfManager, CsrfPolicy};
$manager = new HmacCsrfManager(
secret: 'your-32-byte-secret-here!!!!!!!!!',
random: new SecureRandom(),
constantTime: new HashEquals(),
policy: new CsrfPolicy(ttlSeconds: 3600),
);
$token = $manager->issue($sessionId, 'transfer_funds');
if (!$manager->validate($sessionId, 'transfer_funds', $submitted)) {
throw new \RuntimeException('CSRF validation failed');
}
```
### 签名 URL
```
use Acme\SecurityKit\Crypto\{InMemoryKeyProvider, Key, HashEquals};
use Acme\SecurityKit\UrlSigner\HmacUrlSigner;
$key = new Key('k1', 'HS256', 'your-signing-secret', isSymmetric: true);
$signer = new HmacUrlSigner(new InMemoryKeyProvider($key), new HashEquals());
$signed = $signer->sign('https://app.example.com/download/file.pdf', new \DateTimeImmutable('+1 hour'));
if (!$signer->verify($request->getUri())) {
// 403 Forbidden
}
```
### JWT
```
use Acme\SecurityKit\Jwt\{FirebaseJwtManager, JwtConfig};
$manager = new FirebaseJwtManager(
config: new JwtConfig(issuer: 'https://auth.example.com', audience: 'api'),
keyProvider: $keyProvider,
random: new SecureRandom(),
);
$jwt = $manager->mint(['sub' => 'user-42', 'roles' => ['editor']], new \DateTimeImmutable('+1 hour'));
$verified = $manager->parseAndValidate($jwt);
echo $verified->claim('sub'); // "user-42"
```
### 密码哈希
```
use Acme\SecurityKit\Password\{Argon2idHasher, PolicyAwareHasher, PasswordPolicy};
$hasher = new PolicyAwareHasher(new Argon2idHasher(), new PasswordPolicy(minLength: 12));
$hash = $hasher->hash($plaintext);
if ($hasher->needsRehash($hash)) {
$hash = $hasher->hash($plaintext); // upgrade on next login
}
```
### TOTP (双因素认证)
```
use Acme\SecurityKit\Totp\{RfcTotp, TotpConfig};
$totp = new RfcTotp(new SecureRandom(), new TotpConfig(digits: 6, step: 30));
$secret = $totp->generateSecret();
$uri = $totp->provisioningUri('user@example.com', 'MyApp', $secret);
if (!$totp->verify($secret, $submittedCode)) {
// 401 Unauthorized
}
```
### RBAC 授权
```
use Acme\SecurityKit\Authz\{RbacAuthorizer, Role, InMemoryRoleRepository, InMemoryAssignmentRepository};
$roles = new InMemoryRoleRepository();
$assigns = new InMemoryAssignmentRepository();
$roles->add(new Role('viewer', permissions: ['read:posts']));
$roles->add(new Role('editor', parents: ['viewer'], permissions: ['edit:posts']));
$assigns->assign('user-42', ['editor']);
$authz = new RbacAuthorizer($roles, $assigns);
$decision = $authz->can('user-42', 'read', 'posts');
if (!$decision->allowed) {
// 403 Forbidden — $decision->reason explains why
}
```
## PSR-15 中间件
将这些放入任何兼容 PSR-15 的中间件堆栈中(Slim、Mezzio、Laravel Pipeline 等):
```
$app->pipe(new CsrfMiddleware($csrfManager, $responseFactory, $auditor));
$app->pipe(new SignedUrlMiddleware($urlSigner, $responseFactory, $auditor));
```
完整的框架集成示例位于 [`examples/`](examples/) 中。
## 安全保障
- 所有随机值均使用 `random_bytes()` (CSPRNG)。
- 所有秘密/令牌比较均使用 `hash_equals()` (恒定时间)。
- Argon2id 是默认的密码哈希算法 (内存密集型,抗 GPU)。
- JWT:算法在 `JwtConfig` 中进行服务端配置 — 切勿从 token 头部读取。
- PKCE:仅接受 `S256`;拒绝 `plain` 方法。
- CSRF token 作用于 `(sessionId, context)` 对,以防止跨表单重放。
## 非目标
完整的威胁模型请参阅 [`docs/threat-model.md`](docs/threat-model.md)。
- TLS / 传输安全
- 速率限制 / DDoS 防护
- 完整的 OAuth2 授权服务器 (请使用 [`league/oauth2-server`](https://oauth2.thephpleague.com))
- 硬件安全模块 (HSM) 密钥管理
## 开发
```
composer install
vendor/bin/phpunit # tests
vendor/bin/phpstan analyse # static analysis (level 8)
vendor/bin/php-cs-fixer check --diff # code style check
vendor/bin/rector process --dry-run # upgrade suggestions
vendor/bin/infection --min-msi=70 # mutation testing
```
CI 在每次推送到 `main` 时,会在 PHP 8.2、8.3 和 8.4 上运行 PHPUnit,在级别 8 运行 PHPStan,以及运行 CS Fixer 和变异测试。
## 安全
**切勿公开提 GitHub issue 来报告安全漏洞。**
请遵循 [SECURITY.md](SECURITY.md) 中的负责任披露流程。
## 许可证
MIT。请参阅 [LICENSE](LICENSE)。标签:Argon2id, CSRF防护, ffuf, HMAC, JSON Web Token, JWT, OAuth2, OpenAPI, OpenVAS, PHP, PHP 8.2, PKCE, PSR标准, RBAC, Security Toolkit, TOTP, Web安全, 人工智能安全, 双因素认证, 合规性, 安全工具包, 安全测试工具, 审计日志, 密码哈希, 授权, 权限管理, 模型越狱, 签名URL, 网络安全库, 蓝队分析, 防御跨站请求伪造