# TREK Audit Log Events and Purpose: Complete Security Trail Guide

> Understand TREK audit log events like authentication, trip edits, and admin changes. Securely track and analyze activity for compliance and forensics with this essential guide.

- Repository: [Maurice/TREK](https://github.com/mauriceboe/TREK)
- Tags: audit-guide
- Published: 2026-07-01

---

**TREK's audit log captures security-relevant events including authentication attempts, trip modifications, admin configuration changes, and OAuth flows, providing administrators with a tamper-aware trail for compliance, forensic analysis, and operational monitoring.**

The audit log is a core security feature in the [TREK](https://github.com/mauriceboe/TREK) open-source travel planning application. It persists event data to both an SQLite database table and a rotating plain-text log file, enabling administrators to trace user actions, detect anomalies, and maintain compliance through the Admin UI or direct file access.

## What Events Are Logged by the TREK Audit Log?

TREK categorizes audit events into distinct functional areas. Each event is recorded with a machine-readable action key, timestamp, user context, and JSON metadata.

### Authentication and MFA Events

User identity and access management actions are comprehensively tracked:

- **user.register** – New account creation
- **user.login** – Successful authentication
- **user.login_failed** – Failed authentication attempts (security monitoring)
- **user.password_change** – Password modifications
- **user.account_delete** – Account deletion
- **user.mfa_enable / user.mfa_disable** – Multi-factor authentication state changes

### Trip Management Events

All modifications to travel data are logged to maintain data integrity:

- **trip.create** – New trip creation (title stored in `details.title`)
- **trip.update** – Field-level modifications to existing trips
- **trip.copy** – Trip duplication events with source and destination IDs
- **trip.delete** – Permanent trip removal (ID and title retained in log)

### Administrative Configuration Events

System-level changes made by administrators generate high-priority audit entries:

- **admin.user_create / admin.user_update / admin.user_delete** – User lifecycle management
- **admin.invite_create / admin.invite_delete** – Invitation link management
- **admin.permissions_update** – Instance-wide permission modifications
- **admin.oidc_update** – SSO/OIDC configuration changes
- **admin.addon_update** – Add-on enablement and configuration
- **admin.rotate_jwt_secret** – Security credential rotation
- **settings.app_update** – Application settings changes (SMTP, webhooks, MFA policy)

Specialized admin toggles are also captured, including **admin.bag_tracking**, **admin.places_photos**, **admin.collab_features**, and **admin.packing_template_delete**.

### Backup Operations

Data protection activities are tracked for disaster recovery auditing:

- **backup.create** – Manual backup initiation
- **backup.restore** – Restoration from stored backup
- **backup.upload_restore** – Recovery from uploaded ZIP archives
- **backup.delete** – Backup file removal
- **backup.auto_settings** – Automated backup schedule modifications

### OAuth and Integration Events

Third-party authentication and API access generate detailed audit trails:

- **oauth.client.create / oauth.client.rotate_secret / oauth.client.delete** – OAuth client lifecycle
- **oauth.consent.grant** – User consent for third-party access
- **oauth.token.issue / oauth.token.refresh / oauth.token.revoke** – Token lifecycle management
- **oauth.token.grant_failed / oauth.token.client_auth_failed** – Authentication failures
- **immich.private_ip_configured** – Integration configuration (e.g., Immich URL settings)

### Model Context Protocol (MCP) Events

AI integration activities are logged for transparency:

- **mcp.tool_call** – Records MCP tool invocations with the tool name stored in the `resource` column

## Audit Log Schema and Storage

According to the database schema in [`server/src/db/schema.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/schema.ts) (lines 461-470), the `audit_log` table persists events with the following structure:

- **created_at** – Event timestamp
- **user_id** – Acting user ID (NULL for anonymous actions)
- **action** – Machine-readable action key (e.g., `trip.create`)
- **resource** – Optional resource identifier (trip ID, OAuth client ID, etc.)
- **details** – JSON blob containing contextual data (changed fields, titles, configuration values)
- **ip** – Client IP address extracted from `X-Forwarded-For` headers or the socket connection

Simultaneously, the `writeAudit()` function in [`server/src/services/auditLog.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/services/auditLog.ts) emits structured log entries to `./data/logs/trek.log`, creating a persistent plain-text record that rotates automatically.

## How to Write Custom Audit Events

Developers can extend the audit trail using the `writeAudit()` function from the audit service. The system supports custom action keys while maintaining the same persistence guarantees.

```typescript
import { writeAudit } from '@/server/src/services/auditLog';

// Example: Log a custom PDF export event
writeAudit({
  userId: currentUser.id,
  action: 'trip.export_pdf',
  resource: trip.id.toString(),
  details: { format: 'PDF', pages: 12 },
  ip: getClientIp(req),
});

```

**Note:** Custom actions appear in the Admin UI with their raw key unless you add a human-readable label to the `ACTION_LABELS` mapping in [`server/src/services/auditLog.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/services/auditLog.ts).

## Querying and Retrieving Audit Data

Administrators can access audit data through the REST API or by reading the log file directly.

### Via Admin API

The `getAuditLog` function in [`server/src/services/adminService.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/services/adminService.ts) (lines 221-264) provides paginated access:

```typescript
// GET /api/admin/audit?limit=50&offset=0
const { entries, total, limit, offset } = getAuditLog({ limit: '50', offset: '0' });

entries.forEach(e => {
  console.log(`[${e.created_at}] ${e.username ?? e.user_email ?? 'anonymous'} – ${e.action}`);
});

```

### Via Log File

For direct file access or external log aggregation:

```typescript
import fs from 'fs';
import path from 'path';

const logPath = path.join(process.cwd(), 'data/logs/trek.log');
const recentLines = fs.readFileSync(logPath, 'utf-8')
                      .trim()
                      .split('\n')
                      .slice(-20); // last 20 lines
console.log(recentLines.join('\n'));

```

The client IP extraction respects the `TRUST_PROXY` environment setting, parsing `X-Forwarded-For` headers when configured.

## Key Implementation Files

| File | Purpose |
|------|---------|
| [`server/src/services/auditLog.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/services/auditLog.ts) | Core `writeAudit()` implementation, IP resolution, and log rotation |
| [`server/src/db/schema.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/schema.ts) (lines 461-470) | `audit_log` table definition |
| [`server/src/services/adminService.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/services/adminService.ts) (lines 221-264) | Admin API endpoint `getAuditLog` for UI queries |
| [`server/tests/unit/services/adminService.test.ts`](https://github.com/mauriceboe/TREK/blob/main/server/tests/unit/services/adminService.test.ts) | Test coverage ensuring audit entry persistence |
| `./data/logs/trek.log` | Runtime plain-text log file (created automatically) |

## Summary

- TREK's audit log captures **authentication attempts, trip modifications, admin configuration changes, backup operations, and OAuth flows** in a dual-storage system (SQLite and plain-text).
- Each entry includes **timestamp, user ID, action key, resource identifier, JSON details, and IP address**.
- The `writeAudit()` function in [`server/src/services/auditLog.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/services/auditLog.ts) handles persistence and log rotation.
- Administrators can query events via the **Admin UI**, REST API, or direct file access at `./data/logs/trek.log`.
- The system supports **custom events** for application-specific monitoring needs.

## Frequently Asked Questions

### What is the purpose of the TREK audit log?

The audit log serves as a tamper-aware security and operations trail that enables administrators to detect malicious activity, trace user actions for forensic analysis, monitor configuration changes, and maintain compliance records. It provides both a searchable database interface and a persistent plain-text log file for external aggregation.

### How does TREK handle client IP addresses in audit entries?

TREK extracts client IPs via the `getClientIp()` function in [`server/src/services/auditLog.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/services/auditLog.ts), which respects the `X-Forwarded-For` header when the `TRUST_PROXY` environment variable is configured. This ensures accurate IP logging when the application runs behind reverse proxies or load balancers.

### Can I add custom events to the TREK audit log?

Yes. Import `writeAudit` from [`server/src/services/auditLog.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/services/auditLog.ts) and invoke it with a custom action key, user ID, resource identifier, and details object. Custom events persist to both the database and log file, though you must add entries to `ACTION_LABELS` in the audit service if you want human-readable labels in the Admin UI.

### Where are audit log files stored and how long are they retained?

Audit data persists indefinitely in the SQLite `audit_log` table. Plain-text logs write to `./data/logs/trek.log` with automatic rotation based on the application's logging configuration. Administrators should configure external log rotation or backup policies for long-term retention of the text files.