Skip to content

feat: security event log with entity tracking, login throttle, metrics & admin ui - #3229

Merged
tada5hi merged 15 commits into
masterfrom
feat/roadmap-wave2-audit-spine
Jul 12, 2026
Merged

tada5hi merged 15 commits into
masterfrom
feat/roadmap-wave2-audit-spine

Conversation

@tada5hi

@tada5hi tada5hi commented Jul 11, 2026 •

Copy link
Copy Markdown
Collaborator

Overview

Roadmap wave 2: the security event system in one PR — plan 057 (persisted event log, both stages: explicit security events + the entity-CRUD bridge), plan 053 (failed-login throttle), plan 058 Part 2 (auth-flow metrics counters), and the admin UI. One shared emit infrastructure, one table (auth_events), four consumers.

Design provenance

The system was designed from a deep investigation of PrivateAIM/hub's @privateaim/telemetry-kit / server-telemetry event system (itself Authentik-derived) and adopts its shape 1:1 — Event domain, (scope, name) verb pair (camelCase vocabulary per hub convention: loginFailed, refreshReplayDetected, …), ref_type/ref_id target reference, denormalized actor_type/actor_id/actor_name snapshot (survives actor deletion), request_* context group, expiring + per-row expires_at retention, data as text behind the @authup/kit serialize/deserialize transformer, EVENT_READ permission, GET /events, client.event — while fixing what hub's own implementation lacks:

hub weakness here
open string taxonomy closed EventName/EventScope enums
mutable events (updated_at, dead update() client route) append-only: read-only API, no update/delete, no updated_at
no PII stripping allowlist-first scalars-only sanitizer + secret-denylist on diff keys
serialize(null) persists the string 'null' null-guarded transformer
varchar(15) IPv4-only IP column (::1 rewrite hack) varchar(45)
realm_id (the primary read filter) unindexed; 14 indexes elsewhere realm_id indexed; 10 justified indexes total
hard-coded WEEK_IN_MS retention config-driven per-row retention

The full hub↔authup mapping + the back-port checklist ship in .agents/references/privateaim-hub.md, tracked upstream as PrivateAIM/hub#1745.

What ships

  • auth_events (fresh dual-dialect migration 1783769340000): no FKs by design — rows survive deletion of everything they reference. EventService.record() is fire-and-forget-safe (a write failure logs, never fails the originating operation), stamps expiring/expires_at from the retention config, and emits a structured logger line even with persistence off — free SIEM/Loki forwarding.
  • Security events (explicit emits): login, loginFailed (canonicalized attempted identifier in actor_name, actor_id null — the documented PII-posture call; it is the throttle key), authorize (data.reason: autoConsent|consent), logout (end-session hint revoke), refreshReplayDetected, register, accountActivated, passwordResetRequested/Completed. No per-token rows — auth_session_tokens already inventories issuance.
  • Entity-CRUD tracking: every subscriber-published create/update/delete also lands as a row (scope: entity, ref_type/ref_id, realm-gated) via an EntityEventHandler on the existing domain-event bus — the pre-mutation snapshot rides the publish context (never the shared realtime wire payload); actor + request attribution via an AsyncLocalStorage request-event-context mounted after the authorization middleware (non-HTTP writes = system/null actor); scalar diffs exclude secret-shaped keys (password|secret|hash|token|credential) and *_at columns and are re-validated at the write boundary; created/deleted rows carry no column dumps; entity rows self-prune (EVENT_LOG_ENTITY_RETENTION_DAYS, default 7d; gated by EVENT_LOG_ENTITY_ENABLED).
  • Read API + admin UI: GET /events (+ realm mount), read-only, EVENT_READ-gated with the session-service shape (self-scope fallback, per-row realm-reach drops, force-selected gate columns — plan-039 discipline, red-green-verified). /events pages in client-web (typed VCTable list with name search + pagination; hub-style detail page with General/Actor/Request cards + pretty-printed data), kit <AEvents> collection, EVENT_READ-gated nav, entity/field i18n in all four locales.
  • Retention sweeper: per-minute component, hub's cleaner predicate (expiring = true AND expires_at < now); rejection-proof startup (both cleaners catch per tick; the components module catches every start()).
  • Failed-login throttle (default off): recent loginFailed rows counted per (identifier, ip) pair over indexed columns — never identifier alone (account-lockout-DoS mitigation; no derivable IP → fail open). HTTP 429 login_attempt_throttled with retryAfter; i18n in four locales; enabling it without the event log fails loud at boot. Dead AttemptLogin type deleted. X-Forwarded-For trust documented; repo-wide TRUST_PROXY configurability tracked in Make getRequestIP proxy trust configurable (trustProxy is hardcoded) #3230.
  • Metrics counters (default prom-client registry, idempotent): authup_login_total{result}, authup_token_grant_total{grant_type} (successes only), authup_authorize_total{outcome} (denied reserved until plan 052), authup_refresh_replay_total. Noop when middlewarePrometheus is off. Bounded label sets only.
  • Config: EVENT_LOG_ENABLED, EVENT_LOG_RETENTION_DAYS, EVENT_LOG_ENTITY_ENABLED, EVENT_LOG_ENTITY_RETENTION_DAYS, LOGIN_ATTEMPT_THROTTLE_ENABLED, LOGIN_ATTEMPT_THRESHOLD, LOGIN_ATTEMPT_WINDOW — all in the deployment reference; agent docs gain a Security Event Log section.

Verification

  • Server-core: 135 files / 1412 tests green (+158 vs. the wave-0 baseline: sanitizer table, service scoping/retention, throttle invariants, HTTP read API, red-green realm-isolation projection spec, end-to-end 429 flow, /metrics scrape, config fail-loud, replay emit, diff builder, bridge handler, end-to-end bridge attribution incl. secret-free client-secret-rotation diff).
  • client-web-kit: vue-tsc + 106/106; i18n parity 77/77; client-web nuxi typecheck + full nuxt build; core-kit/server-kit/core-http-kit rebuilt; check:types + eslint clean; migrations verified by the tests-migrations round-trip in CI.

Notes for reviewers

Summary by CodeRabbit

  • New Features
    • Added a read-only Events section with searchable, paginated lists and detailed event views.
    • Added security event tracking for authentication, account, password, logout, and entity activity.
    • Added client API support for retrieving event collections and individual events.
    • Added configurable failed-login throttling with HTTP 429 responses and retry information.
    • Added authentication-flow metrics for Prometheus monitoring.
  • Documentation
    • Documented event retention, audit settings, and login-throttling configuration.
  • Bug Fixes
    • Improved isolation so event visibility respects permissions and realm boundaries.

tada5hi added 7 commits July 11, 2026 11:31
…dMany adapters

A client fields projection (e.g. ?fields[user]=id,name) stripped realm_id
from the SQL SELECT, so the per-row realm_scope gate evaluated against a
missing resource realm: ownOrNull-scoped readers received every realm's
rows (cross-realm disclosure - for clients including a plaintext-secret
gate misfire), while own-scoped readers were wrongly denied their own
rows. The shared applyRealmScopeSelect helper now re-adds realm_id plus
the other gate-read columns after applyQuery in the user, robot, client,
role-attribute and user-attribute adapters (session migrated onto the
same helper). Role/scope/permission/policy list reads carry no per-row
realm gate and are unaffected.
The prometheus middleware skip() excluded /authorize and /token, leaving
the generic per-route histogram blind to the security-critical endpoints.
Only the /metrics self-scrape and the root status endpoint stay excluded;
both metered paths are fixed strings, so there is no label-cardinality
risk.
The UserValidator accepted 3-character passwords and the password-reset
flow enforced an inconsistent minimum of 5. The floor is now a validator
option defaulting to 10 (NIST 800-63B posture: length only, no
composition rules), driven by the new passwordMinLength config key
(env PASSWORD_MIN_LENGTH) and threaded to every password-write site:
user create/update, registration and password reset. Applies to new
writes only - existing password hashes keep verifying.
Client.grant_types existed end-to-end but was never read by an
enforcement path. A non-null (space- or comma-delimited) list is now an
opt-in allowlist checked after client resolution in the
authorization_code, refresh_token (incl. the bound-client-from-token
path), client_credentials and password grants, and in the /authorize
code-request verifier (authorization_code membership, denied before the
consent UI renders). Violations fail with the new unauthorized_client
error code (RFC 6749 §5.2). A null column keeps allow-all semantics, so
upgrades are backward compatible; deployments that stored decorative
grant_types values should review them before upgrading.
…ow metrics

Adds the persisted, PII-stripped security audit trail (plan 057 stage 1)
as a first-class audit-event domain: closed AuditEventName/Scope taxonomy
in core-kit, an append-only audit_events table (no FKs - rows survive
deletion of everything they reference; per-row expires_at retention
stamped from auditLogRetentionDays and swept by a cleaner component), a
fire-and-forget write service behind an allowlist-first scalar-only
sanitizer, and a read-only dual-mounted /audit-events API gated by the
new audit_read permission with the session-service self-scope +
per-row realm-reach shape (gate columns force-selected). The record
shape follows the hub telemetry Event model (scope/name pair,
ref_type/ref_id, denormalized actor snapshot, request context group).

Explicit emits (never the CRUD bus): login, login_failed (canonicalized
attempted identifier in actor_name), authorize, logout, refresh replay,
register, account activation, password reset requested/completed.

On top of the same table, the failed-login throttle (plan 053, default
off): (identifier, ip)-pair keyed counting over indexed columns, HTTP
429 login_attempt_throttled with retryAfter, fail-loud config check
when enabled without the audit log, and the dead AttemptLogin core-kit
type is removed.

Auth-flow metrics counters (plan 058 part 2): IAuthFlowMetrics port with
noop + prom-client adapters on the default registry - authup_login_total,
authup_token_grant_total, authup_authorize_total (denied reserved),
authup_refresh_replay_total.
Copilot AI review requested due to automatic review settings July 11, 2026 13:07
@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@tada5hi, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 11 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: abd0967c-dcbf-46ec-a964-3963abe6fbac

📥 Commits

Reviewing files that changed from the base of the PR and between 4bf7216 and bfd4ee8.

📒 Files selected for processing (5)
  • apps/server-core/src/app/modules/components/module.ts
  • apps/server-core/src/components/event-cleaner/module.ts
  • apps/server-core/src/components/oauth2-cleaner/module.ts
  • apps/server-core/src/core/entities/event/entity-event-handler.ts
  • apps/server-core/test/unit/core/entities/event/entity-event-handler.spec.ts
📝 Walkthrough

Walkthrough

Adds a persisted, PII-sanitized, append-only security event log with authenticated read APIs and an admin UI. Authentication flows emit audit events and Prometheus metrics, failed logins can be throttled, and entity CRUD events can be mirrored with sanitized diffs and retention cleanup.

Changes

Security event platform

Layer / File(s) Summary
Event contracts, persistence, and retention
packages/core-kit/src/domains/event/*, apps/server-core/src/core/entities/event/types.ts, apps/server-core/src/adapters/database/..., apps/server-core/src/components/event-cleaner/*
Defines event taxonomy and entity types, creates the auth_events table, adds repository/service contracts, configures retention, and schedules expired-row cleanup.
Sanitization and entity-event bridge
apps/server-core/src/core/entities/event/*, apps/server-core/src/adapters/database/subscriber/module.ts, apps/server-core/src/adapters/http/request/event-context.ts
Sanitizes event payloads, strips secrets, builds scalar diffs, captures request attribution, and mirrors entity create/update/delete events.
Authentication telemetry and throttling
apps/server-core/src/core/oauth2/*, apps/server-core/src/adapters/http/..., apps/server-core/src/core/authentication/login-throttle/*, apps/server-core/src/core/metrics/*, packages/errors/*
Records login, authorization, logout, password-reset, and refresh-replay events; adds Prometheus counters and HTTP 429 login throttling.
Read APIs and administration UI
apps/server-core/src/adapters/http/controllers/entities/event/*, packages/core-http-kit/src/domains/entities/event/*, apps/client-web/pages/events/*, packages/client-web-kit/src/components/entities/event/*
Adds permission-gated collection/detail reads, client APIs, navigation, event list/detail pages, and localized labels.
Validation and supporting documentation
apps/server-core/test/unit/..., docs/src/guide/deployment/configuration-server-core.md, .agents/architecture.md
Covers configuration, sanitization, retention, permissions, realm isolation, entity auditing, throttling, metrics, and OAuth2 replay behavior, and documents the event architecture.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

  • authup/authup#3112: Provides related domain-event publisher and handler integration used by the entity audit bridge.
  • authup/authup#3020: Modifies the same OAuth2 password-grant request flow used for throttling and failed-login auditing.
  • authup/authup#3186: Modifies the refresh-token replay path where replay audit events and metrics are emitted.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.79% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main changes: security event logging, entity tracking, login throttling, metrics, and the admin UI.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/roadmap-wave2-audit-spine

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@pkg-pr-new

pkg-pr-new Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

authup

npm i https://pkg.pr.new/authup@3229

@authup/client-web

npm i https://pkg.pr.new/@authup/client-web@3229

@authup/server-core

npm i https://pkg.pr.new/@authup/server-core@3229

@authup/access

npm i https://pkg.pr.new/@authup/access@3229

@authup/client-web-kit

npm i https://pkg.pr.new/@authup/client-web-kit@3229

@authup/client-web-kit-theme

npm i https://pkg.pr.new/@authup/client-web-kit-theme@3229

@authup/client-web-nuxt

npm i https://pkg.pr.new/@authup/client-web-nuxt@3229

@authup/client-web-theme

npm i https://pkg.pr.new/@authup/client-web-theme@3229

@authup/core-http-kit

npm i https://pkg.pr.new/@authup/core-http-kit@3229

@authup/core-kit

npm i https://pkg.pr.new/@authup/core-kit@3229

@authup/core-realtime-kit

npm i https://pkg.pr.new/@authup/core-realtime-kit@3229

@authup/errors

npm i https://pkg.pr.new/@authup/errors@3229

@authup/i18n

npm i https://pkg.pr.new/@authup/i18n@3229

@authup/kit

npm i https://pkg.pr.new/@authup/kit@3229

@authup/server-adapter-kit

npm i https://pkg.pr.new/@authup/server-adapter-kit@3229

@authup/server-adapter-node

npm i https://pkg.pr.new/@authup/server-adapter-node@3229

@authup/server-adapter-socket-io

npm i https://pkg.pr.new/@authup/server-adapter-socket-io@3229

@authup/server-adapter-web

npm i https://pkg.pr.new/@authup/server-adapter-web@3229

@authup/server-kit

npm i https://pkg.pr.new/@authup/server-kit@3229

@authup/server-test-kit

npm i https://pkg.pr.new/@authup/server-test-kit@3229

@authup/specs

npm i https://pkg.pr.new/@authup/specs@3229

commit: bfd4ee8

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown

Note

Unit test generation is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.


Generating unit tests... This may take up to 20 minutes.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown

Request timed out after 900000ms (requestId=903a07ca-9e62-4137-98cf-5633817db8bf)

Base automatically changed from feat/roadmap-wave0-hardening to master July 11, 2026 18:29

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/server-core/src/core/oauth2/grant-types/refresh-token.ts (1)

187-207: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Reorder audit recording after session revocation to avoid blocking the security-critical path.

The await this.auditEventService?.record(...) at line 187 places a non-critical side effect before the security-critical operations at lines 201–207 (token blocklisting and session revocation). While the IAuditEventService.record contract guarantees it won't throw, the await means the revocation is gated on the audit write completing. If the audit database is slow or hangs, the session remains active after a confirmed replay detection — extending the attack window.

The contract itself describes the method as "Fire-and-forget-safe," which implies the caller need not block on it. Consider either moving the audit recording and metrics call after this.sessionManager.revoke(sessionId), or dropping the await to make it truly fire-and-forget.

🔒 Suggested fix: move audit/metrics after revocation
     protected async revokeFamily(sessionId: string, jti: string, at: string) : Promise<void> {
         this.logger?.warn('OAuth2 refresh token replay detected; revoking session', {
             session_id: sessionId,
             jti,
         });

-        await this.auditEventService?.record({
-            scope: AuditEventScope.OAUTH2,
-            name: AuditEventName.REFRESH_REPLAY_DETECTED,
-            refType: AuditEventRefType.SESSION,
-            refId: sessionId,
-            data: { jti },
-        });
-        this.metrics?.recordRefreshReplay();
-
         // Blocklisting is best-effort (cache) — settle all of them so one cache
         // failure cannot skip the rest or, worse, abort the session delete
         // below (the load-bearing part of the revocation). Pin each TTL to the
         // token's real expiry (unix seconds) so a long-lived refresh token
         // cannot resurface as active via introspection after the fallback 1h.
         const rows = await this.sessionTokenRepository.revokeBySessionId(sessionId, at);
         await Promise.allSettled(rows.map((row) => this.tokenRepository.setInactive(
             row.id,
             Math.floor(new Date(row.expires_at).getTime() / 1_000),
         )));

         await this.sessionManager.revoke(sessionId);
+
+        this.auditEventService?.record({
+            scope: AuditEventScope.OAUTH2,
+            name: AuditEventName.REFRESH_REPLAY_DETECTED,
+            refType: AuditEventRefType.SESSION,
+            refId: sessionId,
+            data: { jti },
+        }).catch(() => {});
+        this.metrics?.recordRefreshReplay();
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/src/core/oauth2/grant-types/refresh-token.ts` around lines
187 - 207, Move the awaited audit recording and metrics call from before the
security-critical operations to after token blocklisting and
this.sessionManager.revoke(sessionId) in the refresh replay handling flow. Keep
the existing audit payload and metrics behavior unchanged, while ensuring
session revocation is not gated by audit completion.
🧹 Nitpick comments (6)
apps/server-core/src/app/modules/metrics/prom.ts (1)

20-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider guarding the getOrCreateCounter cast against metric type mismatches.

register.getSingleMetric returns Metric | undefined, and the as Counter<T> cast assumes the existing metric is always a Counter. If a different metric type (e.g., Gauge) were ever registered with the same name, this would produce a runtime error on .inc(). A runtime instanceof Counter check would make this robust without changing the happy path.

This is a low-risk concern since the function is only called from one constructor with known names, but the guard is trivial to add.

♻️ Optional guard for metric type safety
 function getOrCreateCounter<T extends string>(
     name: string,
     help: string,
     labelNames: T[] = [],
 ): Counter<T> {
     const existing = register.getSingleMetric(name);
     if (existing instanceof Counter) {
         return existing as Counter<T>;
     }

     return new Counter<T>({
         name,
         help,
         labelNames,
     });
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/src/app/modules/metrics/prom.ts` around lines 20 - 35,
Update getOrCreateCounter to verify that an existing metric is an instance of
Counter before returning it; only reuse the existing metric when the runtime
type matches, and otherwise proceed with the existing Counter creation path.
apps/server-core/src/core/identity/password-recovery/service.ts (1)

129-139: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Include request context in password-recovery audit events for security completeness.

Both PASSWORD_RESET_REQUESTED and PASSWORD_RESET_COMPLETED audit events omit request context (requestIpAddress, requestUserAgent, requestPath, requestMethod). For a security audit log, the source IP and user agent are critical for investigating credential stuffing or account takeover attempts targeting the password recovery flow.

Additionally, actorId/actorName are set to the user whose password is being reset — but in forgotPassword, the requester is unauthenticated and anonymous. The refType/refId already identify the subject user, so the actor fields are redundant and semantically misleading. Consider passing request context through IdentityWorkflowContext or the service context and including it in the record, and setting actor fields to reflect the actual requester (or omitting them for unauthenticated flows).

♻️ Proposed refactor sketch
 // In PasswordRecoveryServiceContext or IdentityWorkflowContext, add:
 // requestContext?: { ipAddress?: string; userAgent?: string; path?: string; method?: string }

 // In forgotPassword, pass request context to the audit event:
 await this.auditEventService?.record({
     scope: AuditEventScope.IDENTITY,
     name: AuditEventName.PASSWORD_RESET_REQUESTED,
     refType: AuditEventRefType.USER,
     refId: merged.id,
-    actorType: IdentityType.USER,
-    actorId: merged.id,
-    actorName: merged.name,
+    // Actor is anonymous for forgotPassword — refType/refId already
+    // identify the subject user; include request source for investigation.
+    requestIpAddress: context?.requestContext?.ipAddress,
+    requestUserAgent: context?.requestContext?.userAgent,
     realmId: merged.realm_id,
 });

Also applies to: 182-192

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines
129 - 139, Update the PASSWORD_RESET_REQUESTED and PASSWORD_RESET_COMPLETED
audit-event creation in the password-recovery service to propagate
IdentityWorkflowContext request metadata (requestIpAddress, requestUserAgent,
requestPath, and requestMethod) into each record. For unauthenticated
forgotPassword flows, remove the target user’s actorId and actorName or
represent the requester as anonymous, while preserving merged.id as the subject
refId.
apps/server-core/src/core/oauth2/grant-types/password.ts (1)

76-93: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Reconsider await on auditEventService?.record — it contradicts the fire-and-forget contract.

The IAuditEventService.record interface states: "Fire-and-forget-safe: never throws — a write failure must not fail the originating auth operation." The await here couples every successful login's response latency to the audit DB write and risks a hung response if the write stalls. If fire-and-forget is the intent, drop the await and use void to make it explicit:

-        await this.auditEventService?.record({
+        void this.auditEventService?.record({
             scope: AuditEventScope.OAUTH2,
             name: AuditEventName.LOGIN,

If the await is intentional (e.g., compliance requires the audit row to be durable before the token is returned), update the interface comment to reflect that callers should await, and consider adding a timeout to prevent unbounded blocking.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/src/core/oauth2/grant-types/password.ts` around lines 76 -
93, Update the successful-login audit call in the password grant flow to follow
IAuditEventService.record’s fire-and-forget contract: remove await and
explicitly discard the optional promise with void, while keeping metrics
recording and the audit payload unchanged.
apps/server-core/src/core/authentication/login-throttle/service.ts (1)

48-58: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Consider computing retryAfter from the oldest in-window event.

retryAfter is always set to the full windowSeconds (900 s default), but the actual remaining lockout time depends on when the oldest counted LOGIN_FAILED event occurred. A user who hit the threshold 899 seconds ago is told to wait 900 more seconds. This is safe but degrades UX. If countRecent can also return the timestamp of the oldest matching event, retryAfter could be computed as windowSeconds - elapsed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/src/core/authentication/login-throttle/service.ts` around
lines 48 - 58, The login throttle currently reports the full window as
retryAfter regardless of event age. Update the repository query and surrounding
login-throttle service flow to obtain the oldest matching LOGIN_FAILED event,
then compute retryAfter as the remaining window duration based on its elapsed
age, clamped to a valid nonnegative value; preserve the existing threshold check
and LoginThrottledError behavior.
apps/server-core/test/unit/http/controllers/workflows/token/grant-password-throttle.spec.ts (1)

68-74: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Test 2 depends on test 1's accumulated state.

"locks out even the correct password within the window" relies on the 4 LOGIN_FAILED events created by the preceding test. If this it block is run in isolation (e.g., vitest -t "locks out"), the throttle won't trip and the assertion will fail. Consider either adding a brief comment documenting the ordering dependency or creating the failures within this test's own setup.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-password-throttle.spec.ts`
around lines 68 - 74, Make the “locks out even the correct password within the
window” test self-contained by creating the required four LOGIN_FAILED events in
its own setup before calling passwordAttempt. Preserve the existing
throttled-response assertions and avoid relying on state accumulated by a
preceding test.
apps/server-core/src/core/entities/audit-event/service.ts (1)

129-160: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff

Post-filter pagination total is inaccurate, and per-row permission checks are N+1.

In the canReadAll branch, total starts from meta.total (the full result-set count) and is decremented only for rows denied on the current page. The returned meta.total therefore reports fullTotal − deniedOnThisPage rather than the number of rows the actor can actually see, which breaks page-count math for API consumers once denials span multiple pages. Separately, calling permissionEvaluator.evaluate(...) once per row is an N+1 pattern that scales poorly for large pages.

Consider computing accessibility at the query layer (realm-reach filter pushed into findMany) so both the rows and total stay consistent, instead of filtering after pagination.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/src/core/entities/audit-event/service.ts` around lines 129 -
160, Update the canReadAll path around repository.findMany and the per-entity
permission loop to push the actor’s realm accessibility filter into the query
via resourceRealmMatch, allowing findMany to return only readable entities and
an accurate total; remove the per-row permissionEvaluator.evaluate checks and
post-pagination total decrements while preserving ownership handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts`:
- Line 69: Update the request IP resolution around getRequestIP in the password
grant flow to use the application's configurable proxy-trust setting instead of
hardcoding trustProxy: true. Thread the setting into this flow from its existing
configuration source, preserving undefined handling for requests without an IP.

In `@apps/server-core/src/components/audit-event-cleaner/module.ts`:
- Around line 22-32: Update the component startup flow around component.start()
to await the audit cleaner’s initial execute() promise, or explicitly catch and
log its rejection before startup continues. Ensure the initial await execute()
in the cleaner’s execute function cannot become an unhandled rejection while
preserving scheduled cleanup behavior.

In `@apps/server-core/src/core/oauth2/end-session/service.ts`:
- Around line 168-180: Update the logout flow around sessionManager.revoke and
auditEventService.record so the audit write is fire-and-forget rather than
awaited, allowing the revoke path and logout response to proceed without waiting
on audit persistence. Preserve the existing audit payload and ensure any
resulting promise handling does not block logout.

---

Outside diff comments:
In `@apps/server-core/src/core/oauth2/grant-types/refresh-token.ts`:
- Around line 187-207: Move the awaited audit recording and metrics call from
before the security-critical operations to after token blocklisting and
this.sessionManager.revoke(sessionId) in the refresh replay handling flow. Keep
the existing audit payload and metrics behavior unchanged, while ensuring
session revocation is not gated by audit completion.

---

Nitpick comments:
In `@apps/server-core/src/app/modules/metrics/prom.ts`:
- Around line 20-35: Update getOrCreateCounter to verify that an existing metric
is an instance of Counter before returning it; only reuse the existing metric
when the runtime type matches, and otherwise proceed with the existing Counter
creation path.

In `@apps/server-core/src/core/authentication/login-throttle/service.ts`:
- Around line 48-58: The login throttle currently reports the full window as
retryAfter regardless of event age. Update the repository query and surrounding
login-throttle service flow to obtain the oldest matching LOGIN_FAILED event,
then compute retryAfter as the remaining window duration based on its elapsed
age, clamped to a valid nonnegative value; preserve the existing threshold check
and LoginThrottledError behavior.

In `@apps/server-core/src/core/entities/audit-event/service.ts`:
- Around line 129-160: Update the canReadAll path around repository.findMany and
the per-entity permission loop to push the actor’s realm accessibility filter
into the query via resourceRealmMatch, allowing findMany to return only readable
entities and an accurate total; remove the per-row permissionEvaluator.evaluate
checks and post-pagination total decrements while preserving ownership handling.

In `@apps/server-core/src/core/identity/password-recovery/service.ts`:
- Around line 129-139: Update the PASSWORD_RESET_REQUESTED and
PASSWORD_RESET_COMPLETED audit-event creation in the password-recovery service
to propagate IdentityWorkflowContext request metadata (requestIpAddress,
requestUserAgent, requestPath, and requestMethod) into each record. For
unauthenticated forgotPassword flows, remove the target user’s actorId and
actorName or represent the requester as anonymous, while preserving merged.id as
the subject refId.

In `@apps/server-core/src/core/oauth2/grant-types/password.ts`:
- Around line 76-93: Update the successful-login audit call in the password
grant flow to follow IAuditEventService.record’s fire-and-forget contract:
remove await and explicitly discard the optional promise with void, while
keeping metrics recording and the audit payload unchanged.

In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-password-throttle.spec.ts`:
- Around line 68-74: Make the “locks out even the correct password within the
window” test self-contained by creating the required four LOGIN_FAILED events in
its own setup before calling passwordAttempt. Preserve the existing
throttled-response assertions and avoid relying on state accumulated by a
preceding test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: df13021c-dbdb-427a-8560-b5fc62600f94

📥 Commits

Reviewing files that changed from the base of the PR and between 384ff46 and 03a97ea.

📒 Files selected for processing (97)
  • .agents/architecture.md
  • apps/server-core/package.json
  • apps/server-core/src/adapters/database/data-source/options/module.ts
  • apps/server-core/src/adapters/database/domains/audit-event/entity.ts
  • apps/server-core/src/adapters/database/domains/audit-event/index.ts
  • apps/server-core/src/adapters/database/domains/index.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1783769340000-Default.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1783769340000-Default.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/authorization/module.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.ts
  • apps/server-core/src/adapters/http/controllers/entities/audit-event/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/audit-event/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/index.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authorize/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authorize/types.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/app/modules/components/module.ts
  • apps/server-core/src/app/modules/config/constants.ts
  • apps/server-core/src/app/modules/config/normalize.ts
  • apps/server-core/src/app/modules/config/read/env.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/app/modules/config/validator.ts
  • apps/server-core/src/app/modules/database/constants.ts
  • apps/server-core/src/app/modules/database/module.ts
  • apps/server-core/src/app/modules/database/repositories/audit-event/index.ts
  • apps/server-core/src/app/modules/database/repositories/audit-event/repository.ts
  • apps/server-core/src/app/modules/database/repositories/index.ts
  • apps/server-core/src/app/modules/http/module.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/index.ts
  • apps/server-core/src/app/modules/metrics/constants.ts
  • apps/server-core/src/app/modules/metrics/index.ts
  • apps/server-core/src/app/modules/metrics/prom.ts
  • apps/server-core/src/components/audit-event-cleaner/index.ts
  • apps/server-core/src/components/audit-event-cleaner/module.ts
  • apps/server-core/src/components/index.ts
  • apps/server-core/src/core/authentication/index.ts
  • apps/server-core/src/core/authentication/login-throttle/index.ts
  • apps/server-core/src/core/authentication/login-throttle/service.ts
  • apps/server-core/src/core/authentication/login-throttle/types.ts
  • apps/server-core/src/core/entities/audit-event/index.ts
  • apps/server-core/src/core/entities/audit-event/sanitize.ts
  • apps/server-core/src/core/entities/audit-event/service.ts
  • apps/server-core/src/core/entities/audit-event/types.ts
  • apps/server-core/src/core/entities/index.ts
  • apps/server-core/src/core/identity/password-recovery/service.ts
  • apps/server-core/src/core/identity/password-recovery/types.ts
  • apps/server-core/src/core/identity/registration/service.ts
  • apps/server-core/src/core/identity/registration/types.ts
  • apps/server-core/src/core/index.ts
  • apps/server-core/src/core/metrics/index.ts
  • apps/server-core/src/core/metrics/noop.ts
  • apps/server-core/src/core/metrics/types.ts
  • apps/server-core/src/core/oauth2/authorization/module.ts
  • apps/server-core/src/core/oauth2/authorization/types.ts
  • apps/server-core/src/core/oauth2/end-session/service.ts
  • apps/server-core/src/core/oauth2/end-session/types.ts
  • apps/server-core/src/core/oauth2/grant-types/password.ts
  • apps/server-core/src/core/oauth2/grant-types/refresh-token.ts
  • apps/server-core/src/core/oauth2/grant-types/types.ts
  • apps/server-core/test/unit/config/index.spec.ts
  • apps/server-core/test/unit/core/authentication/login-throttle/service.spec.ts
  • apps/server-core/test/unit/core/entities/audit-event/fake-repository.ts
  • apps/server-core/test/unit/core/entities/audit-event/sanitize.spec.ts
  • apps/server-core/test/unit/core/entities/audit-event/service.spec.ts
  • apps/server-core/test/unit/core/helpers/fake-audit-event-service.ts
  • apps/server-core/test/unit/core/helpers/fake-auth-flow-metrics.ts
  • apps/server-core/test/unit/core/helpers/index.ts
  • apps/server-core/test/unit/core/oauth2/grant-types/refresh-token.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/audit-event-realm-isolation.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/audit-event.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-password-throttle.spec.ts
  • apps/server-core/test/unit/http/middleware/metrics.spec.ts
  • docs/src/guide/deployment/configuration-server-core.md
  • packages/core-http-kit/src/client/module.ts
  • packages/core-http-kit/src/client/type.ts
  • packages/core-http-kit/src/domains/entities/audit-event/index.ts
  • packages/core-http-kit/src/domains/entities/audit-event/module.ts
  • packages/core-http-kit/src/domains/entities/audit-event/types.ts
  • packages/core-http-kit/src/domains/entities/index.ts
  • packages/core-kit/src/domains/attempt-login/entity.ts
  • packages/core-kit/src/domains/audit-event/constants.ts
  • packages/core-kit/src/domains/audit-event/entity.ts
  • packages/core-kit/src/domains/audit-event/index.ts
  • packages/core-kit/src/domains/index.ts
  • packages/core-kit/src/domains/permission/constants.ts
  • packages/errors/src/built-in/check.ts
  • packages/errors/src/built-in/index.ts
  • packages/errors/src/built-in/login-throttled.ts
  • packages/errors/src/constants.ts
  • packages/errors/src/status.ts
  • packages/i18n/src/catalogs/de/error.ts
  • packages/i18n/src/catalogs/en/error.ts
  • packages/i18n/src/catalogs/es/error.ts
  • packages/i18n/src/catalogs/fr/error.ts
💤 Files with no reviewable changes (1)
  • packages/core-kit/src/domains/attempt-login/entity.ts

}

const user = await this.authenticator.authenticate(username, password, realm.id);
const ipAddress = getRequestIP(event, { trustProxy: true }) ?? undefined;

@coderabbitai coderabbitai Bot Jul 11, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Look for an existing trust-proxy config the grant should honor instead of hardcoding true.
rg -nP -C2 'trustProxy|trust_proxy|TRUST_PROXY' --type=ts
# Compare with other getRequestIP call sites in the codebase.
rg -nP -C2 'getRequestIP\s*\(' --type=ts

Repository: authup/authup

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the target file around the reported line.
sed -n '1,180p' apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts

# Find the base class and any related config wiring for the password grant.
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
  'class\s+PasswordGrantType|extends\s+PasswordGrantType|trustProxy|getRequestIP\(' \
  apps/server-core/src

# Locate any server-level proxy-trust configuration in the repository.
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
  'trustProxy|trust_proxy|TRUST_PROXY|proxy.*trust|forwarded.*for' \
  .

Repository: authup/authup

Length of output: 10808


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the deployment guidance around proxy headers and any note about trusted proxies.
sed -n '1,120p' docs/src/guide/deployment/nginx.md

# Look for server deployment/configuration that indicates the app is expected to sit behind a reverse proxy.
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
  'publicUrl|reverse proxy|nginx|proxy_set_header|X-Forwarded-For|trustProxy|trust proxy' \
  docs apps/server-core/src .agents

# Check the OAuth2 grant base for inherited audit/metrics fields mentioned in the original note.
sed -n '1,220p' apps/server-core/src/core/oauth2/grant-types/password.ts

Repository: authup/authup

Length of output: 17135


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect server-core configuration docs for deployment assumptions around proxies.
sed -n '1,90p' docs/src/guide/deployment/configuration-server-core.md

# Inspect where request IP is used in the OAuth2 grant flow to see whether this is a local one-off or a broader convention.
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
  'requestIpAddress|ipAddress: getRequestIP|getRequestIP\(event, \{ trustProxy: true \}\)' \
  apps/server-core/src/adapters/http/adapters/oauth2/grant-types apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts

Repository: authup/authup

Length of output: 4450


Make trustProxy configurable
This trusts X-Forwarded-For unconditionally, so a direct deployment can spoof the IP used for throttling and audit records. Thread the proxy-trust setting through here instead of hardcoding true.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts`
at line 69, Update the request IP resolution around getRequestIP in the password
grant flow to use the application's configurable proxy-trust setting instead of
hardcoding trustProxy: true. Thread the setting into this flow from its existing
configuration source, preserving undefined handling for requests without an IP.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid concern, but pre-existing and repo-wide: every getRequestIP call site (8, all grant adapters + the identity-provider controller) hardcodes trustProxy: true — the session/session-token ip_address inventory shares the same trust. Threading a config key only through this one site would be inconsistent, so this is tracked as #3230 (config key TRUST_PROXY, default true, threaded through all call sites). This PR adds the deployment-docs warning on the throttle config in the meantime (f91c225).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tada5hi, that makes sense — treating this consistently across all 8 getRequestIP call sites via a dedicated TRUST_PROXY config key (#3230) is the right approach rather than a one-off fix here. Thanks for adding the deployment-docs warning in the meantime as an interim mitigation. Deferring to the tracked issue.

@tada5hi

tada5hi commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai pause

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
✅ Action performed

Reviews paused.

…he process

Review follow-up (#3229): the cleaner components' start() is invoked
fire-and-forget, so a rejected initial sweep became an unhandled
rejection (fatal on modern node). Both cleaners now catch + log per
sweep tick (next tick retries), the components module catches start()
rejections for every component, and the throttle config docs note the
X-Forwarded-For trust assumption.
Maintainer review follow-ups on #3229, pre-release renames (no
compatibility surface exists yet):

- AuditEvent -> Event across core-kit/server-core/core-http-kit
  (EventName/EventScope/EventRefType, EventService, EventController,
  EventRepositoryAdapter, EventAPI, client.event) - the domain is the
  general security event store; the CRUD-subscriber bridge lands in the
  same table later, mirroring hub's EntityEventHandler.
- table audit_events -> auth_events (auth_* table convention),
  permission audit_read -> event_read (hub's permission vocabulary),
  routes /audit-events -> /events, config auditLog* -> eventLog*
  (EVENT_LOG_* env).
- data column: simple-json -> text with the @authup/kit
  serialize/deserialize transformer (hub pattern), null-guarded on
  write since serialize(null) would persist the string 'null'.
- expiring boolean column re-added (indexed, default false, stamped
  from the retention config); the sweeper predicate becomes hub's
  cleaner shape (expiring = true AND expires_at < now).
@tada5hi tada5hi changed the title feat: security audit-event log, failed-login throttle & auth-flow metrics feat: security event log, failed-login throttle & auth-flow metrics Jul 11, 2026
tada5hi added 3 commits July 11, 2026 22:29
Every create/update/delete already published on the domain-event bus by
the entity subscribers now also lands as an auth_events row (plan 057
stage 2, mirroring hub's EntityEventHandler): scope 'entity', name
created/updated/deleted, ref_type/ref_id, realm-gated reads.

Hardened beyond the hub design: the pre-mutation snapshot rides the
publish CONTEXT (dataPrevious) - never the shared realtime wire payload;
actor + request attribution comes from an AsyncLocalStorage request
event context mounted after the authorization middleware (non-HTTP
writes attribute as system/null); the scalar diff excludes secret-shaped
keys (password/secret/hash/token/credential) and timestamp columns, and
the write-boundary sanitizer re-validates the diff shape; created and
deleted rows carry no column dumps. Entity rows self-prune via
eventLogEntityRetentionDays (default 7 days); the bridge is gated by
eventLogEntityEnabled. The hub<->authup mapping and the upstream-to-hub
improvement candidates are recorded in .agents/references/privateaim-hub.md.
Events pages in client-web (list with typed VCTable columns, name
search, pagination; hub-style detail page with general/actor/request
cards and the pretty-printed data dict), a kit AEvents collection
mirroring ASessions, an EVENT_READ-gated nav entry with route-meta
enforcement on every matched record, EntityType.EVENT for the
collection manager (inert server-side - no subscriber), and entity/
field/common i18n keys in all four locales (parity-tested).
EventName multi-word values follow the hub camelCase vocabulary
(loginFailed, refreshReplayDetected, accountActivated,
passwordResetRequested/Completed - stored values, safe pre-release),
the authorize reason value becomes autoConsent, and the sanitizer's
manual object checks collapse onto isObject from @authup/kit.
@tada5hi

tada5hi commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
✅ Action performed

Reviews resumed.

@tada5hi

tada5hi commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.


Your plan includes PR reviews subject to rate limits. More reviews will be available in 59 minutes.

@tada5hi tada5hi changed the title feat: security event log, failed-login throttle & auth-flow metrics feat: security event log with entity tracking, login throttle, metrics & admin ui Jul 11, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (4)
apps/server-core/test/unit/core/helpers/fake-event-service.ts (1)

22-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider accepting and storing query/actor/id arguments for test assertions.

getMany() and getOne() omit the query, actor, and id parameters defined in IEventService. While TypeScript permits this (fewer-parameter functions are assignable to wider signatures), tests using this fake cannot verify that the correct query, actor context, or entity ID was passed — limiting the fake's usefulness for behavioral assertions.

♻️ Optional refactor: capture call arguments
-async getMany(): Promise<EntityRepositoryFindManyResult<Event>> {
+async getMany(query?: Record<string, any>, actor?: ActorContext): Promise<EntityRepositoryFindManyResult<Event>> {
+    this.getManyCalls.push({ query, actor });
     return {
         data: [],
         meta: {
             total: 0,
             limit: 50,
             offset: 0,
         },
     };
 }

-async getOne(): Promise<Event> {
+async getOne(id?: string, actor?: ActorContext): Promise<Event> {
+    this.getOneCalls.push({ id, actor });
     throw new Error('not implemented');
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/test/unit/core/helpers/fake-event-service.ts` around lines
22 - 35, Update the fake event service methods getMany and getOne to accept the
query, actor, and id parameters required by IEventService, and store those
arguments on the fake so tests can inspect the calls. Preserve the existing
return values and unimplemented error behavior while exposing the captured
inputs for assertions.
apps/server-core/test/unit/core/entities/event/entity-event-handler.spec.ts (1)

138-163: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Consider adding a test for undefined ctx.content.data with an updated event.

There's no test covering the case where ctx.content.data is undefined and the event is updated with a dataPrevious snapshot. This is the edge case flagged in entity-event-handler.ts where buildEntityDiff could throw on undefined. Adding a test would clarify the expected behavior and guard against regressions.

🧪 Suggested test
it('records without diff when data is undefined for an updated event', async () => {
    await buildHandler().handle(buildPublishContext({
        content: {
            event: 'updated',
            data: undefined as any,
        },
        dataPrevious: { id: entityId, description: 'before' },
    }));

    expect(eventService.recordCalls).toHaveLength(1);
    expect(eventService.recordCalls[0].data).toBeNull();
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/test/unit/core/entities/event/entity-event-handler.spec.ts`
around lines 138 - 163, Add a unit test alongside the updated-event cases in the
handler spec covering an updated event with undefined content.data and a
populated dataPrevious snapshot. Assert one event is recorded and its data is
null, using buildHandler, buildPublishContext, and eventService.recordCalls.
apps/server-core/src/core/entities/event/entity-event-handler.ts (1)

94-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log errors in the catch block for audit observability.

The silent catch is intentional for failure isolation, but a security audit system that silently drops records with no trace makes debugging impossible. Consider logging the error so operators can detect when audit records are being lost.

♻️ Proposed fix
-        } catch {
-            // record() never throws, but the bridge itself must also never
-            // fail the originating publish.
+        } catch (e) {
+            // record() never throws, but the bridge itself must also never
+            // fail the originating publish. Log for observability so silent
+            // audit-record loss is detectable by operators.
+            console.error('[EntityEventHandler] failed to record audit event:', e);
         }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/src/core/entities/event/entity-event-handler.ts` around
lines 94 - 97, The catch block around the audit bridge must retain failure
isolation while recording errors for audit observability. Update the catch
associated with record() in the event handler to log the caught error with
sufficient context, without rethrowing or changing the originating publish flow.
apps/server-core/src/adapters/database/migrations/mysql/1783769340000-Default.ts (1)

42-51: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider a composite index for the retention sweep instead of separate single-column indexes.

IDX_auth_events_expiring and IDX_auth_events_expires_at are separate; the event-cleaner's retention sweep almost certainly filters WHERE expiring = 1 AND expires_at < ?. A composite (expiring, expires_at) index would serve that query more efficiently than two low-selectivity single-column indexes, and reduces per-insert index-maintenance overhead on this high-frequency append-only table.

♻️ Proposed composite index
-                INDEX \`IDX_auth_events_expiring\` (\`expiring\`),
-                INDEX \`IDX_auth_events_expires_at\` (\`expires_at\`),
+                INDEX \`IDX_auth_events_expiring_expires_at\` (\`expiring\`, \`expires_at\`),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/server-core/src/adapters/database/migrations/mysql/1783769340000-Default.ts`
around lines 42 - 51, Update the auth_events index definitions in the migration
to replace the separate IDX_auth_events_expiring and IDX_auth_events_expires_at
indexes with one composite index covering expiring and expires_at in that order.
Preserve the existing index naming conventions and remove both redundant
single-column definitions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/client-web/pages/events/`[id]/index.vue:
- Around line 106-113: Update the catch block in the event page setup around the
event fetch to return navigateTo({ path: '/events' }) directly, removing the
await and createError({}) throw so the failed load redirects cleanly without
triggering an empty fatal error.

In `@apps/server-core/src/adapters/http/request/event-context.ts`:
- Line 51: Make the trustProxy option used by getRequestIP in the request
context configurable rather than hardcoded to true. Reuse the existing server
configuration mechanism and ensure requestIpAddress continues to return null
when no address is available, while deployments without trusted proxies do not
accept spoofed forwarded addresses.

In `@apps/server-core/src/app/modules/components/module.ts`:
- Around line 41-45: Update the event cleaner condition in the module
initialization flow to start when event logging is enabled and either
eventLogRetentionDays or eventLogEntityRetentionDays is greater than zero. Keep
the existing createEventCleanerComponent(dataSource, logger) behavior unchanged.

In `@apps/server-core/src/components/oauth2-cleaner/module.ts`:
- Around line 39-41: Update the catch block in the expired-session sweep to
capture the thrown error and pass its details to logger?.warn while preserving
the existing swallowed-error behavior and non-crashing flow.

In `@apps/server-core/src/core/entities/event/entity-event-handler.ts`:
- Around line 71-76: Guard the buildEntityDiff call in the UPDATED event
handling branch so it only runs when ctx.content.data is present, alongside the
existing ctx.dataPrevious check. When next data is absent, skip creating the
diff payload while preserving the current behavior for valid data.

---

Nitpick comments:
In
`@apps/server-core/src/adapters/database/migrations/mysql/1783769340000-Default.ts`:
- Around line 42-51: Update the auth_events index definitions in the migration
to replace the separate IDX_auth_events_expiring and IDX_auth_events_expires_at
indexes with one composite index covering expiring and expires_at in that order.
Preserve the existing index naming conventions and remove both redundant
single-column definitions.

In `@apps/server-core/src/core/entities/event/entity-event-handler.ts`:
- Around line 94-97: The catch block around the audit bridge must retain failure
isolation while recording errors for audit observability. Update the catch
associated with record() in the event handler to log the caught error with
sufficient context, without rethrowing or changing the originating publish flow.

In `@apps/server-core/test/unit/core/entities/event/entity-event-handler.spec.ts`:
- Around line 138-163: Add a unit test alongside the updated-event cases in the
handler spec covering an updated event with undefined content.data and a
populated dataPrevious snapshot. Assert one event is recorded and its data is
null, using buildHandler, buildPublishContext, and eventService.recordCalls.

In `@apps/server-core/test/unit/core/helpers/fake-event-service.ts`:
- Around line 22-35: Update the fake event service methods getMany and getOne to
accept the query, actor, and id parameters required by IEventService, and store
those arguments on the fake so tests can inspect the calls. Preserve the
existing return values and unimplemented error behavior while exposing the
captured inputs for assertions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ea69c995-4e3a-4e5d-b86a-2590b83ed124

📥 Commits

Reviewing files that changed from the base of the PR and between 03a97ea and 4bf7216.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (105)
  • .agents/architecture.md
  • .agents/references/authentik.md
  • .agents/references/privateaim-hub.md
  • apps/client-web/config/layout/contants.ts
  • apps/client-web/pages/events/[id]/index.vue
  • apps/client-web/pages/events/index.vue
  • apps/client-web/pages/events/index/index.vue
  • apps/server-core/src/adapters/database/data-source/options/module.ts
  • apps/server-core/src/adapters/database/domains/event/entity.ts
  • apps/server-core/src/adapters/database/domains/event/index.ts
  • apps/server-core/src/adapters/database/domains/index.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1783769340000-Default.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1783769340000-Default.ts
  • apps/server-core/src/adapters/database/subscriber/module.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts
  • apps/server-core/src/adapters/http/controllers/entities/event/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/event/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/index.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authorize/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authorize/types.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/adapters/http/request/event-context.ts
  • apps/server-core/src/adapters/http/request/index.ts
  • apps/server-core/src/app/modules/components/module.ts
  • apps/server-core/src/app/modules/config/constants.ts
  • apps/server-core/src/app/modules/config/normalize.ts
  • apps/server-core/src/app/modules/config/read/env.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/app/modules/config/validator.ts
  • apps/server-core/src/app/modules/database/constants.ts
  • apps/server-core/src/app/modules/database/module.ts
  • apps/server-core/src/app/modules/database/repositories/event/index.ts
  • apps/server-core/src/app/modules/database/repositories/event/repository.ts
  • apps/server-core/src/app/modules/database/repositories/index.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/http/modules/middleware.ts
  • apps/server-core/src/components/event-cleaner/index.ts
  • apps/server-core/src/components/event-cleaner/module.ts
  • apps/server-core/src/components/index.ts
  • apps/server-core/src/components/oauth2-cleaner/module.ts
  • apps/server-core/src/core/authentication/login-throttle/service.ts
  • apps/server-core/src/core/authentication/login-throttle/types.ts
  • apps/server-core/src/core/entities/event/diff.ts
  • apps/server-core/src/core/entities/event/entity-event-handler.ts
  • apps/server-core/src/core/entities/event/index.ts
  • apps/server-core/src/core/entities/event/sanitize.ts
  • apps/server-core/src/core/entities/event/service.ts
  • apps/server-core/src/core/entities/event/types.ts
  • apps/server-core/src/core/entities/index.ts
  • apps/server-core/src/core/identity/password-recovery/service.ts
  • apps/server-core/src/core/identity/password-recovery/types.ts
  • apps/server-core/src/core/identity/registration/service.ts
  • apps/server-core/src/core/identity/registration/types.ts
  • apps/server-core/src/core/oauth2/authorization/module.ts
  • apps/server-core/src/core/oauth2/authorization/types.ts
  • apps/server-core/src/core/oauth2/end-session/service.ts
  • apps/server-core/src/core/oauth2/end-session/types.ts
  • apps/server-core/src/core/oauth2/grant-types/password.ts
  • apps/server-core/src/core/oauth2/grant-types/refresh-token.ts
  • apps/server-core/src/core/oauth2/grant-types/types.ts
  • apps/server-core/test/unit/config/index.spec.ts
  • apps/server-core/test/unit/core/authentication/login-throttle/service.spec.ts
  • apps/server-core/test/unit/core/entities/event/diff.spec.ts
  • apps/server-core/test/unit/core/entities/event/entity-event-handler.spec.ts
  • apps/server-core/test/unit/core/entities/event/fake-repository.ts
  • apps/server-core/test/unit/core/entities/event/sanitize.spec.ts
  • apps/server-core/test/unit/core/entities/event/service.spec.ts
  • apps/server-core/test/unit/core/helpers/fake-event-service.ts
  • apps/server-core/test/unit/core/helpers/index.ts
  • apps/server-core/test/unit/core/oauth2/grant-types/refresh-token.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/event-entity-bridge.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/event-realm-isolation.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/event.spec.ts
  • docs/src/guide/deployment/configuration-server-core.md
  • packages/client-web-kit/src/components/entities/event/AEvents.ts
  • packages/client-web-kit/src/components/entities/event/index.ts
  • packages/client-web-kit/src/components/entities/index.ts
  • packages/core-http-kit/src/client/module.ts
  • packages/core-http-kit/src/client/type.ts
  • packages/core-http-kit/src/domains/entities/event/index.ts
  • packages/core-http-kit/src/domains/entities/event/module.ts
  • packages/core-http-kit/src/domains/entities/event/types.ts
  • packages/core-http-kit/src/domains/entities/index.ts
  • packages/core-kit/src/domains/contstants.ts
  • packages/core-kit/src/domains/event/constants.ts
  • packages/core-kit/src/domains/event/entity.ts
  • packages/core-kit/src/domains/event/index.ts
  • packages/core-kit/src/domains/index.ts
  • packages/core-kit/src/domains/permission/constants.ts
  • packages/core-kit/src/domains/types.ts
  • packages/i18n/src/catalogs/de/common.ts
  • packages/i18n/src/catalogs/de/entity.ts
  • packages/i18n/src/catalogs/de/field.ts
  • packages/i18n/src/catalogs/en/common.ts
  • packages/i18n/src/catalogs/en/entity.ts
  • packages/i18n/src/catalogs/en/field.ts
  • packages/i18n/src/catalogs/es/common.ts
  • packages/i18n/src/catalogs/es/entity.ts
  • packages/i18n/src/catalogs/es/field.ts
  • packages/i18n/src/catalogs/fr/common.ts
  • packages/i18n/src/catalogs/fr/entity.ts
  • packages/i18n/src/catalogs/fr/field.ts
  • packages/i18n/src/constants.ts
  • packages/server-kit/src/domain-event/types.ts
✅ Files skipped from review due to trivial changes (13)
  • packages/i18n/src/catalogs/es/entity.ts
  • packages/i18n/src/catalogs/fr/entity.ts
  • packages/client-web-kit/src/components/entities/index.ts
  • packages/i18n/src/catalogs/de/entity.ts
  • apps/server-core/test/unit/http/controllers/entities/event-realm-isolation.spec.ts
  • apps/server-core/src/core/entities/event/index.ts
  • apps/server-core/src/app/modules/database/repositories/event/index.ts
  • packages/core-kit/src/domains/event/constants.ts
  • packages/i18n/src/catalogs/es/common.ts
  • packages/client-web-kit/src/components/entities/event/index.ts
  • .agents/references/authentik.md
  • apps/server-core/src/adapters/database/domains/event/index.ts
  • .agents/architecture.md
🚧 Files skipped from review as they are similar to previous changes (11)
  • apps/server-core/src/adapters/http/controllers/entities/index.ts
  • apps/server-core/src/app/modules/database/repositories/index.ts
  • apps/server-core/test/unit/core/helpers/index.ts
  • apps/server-core/test/unit/config/index.spec.ts
  • apps/server-core/src/core/authentication/login-throttle/types.ts
  • apps/server-core/src/core/authentication/login-throttle/service.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/test/unit/core/authentication/login-throttle/service.spec.ts
  • apps/server-core/test/unit/core/oauth2/grant-types/refresh-token.spec.ts
  • apps/server-core/src/core/oauth2/authorization/module.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts

- the event cleaner now also starts when only the entity retention is
  configured (eventLogRetentionDays 0 + eventLogEntityRetentionDays > 0
  previously stamped expires_at on entity rows that were never swept)
- the entity-event handler guards the diff build against a data-less
  update publish (Object.keys(undefined) would skip the whole row via
  the outer catch)
- both cleaners log the swallowed sweep error for debuggability
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants