$npx -y skills add Lonsdale201/wp-agent-skills --skill br-audit-enrichmentConfigure Better Route 1.1 audit events and safe enrichment. Use when logging route outcomes, authenticated identity, hashed idempotency keys, trusted client IPs, domain action metadata, or ensuring telemetry failures cannot change API behavior.
| 1 | # Better Route audit enrichment |
| 2 | |
| 3 | Run authentication first, enrichment second, and audit logging around the downstream handler. |
| 4 | |
| 5 | ```php |
| 6 | use BetterRoute\Middleware\Audit\AuditEnricherMiddleware; |
| 7 | use BetterRoute\Middleware\Audit\AuditMiddleware; |
| 8 | |
| 9 | $router->middleware([ |
| 10 | $auth, |
| 11 | new AuditEnricherMiddleware( |
| 12 | staticFields: ['resource' => 'account', 'action' => 'update'], |
| 13 | clientIpResolver: $trustedProxyResolver, |
| 14 | includeClientIp: true |
| 15 | ), |
| 16 | new AuditMiddleware($logger), |
| 17 | ]); |
| 18 | ``` |
| 19 | |
| 20 | `AuditEnricherMiddleware` writes to the context `audit` attribute. It copies the normalized authentication provider, user ID, and subject; hashes an `Idempotency-Key` with SHA-1 for correlation; optionally resolves client IP; and merges reviewed static fields. Existing fields are retained, while later enrichment values with the same name win. |
| 21 | |
| 22 | `AuditMiddleware` logs success or error with route, method, status, duration, correlation metadata, and enrichment. Logger exceptions are swallowed deliberately: observability is best-effort and must not change a successful response or mask the application exception already in flight. |
| 23 | |
| 24 | ## Rules |
| 25 | |
| 26 | - Never include bearer tokens, cookies, nonces, application passwords, HMAC secrets/signatures, payment data, full bodies, or raw idempotency keys. |
| 27 | - Treat SHA-1 here only as a non-secret correlation fingerprint, not as a security proof. |
| 28 | - Use a trusted-proxy-aware resolver before recording or acting on forwarded client IPs. |
| 29 | - Keep static values bounded and public-safe. Do not pass attacker-controlled payload arrays as static fields. |
| 30 | - Protect the log sink with access control, retention limits, rotation, and output escaping in viewers. |
| 31 | - Alert separately when the logging backend is unavailable; the request path intentionally will not fail. |
| 32 | |
| 33 | Test successful responses, `ApiException`, unexpected exceptions, logger failure, missing authentication context, and spoofed forwarded headers. |
| 34 | |
| 35 | Source references: `src/Middleware/Audit/AuditEnricherMiddleware.php`, `src/Middleware/Audit/AuditMiddleware.php`, `src/Observability/AuditEventFactory.php`. |
| 36 | |
| 37 | ## References |
| 38 | |
| 39 | - Official documentation: <https://lonsdale201.github.io/better-docs/docs/better-route/agents> |