> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Audit logs

> Record who changed what and when in each organization with the GatoJS audit-logs module, trackAudit, and the AuditTrail component.

An organization owner or admin wants to know who did what. They search both ways: by person ("what did this warehouse worker do?") and by thing ("who accepted delivery 123, and what changed?"). The `audit-logs` module stores each event as a row with the organization, actor, action, entity, before and after state, channel and a service-mode flag. It gives you an `/audit-log` page with filters and an `<AuditTrail>` component that shows the history of a single entity.

Events are recorded by the code that changes data: the core (membership, superadmin entering an organization), other kit modules (`api-keys`, `uploads`) and your own features. They all call the same core function, `trackAudit`, and the module plugs a database writer in behind it. Actions are open-ended: `action` is any string, and the module that records an action declares its label.

## What it doesn't do

* **No retention.** Nothing deletes old entries, so the table grows without limit. Entries only disappear together with their organization. A planned background jobs module will cover retention and cleanup.
* **No automatic recording.** A change that your code doesn't pass to `trackAudit`, and that the module's better-auth plugin doesn't catch, never reaches the log. Calling `trackAudit` after every data change is a convention; nothing enforces it.
* **No reads, sign-ins or account changes.** Password, email, global role, ban and impersonation events aren't logged. The plugin catches five organization endpoints only.
* **No export and no cross-organization view.** Every query is limited to the active organization.

Skip the module if nobody will read the log. Your code can call `trackAudit` and declare `auditActions` without it, so you can add the module later without changing that code. Events from before the module was added are not stored anywhere.

## Requirements

| | `audit-logs` |
| - | - |
| Required kit modules | None. |
| Services (Docker, CI) | None. |
| Environment variables | None. |
| npm dependencies | `better-call` in `devDependencies`, used only by an integration test to sign a session cookie. |
| Database | `audit_logs` table and `AuditChannel` enum, so a migration after adding the module. |

## Install and remove

> [tab] Existing project
>
> **1. Add the module**
>
> ```bash theme={null}
> npx gato add audit-logs
> ```
>
> This copies the module files, adds `auditLogs AuditLog[]` to `User` and `Organization` in the `wa:relations` region, runs `gato generate` and `npm install`.
>
> **2. Create the migration**
>
> ```bash theme={null}
> npx prisma migrate dev --name add-audit-logs
> ```
>
> Commit the migration. If you used `--no-install`, also run `npm run db:generate`: Prisma 7's `migrate dev` doesn't run the generator, and without it `prisma.auditLog` doesn't exist.
>
> No variables, services or CI changes are needed.

> [tab] New project
>
> ```bash theme={null}
> npm create gato-app@latest acme-app -- --modules audit-logs
> ```
>
> The first migration (`npx prisma migrate dev --name init`) creates the `audit_logs` table.

On deployment, `npx prisma migrate deploy` applies the migration. Events are recorded from the first request served by the new version; earlier events can't be reconstructed.

### Removing the module

`npx gato remove audit-logs` refuses when a project module lists `audit-logs` in `requires`, for example because it renders `<AuditTrail>`. After a successful removal:

| What | After `gato remove audit-logs` |
| - | - |
| `audit_logs` table and `AuditChannel` enum | Stay with their data until you apply `npx prisma migrate dev --name remove-audit-logs`. That migration drops the full event history; copy the table first if you need it. |
| `trackAudit` calls in the core, modules and your code | Keep working and record nothing, because `auditSinks` is empty. |
| `auditActions` declarations | Stay and do nothing. |
| Your code that imports module files (`<AuditTrail>`, `writeAuditLog`) | Stops building with `TS2307: Cannot find module '@/features/audit-logs/…'`. `gato remove` doesn't look for such imports. |
| Menu item, `/audit-log` page, better-auth plugin | Removed with the files and the registry. |

## What the module adds

### Module definition

`src/features/audit-logs/module.ts`:

| Field | Value | Effect |
| - | - | - |
| `key` | `audit-logs` | Key for `requireModuleAccess("audit-logs")` and the translation namespace. |
| `nav` | `/audit-log`, label "Audit log", icon `scroll-text`, `order: 90` | Menu item for roles with access. |
| `routePrefixes` | `["/audit-log"]` | Assigns the path to the module for the menu and path guard. |
| `roles` | `["owner", "admin"]` | Organization owners and admins have access; `member` doesn't. |
| `auditActions` | Six core actions (see [reference](#actions-declared-by-the-kit)) | Labels for events recorded by the core and the module's plugin. |

### The `AuditLog` model

`prisma/schema/audit-logs.prisma`, table `audit_logs`:

| Field | Column and type | Meaning |
| - | - | - |
| `id` | `id`, `uuid` | Entry ID. |
| `organizationId` | `organization_id`, text, required | Organization where the event happened. |
| `userId` | `user_id`, text, optional | Actor. `null` for events without a user (system, API key) and after the user is deleted. |
| `action` | `action`, text | Action in the form `entity.verb`, for example `member.invited`. |
| `entityType` | `entity_type`, text | Entity type, for example `invitation`. |
| `entityId` | `entity_id`, text, optional | Entity ID. |
| `oldData`, `newData` | `old_data`, `new_data`, `jsonb`, optional | State before and after the change, redacted. |
| `channel` | `channel`, `AuditChannel` (`WEB`, `API`), default `WEB` | Where the event came from. |
| `credentialId` | `credential_id`, text, optional | Credential ID (for example an API key). No foreign key, so the entry outlives the key. |
| `serviceMode` | `service_mode`, boolean, default `false` | Superadmin event in service mode. |
| `createdAt` | `created_at`, `timestamptz`, default `now()` | When the entry was written. |

Indexes: `(organizationId, createdAt)`, `(organizationId, entityType, entityId)` and `(organizationId, userId, createdAt)`. Each starts with `organizationId`, because every query filters by organization.

Deleting an organization deletes its entries (`onDelete: Cascade`). Deleting a user keeps the entries with `userId` set to `null`, shown as "System". Writing an event with an `organizationId` that doesn't exist fails on the foreign key inside the sink; `trackAudit` catches and logs it.

### The `/audit-log` page

The page calls `requireModuleAccess("audit-logs")`, parses URL parameters and loads entries and the list of actors in parallel. Filters, sorting and paging live in the URL, so you can share a link to a filtered view.

| Element | Behavior |
| - | - |
| Action filter | Actions declared in `auditActions` across the registry, with labels. Undeclared actions aren't listed; you can still filter by them with the `action` URL parameter. |
| Entity type and entity ID | Text fields, applied on blur. |
| Actor filter | Users with at least one entry in the active organization, alphabetically. |
| From and To | Days in `YYYY-MM-DD` format, both inclusive, in the server process time zone. |
| Columns | Date, action (with "API" and "Service mode" badges), entity (type and ID), actor (name or "System"). |
| Row details | Expanding a row shows `oldData` ("Before") and `newData` ("After") as JSON. |
| Sorting and paging | By date (default, descending), action or entity type; 10, 25 (default), 50 or 100 per page. |

Invalid URL parameters don't cause errors: each bad value falls back to its default or is ignored.

> [!NOTE]
>
> Date filters use the time zone of the Node process (`TZ`), not UTC or the browser's zone. The date column shows the browser's local time. On a UTC server, a user in another zone sees entries near midnight shifted relative to the filter boundaries.

### Access by role

The page, its queries and `<AuditTrail>` are available to owners and admins of the active organization and to accounts with the global `admin` or `superadmin` role. A `member` gets a 404 on the page, and `<AuditTrail>` renders nothing for them. Owners and admins see every entry of their organization, including superadmin service-mode entries and the contents of `oldData` and `newData`, such as invited email addresses. See [Auth and roles](https://docs.gatojs.com/concepts/auth-and-roles.md).

The module has no server actions (`"use server"` files), so no one can add or change an entry from the browser.

### Events recorded by the core and kit modules

The module's better-auth plugin (`src/features/audit-logs/auth.ts`) catches five organization endpoints. It takes the organization from the endpoint response, not the request body, and a failed endpoint call creates no entry. Other events are recorded by core and module code directly.

| Action | `entityType` | Data | Recorded by |
| - | - | - | - |
| `member.invited` | `invitation` | `newData: { email, role }` | Plugin (`/organization/invite-member`); core `inviteUserCommand` on the Users page. |
| `invitation.canceled` | `invitation` | none | Plugin (`/organization/cancel-invitation`). |
| `invitation.accepted` | `invitation` | none | Plugin (`/organization/accept-invitation`); core, when a user signs up with an invitation. |
| `member.role_changed` | `member` | `oldData: { role }` when known, `newData: { role }` | Plugin (`/organization/update-member-role`). |
| `member.removed` | `member` | `oldData: { userId, role }` | Plugin (`/organization/remove-member`). |
| `organization.entered` | `organization` | `serviceMode: true` | Core, when a superadmin enters an organization without membership. |
| `api_key.created` | `api_key` | `newData: { name, scopes, displayPrefix }` | [`api-keys`](https://docs.gatojs.com/modules/api-keys). |
| `api_key.revoked`, `api_key.deleted` | `api_key` | `oldData: { name, displayPrefix }` | `api-keys`, only when the row actually changed. |
| `upload.created` | `upload` | `newData: { purpose, key, size }` | [`uploads`](https://docs.gatojs.com/modules/uploads). |
| `upload.deleted` | `upload` | `oldData: { purpose, key, size }` | `uploads`. |

No kit code writes the `API` channel or a `credentialId`. Your API routes fill those in; see [Recording from an API key route](#recording-from-an-api-key-route).

## Entry point contracts

`trackAudit`, `auditActor` and `AuditSink` live in the core (`src/shared/lib/audit.ts`), and `auditActions` is a `defineModule` field. They exist in every project, with or without the module.

### `trackAudit`

```ts src/shared/lib/audit.ts theme={null}
export interface AuditEvent {
  organizationId: string;
  actorUserId: string | null;
  action: string;
  entityType: string;
  entityId?: string | null;
  oldData?: unknown;
  newData?: unknown;
  channel?: AuditChannel; // "WEB" | "API"
  credentialId?: string | null;
  serviceMode?: boolean;
}

export type AuditSink = (event: AuditEvent) => Promise<void>;

export async function trackAudit(
  event: AuditEvent,
  sinks: readonly AuditSink[] = auditSinks,
): Promise<void> {
  for (const sink of sinks) {
    try {
      await sink(event);
    } catch (error) {
      logger.error("trackAudit failed", { action: event.action, error });
    }
  }
}
```

* **Input.** `organizationId`, `actorUserId`, `action` and `entityType` are required. Take the organization from the context (`auditActor(context)`), never from user input.
* **When to call.** After a successful write, before returning the result.
* **What it does.** Calls each sink in `auditSinks` in order with the same event object and awaits each one.
* **Errors.** A failing sink is logged as `trackAudit failed` and the next sink still runs. `trackAudit` never throws, so **a failed audit write doesn't fail the command or roll back its change**. The user sees success; only the logs show the missing entry.
* **No transaction.** The entry is written in a separate query, outside your command's transaction.
* **Without the module.** If no feature has an `audit-sink.ts`, the call records nothing, logs nothing and returns normally.
* **Security.** `audit.ts` has no `"use server"` directive, so the browser can't call `trackAudit`. Don't export a server action that accepts an event from the client and forwards it.

### `auditActor`

`auditActor(context)` takes an `OrgContext` and returns `{ organizationId, actorUserId, serviceMode }`. Spread it into the event (`...auditActor(context)`) and a superadmin's change in service mode gets `serviceMode: true` and a "Service mode" badge. An event built by hand without `serviceMode` is stored with `false`, even in service mode.

`getOrgContext()` and `requireModuleAccess()` return the context. Routes authenticated with an API key have no session and no `OrgContext`, so they build the event by hand.

### `AuditSink`

A sink is a function `(event: AuditEvent) => Promise<void>` exported as `auditSink` from `src/features/<name>/audit-sink.ts`. `gato generate` adds it to `auditSinks`, after kit module sinks. The module's sink is a one-liner:

```ts src/features/audit-logs/audit-sink.ts theme={null}
import type { AuditSink } from "@/shared/lib/audit";
import { writeAuditLog } from "./services/write-audit-log";

export const auditSink: AuditSink = writeAuditLog;
```

You can add your own sink, for example to forward events to an external system.

> [!WARNING]
>
> A sink receives the event **before redaction**. Only `writeAuditLog` redacts. A sink that stores or sends `oldData` and `newData` must redact them itself, for example with `redactSensitive` from the module. Don't mutate the event: every sink gets the same object. A slow sink delays every command that calls `trackAudit`, because sinks run one after another.

### `auditActions`

The `auditActions?: { action: string; labelKey: string }[]` field in `defineModule` tells the log how to display an action. The label is `labelKey` in the translation namespace of the declaring module, which is its feature folder name, so `key` must equal the folder name.

* **Who reads it.** The `/audit-log` page (table labels and the action filter) and `<AuditTrail>`.
* **No declaration.** The action shows as a raw string and isn't in the filter list. Recording still works: the declaration isn't validation.
* **Missing translation key.** next-intl reports `MISSING_MESSAGE` and shows the key path.
* **Same action in two modules.** The first in the registry wins: core, then kit modules, then project modules.

### Redaction

Owners and admins read the log, so before writing, `redactSensitive` replaces the value of every sensitive key with `"[REDACTED]"` at any depth in objects and arrays. A key is sensitive when, lowercased and with `-` and `_` removed, it contains `password`, `secret`, `token`, `apikey`, `authorization`, `cookie`, `privatekey` or `hashedkey`. That covers `newPassword`, `client_secret`, `X-API-Key`, `set-cookie` and `tokens`. Objects with `toJSON` are redacted after serialization; `Date` values and primitives pass through.

> [!WARNING]
>
> Redaction works on key names only. A secret under a neutral name (`value`, `code`, `pin`) or inside a string (`"Bearer abc"` in a `header` field) is stored and shown to owners and admins. Personal data such as email addresses is not redacted. Pass only the fields you want in the log, never a whole database row.

## Record an event from your code

The examples below come from a `deliveries` project module that records accepted deliveries.

### In a command

Call `trackAudit` after the service-mode check and after the write:

```ts src/features/deliveries/services/commands/receive-delivery-command.ts theme={null}
import { auditActor, trackAudit } from "@/shared/lib/audit";

// inside the command, after parsing input:
const context = await requireModuleAccess("deliveries");
assertServiceModeConfirmed(context, confirmation);

const delivery = await prisma.delivery.create({
  data: {
    organizationId: context.organizationId,
    supplier: parsed.data.supplier,
    packages: parsed.data.packages,
  },
  select: { id: true },
});

await trackAudit({
  ...auditActor(context),
  action: "delivery.accepted",
  entityType: "delivery",
  entityId: delivery.id,
  newData: {
    supplier: parsed.data.supplier,
    packages: parsed.data.packages,
  },
});
```

The order matters. A refused service-mode confirmation, invalid input or a failed write never reaches `trackAudit`, so no entry is written. `newData` contains only the fields you want in the log. A failed audit write doesn't change the command result.

### Add an action label

Declare the label in the module that records the action:

```ts src/features/deliveries/module.ts theme={null}
export default defineModule({
  key: "deliveries",
  nav: [{ href: "/deliveries", labelKey: "nav", icon: "truck", order: 50 }],
  routePrefixes: ["/deliveries"],
  auditActions: [
    { action: "delivery.accepted", labelKey: "action-delivery-accepted" },
  ],
});
```

Add `action-delivery-accepted` to `src/features/deliveries/i18n/en.json` and every other locale file. A new `module.ts` or translation file needs `npx gato generate`; a new entry in an existing `auditActions` array doesn't.

### Show an entity's history

`<AuditTrail entityType entityId />` is an async server component. Render it in a page or another server component, not in a `"use client"` component:

```tsx src/app/[locale]/(app)/deliveries/page.tsx theme={null}
import { AuditTrail } from "@/features/audit-logs/components/audit-trail";

// …
{deliveries.map((delivery) => (
  <li key={delivery.id}>
    <p>{delivery.supplier}</p>
    <AuditTrail entityType="delivery" entityId={delivery.id} />
  </li>
))}
```

* It shows the 50 newest entries for the entity in the active organization, newest first: time, action label and actor ("System" when there is none). With no entries it shows "No history".
* A user without module access (role `member`) sees nothing: the component returns `null` and the page still renders, so you can place it on pages every role can open.
* Entries with the same `entityId` in another organization, or with another `entityType`, are not shown.
* Time is formatted on the server (`yyyy-MM-dd HH:mm`) in the server's time zone.
* Each component runs its own query, so a list of 20 entities runs 20 queries.

Importing `<AuditTrail>` ties your feature to the module. Add `"requires": ["audit-logs"]` to the feature's `projectModules` entry in `.wa/kit.json`, so `gato remove audit-logs` refuses instead of breaking your build.

### Recording from an API key route

A route authenticated with an API key has no session, so there is no `auditActor`. Build the event from the key context: `organizationId` from the context, `actorUserId: null`, `channel: "API"` and `credentialId` set to the key ID. The log then shows an "API" badge and "System" as the actor. See [API keys](https://docs.gatojs.com/modules/api-keys.md#record-an-audit-event-with-the-api-channel) for a full example.

### Code that works without the module

A feature that should run in projects with and without `audit-logs`:

* calls `trackAudit` and `auditActor` from `@/shared/lib/audit` and declares `auditActions`. That works everywhere, and events start being stored after `gato add audit-logs` with no code change;
* imports nothing from `@/features/audit-logs/` (`<AuditTrail>`, `redactSensitive`, queries);
* doesn't list `audit-logs` in `requires`.

The core does the same: its commands call `trackAudit` without checking whether the module is installed.

## Security and isolation

* **Isolation.** Every module query filters by `organizationId` from the context: the entry list, the actor list and entity history. Filtering by a user ID from another organization returns nothing. An event is stored in `event.organizationId`, so take it from the context.
* **Owners and admins only**, checked in the page, in each query and in `<AuditTrail>`. A `member` can't read the queries even from another page, because the guard is in the query.
* **No writes from the browser.** The module has no server actions and `audit.ts` has no `"use server"`.
* **Redaction is name-based** and misses secrets under neutral names and personal data.
* **Custom sinks get unredacted data.**
* **A failed audit write doesn't stop the command.** Monitor your logs for `trackAudit failed`. See [Logging and observability](https://docs.gatojs.com/configuration/logging-and-observability.md).
* **Service mode is visible** only when the event gets `serviceMode` from `auditActor(context)`.
* **No retention.** Personal data in `oldData` and `newData` stays until the organization is deleted.

## Testing

**Integration test with the real sink.** The strongest test for a command that calls `trackAudit` runs against a real database with the real `trackAudit` and the `audit-logs` sink, and checks the row in `audit_logs`. Mock only framework I/O (`next/headers`, `next/cache`, `next/navigation`, `@/i18n/routing`, `next-intl/server`) and the session with `vi.spyOn(auth.api, "getSession")`.

```ts src/features/deliveries/services/__tests__/receive-delivery-command.integration.test.ts theme={null}
it("writes delivery.accepted in the active organization, not in B", async () => {
  await signInAs(world.alice, world.orgA);

  const result = await receiveDeliveryCommand({
    supplier: "North Wholesale",
    packages: "3",
  });

  expect(result.success).toBe(true);
  const rowsA = await prisma.auditLog.findMany({
    where: { organizationId: world.orgA.id },
  });
  expect(rowsA).toHaveLength(1);
  expect(rowsA[0]).toMatchObject({
    userId: world.alice.id,
    action: "delivery.accepted",
    entityType: "delivery",
    newData: { supplier: "North Wholesale", packages: 3 },
    oldData: null,
    channel: "WEB",
    serviceMode: false,
  });
  await expect(
    prisma.auditLog.count({ where: { organizationId: world.orgB.id } }),
  ).resolves.toBe(0);
});
```

Add cases for invalid input (no row), a superadmin in service mode without confirmation (error, no row) and with confirmation (`serviceMode: true`). Use literal expected values, not values computed by production code. `resetDatabase()` truncates core tables with `CASCADE`, so audit entries go with their organizations. See [Testing](https://docs.gatojs.com/guides/testing.md).

**Mocking `trackAudit`.** When a test doesn't need the row, replace only `trackAudit` and keep `auditActor`:

```ts theme={null}
vi.mock("@/shared/lib/audit", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@/shared/lib/audit")>()),
  trackAudit: (event: unknown) => mockTrackAudit(event),
}));
```

This checks the event contents, not redaction or storage. Don't mock `trackAudit` in a test that should prove the entry lands in the right organization.

**Without the module.** With no sink, a test using the real `trackAudit` passes but stores nothing, and the test database has no `audit_logs` table. Check event contents with a mock.

## Troubleshooting

| Symptom | Cause | Fix |
| - | - | - |
| The command succeeds but there's no entry; logs show `trackAudit failed` | A sink threw (database error, organization foreign key). | Check the logged error and that `organizationId` comes from the context. |
| No entry and nothing in the logs | The module isn't installed (`auditSinks` is empty), or the code path doesn't reach `trackAudit` (an early `return`). | Run `npx gato list`; make sure every success branch calls `trackAudit` after the write. |
| Raw action string instead of a label | No `auditActions` declaration. | Declare the action in the `module.ts` of the feature that records it. |
| Key path instead of a label and `MISSING_MESSAGE` | The label key is missing from a locale file, the translation file isn't registered, or the module `key` differs from its folder name. | Add the key in every locale; run `npx gato generate` after adding a new translation file; make `key` match the folder name. |
| `TS2307: Cannot find module '@/features/audit-logs/…'` | Your code imports a module file but the module isn't installed. | `npx gato add audit-logs`, or remove the import. |
| `Cannot read properties of undefined (reading 'create')` on `prisma.auditLog` | The Prisma client doesn't know the model; the generator didn't run after `migrate dev`. | `npm run db:generate`. |
| Date filter covers different hours than the date column shows | Filters use the server time zone; the column uses the browser's. | Set the server process `TZ` to the client's zone, or account for the offset. |
| `gato remove audit-logs` refuses, naming a module | A project module lists `audit-logs` in `requires`. | Remove the `<AuditTrail>` import and the `requires` entry, or keep the module. |
| `audit_logs` keeps growing | No retention. | Clean up outside the kit, for example with a scheduled database job. |

## Reference

### `AuditEvent` fields

| Field | Type | Required | Stored default | Column |
| - | - | - | - | - |
| `organizationId` | `string` | yes | | `organization_id` |
| `actorUserId` | `string \| null` | yes | | `user_id` |
| `action` | `string` | yes | | `action` |
| `entityType` | `string` | yes | | `entity_type` |
| `entityId` | `string \| null` | no | `null` | `entity_id` |
| `oldData`, `newData` | `unknown` | no | `NULL`, redacted | `old_data`, `new_data` |
| `channel` | `"WEB" \| "API"` | no | `"WEB"` | `channel` |
| `credentialId` | `string \| null` | no | `null` | `credential_id` |
| `serviceMode` | `boolean` | no | `false` | `service_mode` |

### Actions declared by the kit

| Action | Declared by | English label |
| - | - | - |
| `organization.entered` | `audit-logs` | Entered organization |
| `member.invited` | `audit-logs` | Member invited |
| `invitation.canceled` | `audit-logs` | Invitation canceled |
| `invitation.accepted` | `audit-logs` | Invitation accepted |
| `member.role_changed` | `audit-logs` | Member role changed |
| `member.removed` | `audit-logs` | Member removed |
| `api_key.created`, `api_key.revoked`, `api_key.deleted` | `api-keys` | API key created / revoked / deleted |
| `upload.created`, `upload.deleted` | `uploads` | File uploaded / deleted |

Core actions are declared by `audit-logs`, not by the core, so without the module nothing displays them.

### `/audit-log` URL parameters

| Parameter | Values | Invalid value |
| - | - | - |
| `page` | integer 1–1,000,000 | `1` |
| `pageSize` | `10`, `25`, `50`, `100` | `25` |
| `sortBy` | `createdAt`, `action`, `entityType` | `createdAt` |
| `sortDir` | `asc`, `desc` | `desc` |
| `userId`, `action`, `entityType`, `entityId` | text, 1–200 characters after trimming, exact match | ignored |
| `from`, `to` | `YYYY-MM-DD`, server time zone, inclusive | ignored |

### Files

| File | Export | Purpose |
| - | - | - |
| `components/audit-log-view.tsx` | `AuditLogView` | Client view of `/audit-log`. |
| `components/audit-trail.tsx` | `AuditTrail` | Server component with one entity's history. |
| `services/queries/audit-log-queries.ts` | `listAuditLogsQuery`, `listAuditLogActorsQuery` | Entries and actors of the active organization, guarded by `requireModuleAccess("audit-logs")`. |
| `services/queries/audit-trail-query.ts` | `getEntityAuditTrailQuery` | 50 newest entries for an entity; returns `null` without access. |
| `services/write-audit-log.ts` | `writeAuditLog` | Writes a redacted entry. |
| `services/redact.ts` | `redactSensitive` | Key-name redaction. |
| `audit-sink.ts` | `auditSink` | The module's sink. |
| `auth.ts` | `authPlugin` | better-auth plugin for organization events. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.