Audit Log Mechanism
What is an Audit Log?
An audit log (also called an audit trail) is a security-relevant chronological record, set of records, and/or destination and source of records that provide documentary evidence of the sequence of activities that have affected at any time a specific operation, procedure, or event.
In NuxSaaS, audit logs are crucial for tracking user activities, system events, and potential security incidents. They help in maintaining accountability, facilitating debugging, and ensuring compliance.
Audit Log Schema
The audit log entries are stored in the audit_log
table with the following structure (defined in server/database/schema/auditLog.ts
):
id
: SERIAL - A unique identifier for the audit log entry (Primary Key).userId
: UUID - The ID of the user who performed the action. This references theuser.id
. It can benull
if the action was performed by the system or an unauthenticated entity.category
: TEXT - The category of the event. Examples:auth
,email
,payment
.action
: TEXT - The specific action performed. Examples:login
,register
,verification
,reset_password
,trial_start
,subscription_created
.targetType
: TEXT - The type of entity that the action was performed on. Examples:user
,email
,stripeCustomerId
.targetId
: TEXT - The identifier of the target entity.ipAddress
: TEXT - The IP address from which the action originated.userAgent
: TEXT - The user agent string of the client that initiated the action.status
: TEXT - The status of the action. Examples:success
,failure
,pending
. Defaults tosuccess
.details
: TEXT - Additional details or error messages related to the event.createdAt
: TIMESTAMP - The timestamp indicating when the event occurred. Defaults to the current time.
How Audit Events are Logged
Audit events are logged using the logAuditEvent
function located in server/utils/auditLogger.ts
. This centralized function is called from various parts of the application to record significant events.
export async function logAuditEvent(data: {
userId?: string;
category: 'auth' | 'email' | 'payment';
action: string;
targetType?: string;
targetId?: string;
ipAddress?: string;
userAgent?: string;
status?: 'success' | 'failure' | 'pending';
details?: string;
}) {
// ... implementation to insert into audit_log table ...
}
This function takes an object with event details and persists it to the database.
Examples of Logged Events
NuxSaaS logs various events across different modules:
1. Authentication Events
Authentication-related activities are logged via hooks in the better-auth
system, as configured in server/utils/auth.ts
.
- Events Logged :
- User sign-in attempts (e.g.,
/sign-in/email
) - User sign-up (e.g.,
/sign-up/email
) - Password forget requests (e.g.,
/forget-password
) - Password reset completions (e.g.,
/reset-password
)
- User sign-in attempts (e.g.,
- Information Captured :
userId
(if available, e.g., after successful sign-in or for existing session actions)category
:auth
action
: The API path of the auth operation (e.g., /sign-in/email ).targetType
:email
(for email/password actions) oruser
.targetId
: The user's email or user ID.ipAddress
: Captured from request headers.userAgent
: Captured from request headers.status
:success
orfailure
.details
: Error messages in case of failures (e.g., fromAPIError
).
2. Email Sending Events
Events related to sending emails (e.g., verification, password reset) are logged directly after the email sending attempt.
- Events Logged (from
server/utils/auth.ts
):- Sending password reset emails (
sendResetPassword
function). - Sending email verification emails (
sendVerificationEmail
function).
- Sending password reset emails (
- Information Captured:
userId
: The ID of the user to whom the email is sent.category
:email
action
:reset_password
orverification
.targetType
:email
.targetId
: The user's email address.status
:success
orfailure
(based on the email sending service response).details
: Error messages if the email sending failed.
3. Payment Events (Stripe Integration)
Payment and subscription lifecycle events are logged via callbacks from the Stripe integration, as defined in server/utils/stripe.ts
.
- Events Logged:
- Trial start (
trial_start
) - Trial end (
trial_end
) - Trial expiration without conversion (
trial_expired
) - Subscription creation (
subscription_created
) - Subscription update (
subscription_updated
) - Subscription cancellation (
subscription_canceled
) - Subscription deletion (
subscription_deleted
)
- Trial start (
- Information Captured (by the
addPaymentLog
helper function):userId
: The ID of the user associated with the Stripe customer ID.category
:payment
action
: A composite string liketrial_start:pro-monthly
, indicating the event and plan.targetType
:stripeCustomerId
.targetId
: The Stripe Customer ID.status
: Typicallysuccess
for these webhook-driven events.
Accessing and Utilizing Audit Logs
Audit logs can be accessed by querying the audit_log
table in the database. Administrators can use this data for:
- Security Monitoring: Detecting suspicious activities, unauthorized access attempts, or potential security breaches.
- Troubleshooting: Diagnosing issues by reviewing the sequence of events leading up to a problem.
- Compliance: Providing evidence of system activities for regulatory or internal compliance requirements.
- User Support: Understanding user actions to provide better assistance.
Typically, a dedicated interface in the admin panel would be used to view, filter, and search audit logs, making them easily accessible for administrative purposes.