Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

📒 feat: Audit Log Backend for SystemGrant Assign and Revoke Events (#13087)

Dustin Healy6a63531eb42f
diff --git a/api/server/index.js b/api/server/index.js
index 501946a413..a8c7c35e5a 100644
--- a/api/server/index.js
+++ b/api/server/index.js
@@ -243,6 +243,7 @@ const startServer = async () => {
app.use('/api/admin/roles', routes.adminRoles);
app.use('/api/admin/skills', routes.adminSkills);
app.use('/api/admin/users', routes.adminUsers);
+ app.use('/api/admin/audit-log', routes.adminAuditLog);
app.use('/api/actions', routes.actions);
app.use('/api/keys', routes.keys);
app.use('/api/api-keys', routes.apiKeys);
diff --git a/api/server/routes/admin/audit.js b/api/server/routes/admin/audit.js
new file mode 100644
index 0000000000..7332f8296a
--- /dev/null
+++ b/api/server/routes/admin/audit.js
@@ -0,0 +1,35 @@
+const express = require('express');
+const { createAdminAuditLogHandlers } = require('@librechat/api');
+const { SystemCapabilities } = require('@librechat/data-schemas');
+const { requireCapability } = require('~/server/middleware/roles/capabilities');
+const { requireJwtAuth } = require('~/server/middleware');
+const db = require('~/models');
+
+const router = express.Router();
+
+const requireAdminAccess = requireCapability(SystemCapabilities.ACCESS_ADMIN);
+const requireAuditLogRead = requireCapability(SystemCapabilities.READ_AUDIT_LOG);
+
+const handlers = createAdminAuditLogHandlers({
+ listAuditLogPage: db.listAuditLogPage,
+ findAuditLogEntry: db.findAuditLogEntry,
+ streamAuditLogEntries: db.streamAuditLogEntries,
+ verifyAuditChain: db.verifyAuditChain,
+});
+
+/**
+ * `ACCESS_ADMIN` gates entry to the admin surface; `READ_AUDIT_LOG` then gates
+ * this specific feature within that surface. The two capabilities are
+ * independent in `CapabilityImplications`, so a role delegated only
+ * `READ_AUDIT_LOG` without `ACCESS_ADMIN` would otherwise bypass the admin
+ * boundary on this router — every other admin router enforces the same pair.
+ */
+router.use(requireJwtAuth, requireAdminAccess, requireAuditLogRead);
+
+router.get('/', handlers.listAuditLog);
+/** Literal sub-paths MUST precede `/:id` so they aren't matched as `{ id }`. */
+router.get('/export.csv', handlers.exportAuditLogCsv);
+router.get('/verify', handlers.verifyAuditLog);
+router.get('/:id', handlers.getAuditLogEntry);
+
+module.exports = router;
diff --git a/api/server/routes/admin/grants.js b/api/server/routes/admin/grants.js
index a0fa73dc43..f48c3ddd60 100644
--- a/api/server/routes/admin/grants.js
+++ b/api/server/routes/admin/grants.js
@@ -21,6 +21,9 @@ const handlers = createAdminGrantsHandlers({
getHeldCapabilities: db.getHeldCapabilities,
getCachedPrincipals,
checkRoleExists: async (name) => (await db.getRoleByName(name)) != null,
+ recordAuditEntry: db.recordAuditEntry,
+ /** Opt-in: fail the grant request if its audit entry can't be persisted. */
+ auditFailClosed: process.env.AUDIT_LOG_FAIL_CLOSED === 'true',
});
router.use(requireJwtAuth, requireAdminAccess);
diff --git a/api/server/routes/admin/roles.js b/api/server/routes/admin/roles.js
index f2bbd7f7ea..5c6d4e92e8 100644
--- a/api/server/routes/admin/roles.js
+++ b/api/server/routes/admin/roles.js
@@ -29,6 +29,7 @@ const handlers = createAdminRolesHandlers({
deleteConfig: db.deleteConfig,
deleteAclEntries: db.deleteAclEntries,
deleteGrantsForPrincipal: db.deleteGrantsForPrincipal,
+ recordAuditEntry: db.recordAuditEntry,
});
router.use(requireJwtAuth, requireAdminAccess);
diff --git a/api/server/routes/index.js b/api/server/routes/index.js
index 59955e937e..ac2b38f579 100644
--- a/api/server/routes/index.js
+++ b/api/server/routes/index.js
@@ -8,6 +8,7 @@ const adminGroups = require('./admin/groups');
const adminRoles = require('./admin/roles');
const adminSkills = require('./admin/skills');
const adminUsers = require('./admin/users');
+const adminAuditLog = require('./admin/audit');
const endpoints = require('./endpoints');
const staticRoute = require('./static');
const messages = require('./messages');
@@ -47,6 +48,7 @@ module.exports = {
adminRoles,
adminSkills,
adminUsers,
+ adminAuditLog,
keys,
apiKeys,
user,
diff --git a/package-lock.json b/package-lock.json
index 097132596b..0d9398d548 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -44785,7 +44785,7 @@
},
"packages/data-schemas": {
"name": "@librechat/data-schemas",
- "version": "0.0.53",
+ "version": "0.0.54",
"license": "MIT",
"devDependencies": {
"@rollup/plugin-alias": "^5.1.0",
diff --git a/packages/api/src/admin/auditLog.spec.ts b/packages/api/src/admin/auditLog.spec.ts
new file mode 100644
index 0000000000..cdb221bcc5
--- /dev/null
+++ b/packages/api/src/admin/auditLog.spec.ts
@@ -0,0 +1,463 @@
+import { Types } from 'mongoose';
+import { EventEmitter } from 'events';
+import { MAX_AUDIT_EXPORT_ROWS } from '@librechat/data-schemas';
+import type {
+ AdminAuditLogEntry,
+ AuditChainVerification,
+ AuditLogPage,
+} from '@librechat/data-schemas';
+import type { Response } from 'express';
+import type { AdminAuditLogDeps } from './auditLog';
+import type { ServerRequest } from '~/types/http';
+import { createAdminAuditLogHandlers } from './auditLog';
+
+jest.mock('@librechat/data-schemas', () => ({
+ ...jest.requireActual('@librechat/data-schemas'),
+ logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() },
+}));
+
+const validObjectId = new Types.ObjectId().toString();
+
+function mockEntry(overrides: Partial<AdminAuditLogEntry> = {}): AdminAuditLogEntry {
+ return {
+ id: new Types.ObjectId().toString(),
+ schemaVersion: 1,
+ category: 'grant',
+ action: 'grant.assigned',
+ outcome: 'success',
+ severity: 'warning',
+ actor: { type: 'user', id: new Types.ObjectId().toString(), name: 'Alice Admin' },
+ target: { type: 'role', id: 'ADMIN', name: 'ADMIN' },
+ metadata: { capability: 'manage:users' },
+ context: { ip: '10.0.0.1', requestId: 'req-1' },
+ integrity: { seq: 1, hash: 'a'.repeat(64), prevHash: '0'.repeat(64) },
+ timestamp: new Date('2025-01-15T10:30:00.000Z').toISOString(),
+ ...overrides,
+ };
+}
+
+function mockPage(overrides: Partial<AuditLogPage> = {}): AuditLogPage {
+ return { entries: [], total: 0, nextCursor: null, ...overrides };
+}
+
+function mockVerification(overrides: Partial<AuditChainVerification> = {}): AuditChainVerification {
+ return {
+ ok: true,
+ chainKey: 'tenant-a',
+ checked: 3,
+ range: { firstSeq: 1, lastSeq: 3 },
+ ...overrides,
+ };
+}
+
+function createReqRes(
+ overrides: {
+ params?: Record<string, string>;
+ query?: Record<string, string | string[]>;
+ user?: { _id?: Types.ObjectId; id?: string; role?: string; tenantId?: string } | undefined;
+ } = {},
+) {
+ const req = {
+ params: overrides.params ?? {},
+ query: overrides.query ?? {},
+ body: {},
+ user: 'user' in overrides ? overrides.user : { _id: new Types.ObjectId(), role: 'admin' },
+ } as unknown as ServerRequest;
+
+ const json = jest.fn();
+ const status = jest.fn().mockReturnValue({ json });
+ const res = { status, json } as unknown as Response;
+
+ return { req, res, status, json };
+}
+
+interface CsvCaptureContext {
+ req: ServerRequest;
+ res: Response;
+ emitter: EventEmitter;
+ reqEmitter: EventEmitter;
+ chunks: string[];
+ endCalled: () => boolean;
+ emitClose: () => void;
+}
+
+/**
+ * Wraps request/response in EventEmitter shims so the streaming handler can
+ * register `close` / `aborted` / `drain` listeners and the test can drive them.
+ */
+function createCsvContext(
+ overrides: {
+ query?: Record<string, string | string[]>;
+ user?: { _id?: Types.ObjectId; id?: string; role?: string; tenantId?: string } | undefined;
+ writeReturns?: boolean;
+ } = {},
+): CsvCaptureContext {
+ const emitter = new EventEmitter();
+ const reqEmitter = new EventEmitter();
+ const chunks: string[] = [];
+ let ended = false;
+
+ const res = Object.assign(emitter, {
+ setHeader: jest.fn(),
+ write: jest.fn((chunk: string) => {
+ chunks.push(chunk);
+ return overrides.writeReturns ?? true;
+ }),
+ end: jest.fn(() => {
+ ended = true;
+ }),
+ headersSent: false,
+ status: jest.fn().mockReturnValue({ json: jest.fn() }),
+ removeListener: emitter.removeListener.bind(emitter),
+ }) as unknown as Response;
+
+ const req = Object.assign(reqEmitter, {
+ params: {},
+ query: overrides.query ?? {},
+ body: {},
+ user: 'user' in overrides ? overrides.user : { _id: new Types.ObjectId(), role: 'admin' },
+ removeListener: reqEmitter.removeListener.bind(reqEmitter),
+ }) as unknown as ServerRequest;
+
+ return {
+ req,
+ res,
+ emitter,
+ reqEmitter,
+ chunks,
+ endCalled: () => ended,
+ emitClose: () => emitter.emit('close'),
+ };
+}
+
+function createDeps(overrides: Partial<AdminAuditLogDeps> = {}): AdminAuditLogDeps {
+ return {
+ listAuditLogPage: jest.fn<Promise<AuditLogPage>, unknown[]>().mockResolvedValue(mockPage()),
+ findAuditLogEntry: jest
+ .fn<Promise<AdminAuditLogEntry | null>, unknown[]>()
+ .mockResolvedValue(null),
+ streamAuditLogEntries: jest
+ .fn<Promise<{ count: number; truncated: boolean }>, unknown[]>()
+ .mockResolvedValue({ count: 0, truncated: false }),
+ verifyAuditChain: jest
+ .fn<Promise<AuditChainVerification>, unknown[]>()
+ .mockResolvedValue(mockVerification()),
+ ...overrides,
+ };
+}
+
+describe('createAdminAuditLogHandlers', () => {
+ describe('listAuditLog', () => {
+ it('returns 401 when req.user is missing', async () => {
+ const handlers = createAdminAuditLogHandlers(createDeps());
+ const { req, res, status, json } = createReqRes({ user: undefined });
+ await handlers.listAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(401);
+ expect(json).toHaveBeenCalledWith({ error: 'Authentication required' });
+ });
+
+ it('returns 200 with the page payload', async () => {
+ const page = mockPage({ entries: [mockEntry()], total: 1, nextCursor: 5 });
+ const deps = createDeps({ listAuditLogPage: jest.fn().mockResolvedValue(page) });
+ const handlers = createAdminAuditLogHandlers(deps);
+ const { req, res, status, json } = createReqRes();
+ await handlers.listAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(200);
+ expect(json).toHaveBeenCalledWith(page);
+ });
+
+ it('rejects malformed `from` with 400', async () => {
+ const deps = createDeps();
+ const handlers = createAdminAuditLogHandlers(deps);
+ const { req, res, status, json } = createReqRes({ query: { from: '2025-01-01 10:00' } });
+ await handlers.listAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(400);
+ expect(json.mock.calls[0][0].error).toMatch(/from/);
+ expect(deps.listAuditLogPage).not.toHaveBeenCalled();
+ });
+
+ it('rejects local-time ISO without a zone offset', async () => {
+ const handlers = createAdminAuditLogHandlers(createDeps());
+ const { req, res, status } = createReqRes({ query: { to: '2025-01-01T10:00:00' } });
+ await handlers.listAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(400);
+ });
+
+ it('accepts ISO timestamps with a `+HH:MM` offset', async () => {
+ const handlers = createAdminAuditLogHandlers(createDeps());
+ const { req, res, status } = createReqRes({ query: { from: '2025-01-01T10:00:00+02:00' } });
+ await handlers.listAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(200);
+ });
+
+ it('widens a date-only `to` filter to the end of the day UTC', async () => {
+ const deps = createDeps();
+ const handlers = createAdminAuditLogHandlers(deps);
+ const { req, res } = createReqRes({ query: { to: '2025-01-15' } });
+ await handlers.listAuditLog(req, res);
+ const filtersArg = (deps.listAuditLogPage as jest.Mock).mock.calls[0][1];
+ expect((filtersArg.to as Date).toISOString()).toBe('2025-01-15T23:59:59.999Z');
+ });
+
+ it('rejects an inverted date range with 400', async () => {
+ const handlers = createAdminAuditLogHandlers(createDeps());
+ const { req, res, status } = createReqRes({
+ query: { from: '2025-02-01', to: '2025-01-01' },
+ });
+ await handlers.listAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(400);
+ });
+
+ it('rejects an out-of-range date-only value instead of normalizing it', async () => {
+ const deps = createDeps();
+ const handlers = createAdminAuditLogHandlers(deps);
+ const { req, res, status } = createReqRes({ query: { from: '2025-02-31' } });
+ await handlers.listAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(400);
+ expect(deps.listAuditLogPage).not.toHaveBeenCalled();
+ });
+
+ it('rejects an out-of-range day in a full ISO timestamp', async () => {
+ const deps = createDeps();
+ const handlers = createAdminAuditLogHandlers(deps);
+ const { req, res, status } = createReqRes({ query: { to: '2025-02-31T00:00:00Z' } });
+ await handlers.listAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(400);
+ expect(deps.listAuditLogPage).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['action', { action: 'nope' }],
+ ['category', { category: 'nope' }],
+ ['outcome', { outcome: 'nope' }],
+ ['severity', { severity: 'nope' }],
+ ['actorType', { actorType: 'nope' }],
+ ])('rejects an unknown %s value with 400', async (_label, query) => {
+ const handlers = createAdminAuditLogHandlers(createDeps());
+ const { req, res, status } = createReqRes({ query });
+ await handlers.listAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(400);
+ });
+
+ it('passes a multi-value action filter through as an array', async () => {
+ const deps = createDeps();
+ const handlers = createAdminAuditLogHandlers(deps);
+ const { req, res } = createReqRes({
+ query: { action: ['grant.assigned', 'grant.removed'] },
+ });
+ await handlers.listAuditLog(req, res);
+ const filtersArg = (deps.listAuditLogPage as jest.Mock).mock.calls[0][1];
+ expect(filtersArg.action).toEqual(['grant.assigned', 'grant.removed']);
+ });
+
+ it('rejects limit over the cap, negative offset, and cursor < 1', async () => {
+ const handlers = createAdminAuditLogHandlers(createDeps());
+ const over = createReqRes({ query: { limit: '600' } });
+ await handlers.listAuditLog(over.req, over.res);
+ expect(over.status).toHaveBeenCalledWith(400);
+
+ const neg = createReqRes({ query: { offset: '-1' } });
+ await handlers.listAuditLog(neg.req, neg.res);
+ expect(neg.status).toHaveBeenCalledWith(400);
+
+ const badCursor = createReqRes({ query: { cursor: '0' } });
+ await handlers.listAuditLog(badCursor.req, badCursor.res);
+ expect(badCursor.status).toHaveBeenCalledWith(400);
+ });
+
+ it('passes limit/offset/cursor through to the data layer', async () => {
+ const deps = createDeps();
+ const handlers = createAdminAuditLogHandlers(deps);
+ const { req, res } = createReqRes({ query: { limit: '10', cursor: '42' } });
+ await handlers.listAuditLog(req, res);
+ const filtersArg = (deps.listAuditLogPage as jest.Mock).mock.calls[0][1];
+ expect(filtersArg.limit).toBe(10);
+ expect(filtersArg.cursor).toBe(42);
+ });
+
+ it('sources tenant scope from the JWT and ignores a forged ?tenantId', async () => {
+ const deps = createDeps();
+ const handlers = createAdminAuditLogHandlers(deps);
+ const req = {
+ params: {},
+ query: { tenantId: 'forged-tenant' },
+ body: {},
+ user: { _id: new Types.ObjectId(), role: 'admin', tenantId: 'real-tenant' },
+ } as unknown as ServerRequest;
+ const json = jest.fn();
+ const res = { status: jest.fn().mockReturnValue({ json }), json } as unknown as Response;
+ await handlers.listAuditLog(req, res);
+ expect((deps.listAuditLogPage as jest.Mock).mock.calls[0][0]).toBe('real-tenant');
+ });
+
+ it('returns 500 when the data layer throws', async () => {
+ const deps = createDeps({
+ listAuditLogPage: jest.fn().mockRejectedValue(new Error('db down')),
+ });
+ const handlers = createAdminAuditLogHandlers(deps);
+ const { req, res, status } = createReqRes();
+ await handlers.listAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(500);
+ });
+ });
+
+ describe('getAuditLogEntry', () => {
+ it('returns 401 when unauthenticated', async () => {
+ const handlers = createAdminAuditLogHandlers(createDeps());
+ const { req, res, status } = createReqRes({ user: undefined, params: { id: validObjectId } });
+ await handlers.getAuditLogEntry(req, res);
+ expect(status).toHaveBeenCalledWith(401);
+ });
+
+ it('returns 400 for a non-ObjectId id', async () => {
+ const handlers = createAdminAuditLogHandlers(createDeps());
+ const { req, res, status } = createReqRes({ params: { id: 'nope' } });
+ await handlers.getAuditLogEntry(req, res);
+ expect(status).toHaveBeenCalledWith(400);
+ });
+
+ it('returns 404 when not found', async () => {
+ const handlers = createAdminAuditLogHandlers(createDeps());
+ const { req, res, status } = createReqRes({ params: { id: validObjectId } });
+ await handlers.getAuditLogEntry(req, res);
+ expect(status).toHaveBeenCalledWith(404);
+ });
+
+ it('returns 200 with the entry', async () => {
+ const entry = mockEntry();
+ const deps = createDeps({ findAuditLogEntry: jest.fn().mockResolvedValue(entry) });
+ const handlers = createAdminAuditLogHandlers(deps);
+ const { req, res, status, json } = createReqRes({ params: { id: validObjectId } });
+ await handlers.getAuditLogEntry(req, res);
+ expect(status).toHaveBeenCalledWith(200);
+ expect(json).toHaveBeenCalledWith({ entry });
+ });
+ });
+
+ describe('verifyAuditLog', () => {
+ it('returns 401 when unauthenticated', async () => {
+ const handlers = createAdminAuditLogHandlers(createDeps());
+ const { req, res, status } = createReqRes({ user: undefined });
+ await handlers.verifyAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(401);
+ });
+
+ it('returns the verification result scoped to the caller tenant', async () => {
+ const verification = mockVerification({ ok: false, brokenAt: 2, reason: 'hash mismatch' });
+ const deps = createDeps({ verifyAuditChain: jest.fn().mockResolvedValue(verification) });
+ const handlers = createAdminAuditLogHandlers(deps);
+ const { req, res, status, json } = createReqRes({
+ user: { _id: new Types.ObjectId(), role: 'admin', tenantId: 'real-tenant' },
+ });
+ await handlers.verifyAuditLog(req, res);
+ expect((deps.verifyAuditChain as jest.Mock).mock.calls[0][0]).toBe('real-tenant');
+ expect(status).toHaveBeenCalledWith(200);
+ expect(json).toHaveBeenCalledWith(verification);
+ });
+
+ it('returns 500 when verification throws', async () => {
+ const deps = createDeps({
+ verifyAuditChain: jest.fn().mockRejectedValue(new Error('boom')),
+ });
+ const handlers = createAdminAuditLogHandlers(deps);
+ const { req, res, status } = createReqRes();
+ await handlers.verifyAuditLog(req, res);
+ expect(status).toHaveBeenCalledWith(500);
+ });
+ });
+
+ describe('exportAuditLogCsv', () => {
+ function streamFrom(entries: AdminAuditLogEntry[]): AdminAuditLogDeps['streamAuditLogEntries'] {
+ return jest.fn(async (_tenantId, _filters, onEntry, options) => {
+ let count = 0;
+ for (const entry of entries) {
+ if (options?.isCancelled?.()) break;
+ await onEntry(entry);
+ count++;
+ }
+ return { count, truncated: false };
+ });
+ }
+
+ it('returns 401 when unauthenticated', async () => {
+ const ctx = createCsvContext({ user: undefined });
+ const handlers = createAdminAuditLogHandlers(createDeps());
+ await handlers.exportAuditLogCsv(ctx.req, ctx.res);
+ expect(ctx.res.status as jest.Mock).toHaveBeenCalledWith(401);
+ });
+
+ it('writes a BOM, header row, and CRLF line endings', async () => {
+ const deps = createDeps({ streamAuditLogEntries: streamFrom([mockEntry()]) });
+ const handlers = createAdminAuditLogHandlers(deps);
+ const ctx = createCsvContext();
+ await handlers.exportAuditLogCsv(ctx.req, ctx.res);
+ expect(ctx.chunks[0]).toBe('');
+ expect(ctx.chunks[1]).toContain('Timestamp');
+ expect(ctx.chunks[1]).toContain('Hash');
+ expect(ctx.chunks[2]).toBe('\r\n');
+ expect(ctx.endCalled()).toBe(true);
+ });
+
+ it('defangs formula-injection cells and quotes special characters', async () => {
+ const entry = mockEntry({
+ actor: { type: 'user', id: 'x', name: '=cmd()' },
+ target: { type: 'role', id: 'r', name: 'Ops, North' },
+ });
+ const deps = createDeps({ streamAuditLogEntries: streamFrom([entry]) });
+ const handlers = createAdminAuditLogHandlers(deps);
+ const ctx = createCsvContext();
+ await handlers.exportAuditLogCsv(ctx.req, ctx.res);
+ const body = ctx.chunks.join('');
+ expect(body).toContain("'=cmd()");
+ expect(body).toContain('"Ops, North"');
+ });
+
+ it('threads cancellation and a row cap into the stream', async () => {
+ const deps = createDeps();
+ const handlers = createAdminAuditLogHandlers(deps);
+ const ctx = createCsvContext();
+ const promise = handlers.exportAuditLogCsv(ctx.req, ctx.res);
+ ctx.emitClose();
+ await promise;
+ const streamMock = deps.streamAuditLogEntries as jest.Mock;
+ const optionsArg = streamMock.mock.calls[0][3];
+ expect(optionsArg.isCancelled()).toBe(true);
+ expect(optionsArg.maxRows).toBeGreaterThan(0);
+ });
+
+ it('returns 400 on malformed filters before streaming', async () => {
+ const deps = createDeps();
+ const handlers = createAdminAuditLogHandlers(deps);
+ const ctx = createCsvContext({ query: { from: 'garbage' } });
+ await handlers.exportAuditLogCsv(ctx.req, ctx.res);
+ expect(ctx.res.status as jest.Mock).toHaveBeenCalledWith(400);
+ expect(deps.streamAuditLogEntries).not.toHaveBeenCalled();
+ });
+
+ it('appends an explicit marker when the export is truncated', async () => {
+ const deps = createDeps({
+ streamAuditLogEntries: jest
+ .fn()
+ .mockResolvedValue({ count: MAX_AUDIT_EXPORT_ROWS, truncated: true }),
+ });
+ const handlers = createAdminAuditLogHandlers(deps);
+ const ctx = createCsvContext();
+ await handlers.exportAuditLogCsv(ctx.req, ctx.res);
+ expect(ctx.chunks.join('')).toContain('TRUNCATED');
+ expect(ctx.endCalled()).toBe(true);
+ });
+
+ it('does not mark an exact-cap export as truncated', async () => {
+ const deps = createDeps({
+ streamAuditLogEntries: jest
+ .fn()
+ .mockResolvedValue({ count: MAX_AUDIT_EXPORT_ROWS, truncated: false }),
+ });
+ const handlers = createAdminAuditLogHandlers(deps);
+ const ctx = createCsvContext();
+ await handlers.exportAuditLogCsv(ctx.req, ctx.res);
+ expect(ctx.chunks.join('')).not.toContain('TRUNCATED');
+ expect(ctx.endCalled()).toBe(true);
+ });
+ });
+});
diff --git a/packages/api/src/admin/auditLog.ts b/packages/api/src/admin/auditLog.ts
new file mode 100644
index 0000000000..6b21e02f78
--- /dev/null
+++ b/packages/api/src/admin/auditLog.ts
@@ -0,0 +1,439 @@
+import {
+ logger,
+ AUDIT_ACTIONS,
+ AUDIT_CATEGORIES,
+ AUDIT_OUTCOMES,
+ AUDIT_SEVERITIES,
+ AUDIT_ACTOR_TYPES,
+ MAX_AUDIT_EXPORT_ROWS,
+ MAX_AUDIT_LOG_LIMIT,
+} from '@librechat/data-schemas';
+import type {
+ AdminAuditLogEntry,
+ AuditAction,
+ AuditActorType,
+ AuditCategory,
+ AuditChainVerification,
+ AuditLogFilters,
+ AuditLogPage,
+ AuditOutcome,
+ AuditSeverity,
+} from '@librechat/data-schemas';
+import type { Response } from 'express';
+import type { ServerRequest } from '~/types/http';
+
+const FORMULA_PREFIX = /^[=+\-@\t\r]/;
+/** UTF-8 BOM, written first so Excel recognizes the encoding on import. Spelled
+ * as a Unicode escape so readers can see the constant in editors that hide the
+ * zero-width glyph. */
+const CSV_BOM = '';
+
+const VALID_ACTIONS = new Set<string>(AUDIT_ACTIONS);
+const VALID_CATEGORIES = new Set<string>(AUDIT_CATEGORIES);
+const VALID_OUTCOMES = new Set<string>(AUDIT_OUTCOMES);
+const VALID_SEVERITIES = new Set<string>(AUDIT_SEVERITIES);
+const VALID_ACTOR_TYPES = new Set<string>(AUDIT_ACTOR_TYPES);
+
+/**
+ * Accepts `YYYY-MM-DD` (interpreted as UTC by the downstream Date parse) or a
+ * full ISO 8601 / RFC 3339 timestamp that includes either `Z` or a `±HH:MM`
+ * offset. Local-time strings without a zone are rejected so every input maps to
+ * an unambiguous instant.
+ */
+const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2}))?$/;
+const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
+const OBJECT_ID_RE = /^[a-fA-F0-9]{24}$/;
+
+export interface AdminAuditLogDeps {
+ listAuditLogPage: (
+ tenantId: string | undefined,
+ filters: AuditLogFilters,
+ ) => Promise<AuditLogPage>;
+ findAuditLogEntry: (
+ tenantId: string | undefined,
+ id: string,
+ ) => Promise<AdminAuditLogEntry | null>;
+ streamAuditLogEntries: (
+ tenantId: string | undefined,
+ filters: Omit<AuditLogFilters, 'offset' | 'limit' | 'cursor'>,
+ onEntry: (entry: AdminAuditLogEntry) => void | Promise<void>,
+ options?: { isCancelled?: () => boolean; maxRows?: number },
+ ) => Promise<{ count: number; truncated: boolean }>;
+ verifyAuditChain: (tenantId: string | undefined) => Promise<AuditChainVerification>;
+}
+
+interface CallerContext {
+ userId: string;
+ role: string;
+ tenantId?: string;
+}
+
+function resolveCaller(req: ServerRequest): CallerContext | null {
+ const user = req.user;
+ if (!user) return null;
+ const userId = user._id?.toString() ?? user.id;
+ if (!userId || !user.role) return null;
+ return { userId, role: user.role, tenantId: user.tenantId };
+}
+
+function asStringArray(v: unknown): string[] | undefined {
+ if (v == null) return undefined;
+ if (Array.isArray(v)) return v.filter((x): x is string => typeof x === 'string');
+ if (typeof v === 'string') return [v];
+ return undefined;
+}
+
+type ParseResult<T> = { ok: true; value: T } | { ok: false; error: string };
+
+/** Parses a repeatable enum filter (`?action=a&action=b`) against a whitelist. */
+function parseEnumArray<T extends string>(
+ raw: unknown,
+ valid: Set<string>,
+ label: string,
+): ParseResult<T[] | undefined> {
+ const arr = asStringArray(raw);
+ if (!arr || arr.length === 0) return { ok: true, value: undefined };
+ const invalid = arr.find((a) => !valid.has(a));
+ if (invalid != null) return { ok: false, error: `Unknown ${label}: ${invalid}` };
+ return { ok: true, value: arr as T[] };
+}
+
+function parseEnum<T extends string>(
+ raw: unknown,
+ valid: Set<string>,
+ label: string,
+): ParseResult<T | undefined> {
+ if (raw == null || raw === '') return { ok: true, value: undefined };
+ if (typeof raw !== 'string') return { ok: false, error: `${label} must be a string` };
+ if (!valid.has(raw)) return { ok: false, error: `Unknown ${label}: ${raw}` };
+ return { ok: true, value: raw as T };
+}
+
+/**
+ * Parses a filter date. `boundary` controls how a bare `YYYY-MM-DD` is widened:
+ * `start` leaves it at 00:00:00.000Z (default for `from`), `end` snaps it to
+ * 23:59:59.999Z so `to=2025-01-15` includes everything on January 15 instead of
+ * cutting off at midnight. Full ISO timestamps are honored exactly.
+ */
+function parseIsoDate(
+ raw: unknown,
+ boundary: 'start' | 'end' = 'start',
+): ParseResult<Date | undefined> {
+ if (raw == null || raw === '') return { ok: true, value: undefined };
+ if (typeof raw !== 'string') return { ok: false, error: 'Date must be a string' };
+ if (!ISO_DATE_RE.test(raw)) return { ok: false, error: 'Date must be ISO 8601' };
+ const d = new Date(raw);
+ if (Number.isNaN(d.getTime())) return { ok: false, error: 'Invalid date' };
+ /**
+ * `new Date('2025-02-31')` (and the timestamp form `2025-02-31T00:00:00Z`)
+ * silently normalizes to March 3 rather than throwing. Validate the literal
+ * calendar tokens — independent of any time/zone, so legitimate offset shifts
+ * are unaffected — so an out-of-range day is rejected instead of quietly
+ * shifting the queried window.
+ */
+ const [year, month, day] = raw.slice(0, 10).split('-').map(Number);
+ const lastDayOfMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
+ if (month < 1 || month > 12 || day < 1 || day > lastDayOfMonth) {
+ return { ok: false, error: 'Invalid date' };
+ }
+ if (boundary === 'end' && DATE_ONLY_RE.test(raw)) {
+ d.setUTCHours(23, 59, 59, 999);
+ }
+ return { ok: true, value: d };
+}
+
+function parseIntInRange(
+ raw: unknown,
+ label: string,
+ min: number,
+ max?: number,
+): ParseResult<number | undefined> {
+ if (raw == null || raw === '') return { ok: true, value: undefined };
+ const n = typeof raw === 'number' ? raw : Number.parseInt(String(raw), 10);
+ if (!Number.isFinite(n)) return { ok: false, error: `${label} must be a number` };
+ if (n < min) return { ok: false, error: `${label} must be >= ${min}` };
+ if (max != null && n > max) return { ok: false, error: `${label} must be <= ${max}` };
+ return { ok: true, value: Math.floor(n) };
+}
+
+function pickString(raw: unknown, maxLen = 256): string | undefined {
+ if (typeof raw !== 'string') return undefined;
+ const trimmed = raw.trim();
+ if (!trimmed) return undefined;
+ return trimmed.slice(0, maxLen);
+}
+
+function escapeCsvCell(value: string): string {
+ if (value === '') return '';
+ const guarded = FORMULA_PREFIX.test(value) ? `'${value}` : value;
+ if (/[",\n\r]/.test(guarded)) {
+ return `"${guarded.replace(/"/g, '""')}"`;
+ }
+ return guarded;
+}
+
+function stringifyMetaValue(value: unknown): string {
+ if (value == null) return '';
+ if (typeof value === 'string') return value;
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
+ return '';
+}
+
+const CSV_COLUMNS: ReadonlyArray<{ label: string; value: (e: AdminAuditLogEntry) => string }> = [
+ { label: 'Timestamp', value: (e) => e.timestamp },
+ { label: 'Category', value: (e) => e.category },
+ { label: 'Action', value: (e) => e.action },
+ { label: 'Outcome', value: (e) => e.outcome },
+ { label: 'Severity', value: (e) => e.severity },
+ { label: 'Actor type', value: (e) => e.actor.type },
+ { label: 'Actor', value: (e) => e.actor.name },
+ { label: 'Actor ID', value: (e) => e.actor.id ?? '' },
+ { label: 'Target type', value: (e) => e.target.type },
+ { label: 'Target', value: (e) => e.target.name ?? '' },
+ { label: 'Target ID', value: (e) => e.target.id ?? '' },
+ { label: 'Capability', value: (e) => stringifyMetaValue(e.metadata?.capability) },
+ { label: 'Details', value: (e) => (e.metadata ? JSON.stringify(e.metadata) : '') },
+ { label: 'IP', value: (e) => e.context?.ip ?? '' },
+ { label: 'Request ID', value: (e) => e.context?.requestId ?? '' },
+ { label: 'Seq', value: (e) => String(e.integrity.seq) },
+ { label: 'Hash', value: (e) => e.integrity.hash },
+];
+
+function formatCsvHeader(): string {
+ return CSV_COLUMNS.map((c) => escapeCsvCell(c.label)).join(',');
+}
+
+function formatCsvRow(entry: AdminAuditLogEntry): string {
+ return CSV_COLUMNS.map((c) => escapeCsvCell(c.value(entry))).join(',');
+}
+
+type ParsedFilters = Omit<AuditLogFilters, 'offset' | 'limit' | 'cursor'>;
+
+interface AuditLogQuery {
+ search?: string;
+ category?: string | string[];
+ action?: string | string[];
+ outcome?: string | string[];
+ severity?: string | string[];
+ actorType?: string;
+ actorQuery?: string;
+ targetType?: string;
+ targetQuery?: string;
+ capability?: string;
+ from?: string;
+ to?: string;
+ limit?: string;
+ offset?: string;
+ cursor?: string;
+}
+
+function parseFilters(query: AuditLogQuery): ParseResult<ParsedFilters> {
+ const from = parseIsoDate(query.from, 'start');
+ if (!from.ok) return { ok: false, error: `from: ${from.error}` };
+ const to = parseIsoDate(query.to, 'end');
+ if (!to.ok) return { ok: false, error: `to: ${to.error}` };
+ if (from.value && to.value && from.value > to.value) {
+ return { ok: false, error: '`from` must be earlier than `to`' };
+ }
+
+ const category = parseEnumArray<AuditCategory>(query.category, VALID_CATEGORIES, 'category');
+ if (!category.ok) return { ok: false, error: category.error };
+ const action = parseEnumArray<AuditAction>(query.action, VALID_ACTIONS, 'action');
+ if (!action.ok) return { ok: false, error: action.error };
+ const outcome = parseEnumArray<AuditOutcome>(query.outcome, VALID_OUTCOMES, 'outcome');
+ if (!outcome.ok) return { ok: false, error: outcome.error };
+ const severity = parseEnumArray<AuditSeverity>(query.severity, VALID_SEVERITIES, 'severity');
+ if (!severity.ok) return { ok: false, error: severity.error };
+ const actorType = parseEnum<AuditActorType>(query.actorType, VALID_ACTOR_TYPES, 'actorType');
+ if (!actorType.ok) return { ok: false, error: actorType.error };
+
+ return {
+ ok: true,
+ value: {
+ search: pickString(query.search, 200),
+ category: category.value,
+ action: action.value,
+ outcome: outcome.value,
+ severity: severity.value,
+ actorType: actorType.value,
+ actorQuery: pickString(query.actorQuery, 128),
+ targetType: pickString(query.targetType, 128),
+ targetQuery: pickString(query.targetQuery, 128),
+ capability: pickString(query.capability, 256),
+ from: from.value,
+ to: to.value,
+ },
+ };
+}
+
+export function createAdminAuditLogHandlers(deps: AdminAuditLogDeps): {
+ listAuditLog: (req: ServerRequest, res: Response) => Promise<Response>;
+ getAuditLogEntry: (req: ServerRequest, res: Response) => Promise<Response>;
+ verifyAuditLog: (req: ServerRequest, res: Response) => Promise<Response>;
+ exportAuditLogCsv: (req: ServerRequest, res: Response) => Promise<Response | void>;
+} {
+ const { listAuditLogPage, findAuditLogEntry, streamAuditLogEntries, verifyAuditChain } = deps;
+
+ async function listAuditLogHandler(req: ServerRequest, res: Response) {
+ try {
+ const caller = resolveCaller(req);
+ if (!caller) return res.status(401).json({ error: 'Authentication required' });
+
+ const query = req.query as AuditLogQuery;
+ const filters = parseFilters(query);
+ if (!filters.ok) return res.status(400).json({ error: filters.error });
+
+ const limit = parseIntInRange(query.limit, 'limit', 1, MAX_AUDIT_LOG_LIMIT);
+ if (!limit.ok) return res.status(400).json({ error: limit.error });
+ const offset = parseIntInRange(query.offset, 'offset', 0);
+ if (!offset.ok) return res.status(400).json({ error: offset.error });
+ const cursor = parseIntInRange(query.cursor, 'cursor', 1);
+ if (!cursor.ok) return res.status(400).json({ error: cursor.error });
+
+ const page = await listAuditLogPage(caller.tenantId, {
+ ...filters.value,
+ offset: offset.value,
+ limit: limit.value,
+ cursor: cursor.value,
+ });
+
+ return res.status(200).json(page);
+ } catch (err) {
+ logger.error('[adminAuditLog] list error:', err);
+ return res.status(500).json({ error: 'Failed to fetch audit log' });
+ }
+ }
+
+ async function getAuditLogEntryHandler(req: ServerRequest, res: Response) {
+ try {
+ const caller = resolveCaller(req);
+ if (!caller) return res.status(401).json({ error: 'Authentication required' });
+
+ const { id } = req.params as { id?: string };
+ if (!id || !OBJECT_ID_RE.test(id)) {
+ return res.status(400).json({ error: 'Invalid id' });
+ }
+
+ const entry = await findAuditLogEntry(caller.tenantId, id);
+ if (!entry) return res.status(404).json({ error: 'Not found' });
+ return res.status(200).json({ entry });
+ } catch (err) {
+ logger.error('[adminAuditLog] get error:', err);
+ return res.status(500).json({ error: 'Failed to fetch audit log entry' });
+ }
+ }
+
+ async function verifyAuditLogHandler(req: ServerRequest, res: Response) {
+ try {
+ const caller = resolveCaller(req);
+ if (!caller) return res.status(401).json({ error: 'Authentication required' });
+
+ const result = await verifyAuditChain(caller.tenantId);
+ return res.status(200).json(result);
+ } catch (err) {
+ logger.error('[adminAuditLog] verify error:', err);
+ return res.status(500).json({ error: 'Failed to verify audit log integrity' });
+ }
+ }
+
+ async function exportAuditLogCsvHandler(req: ServerRequest, res: Response) {
+ try {
+ const caller = resolveCaller(req);
+ if (!caller) return res.status(401).json({ error: 'Authentication required' });
+
+ const filters = parseFilters(req.query as AuditLogQuery);
+ if (!filters.ok) return res.status(400).json({ error: filters.error });
+
+ const filenameStamp = new Date().toISOString().slice(0, 10);
+ res.setHeader('Content-Type', 'text/csv; charset=utf-8');
+ res.setHeader('Content-Disposition', `attachment; filename="audit-log-${filenameStamp}.csv"`);
+ res.setHeader('Cache-Control', 'no-store');
+
+ /**
+ * The socket-`close` listener is the canonical signal — it fires on client
+ * TCP RST as well as on graceful end. `req.aborted` (deprecated) is kept as
+ * a belt-and-braces fallback for Node versions that emit it before the
+ * response sees `close`.
+ */
+ let clientAborted = false;
+ const markAborted = () => {
+ clientAborted = true;
+ };
+ res.once('close', markAborted);
+ req.once('aborted', markAborted);
+ const isCancelled = () => clientAborted;
+
+ /**
+ * Wait for `drain` when the socket buffer is full so we never queue an
+ * unbounded amount of CSV in Node memory for slow consumers. Race against
+ * `close` so a destroyed socket can't strand the handler on a `drain` that
+ * will never fire.
+ */
+ const writeChunk = (chunk: string): Promise<void> => {
+ if (clientAborted) return Promise.resolve();
+ if (res.write(chunk)) return Promise.resolve();
+ return new Promise<void>((resolve) => {
+ const onDrain = () => {
+ res.removeListener('close', onClose);
+ resolve();
+ };
+ const onClose = () => {
+ res.removeListener('drain', onDrain);
+ resolve();
+ };
+ res.once('drain', onDrain);
+ res.once('close', onClose);
+ });
+ };
+
+ await writeChunk(CSV_BOM);
+ await writeChunk(formatCsvHeader());
+ await writeChunk('\r\n');
+
+ const { truncated } = await streamAuditLogEntries(
+ caller.tenantId,
+ filters.value,
+ async (entry) => {
+ if (clientAborted) return;
+ await writeChunk(formatCsvRow(entry));
+ await writeChunk('\r\n');
+ },
+ { isCancelled, maxRows: MAX_AUDIT_EXPORT_ROWS },
+ );
+
+ res.removeListener('close', markAborted);
+ req.removeListener('aborted', markAborted);
+ if (!clientAborted) {
+ /**
+ * `truncated` is true only when rows existed beyond the cap (an exact-cap
+ * match is reported as complete). Surfacing this is a compliance
+ * requirement — a silently truncated export reads as a complete record.
+ * Emit an explicit trailing marker and log it; callers should narrow the
+ * date range for the full set.
+ */
+ if (truncated) {
+ logger.warn('[adminAuditLog] CSV export truncated at row cap', {
+ maxRows: MAX_AUDIT_EXPORT_ROWS,
+ });
+ await writeChunk(
+ `# TRUNCATED: export capped at ${MAX_AUDIT_EXPORT_ROWS} rows — narrow the from/to range to export the complete set\r\n`,
+ );
+ }
+ res.end();
+ }
+ } catch (err) {
+ logger.error('[adminAuditLog] export error:', err);
+ if (!res.headersSent) {
+ return res.status(500).json({ error: 'Failed to export audit log' });
+ }
+ res.end();
+ }
+ }
+
+ return {
+ listAuditLog: listAuditLogHandler,
+ getAuditLogEntry: getAuditLogEntryHandler,
+ verifyAuditLog: verifyAuditLogHandler,
+ exportAuditLogCsv: exportAuditLogCsvHandler,
+ };
+}
diff --git a/packages/api/src/admin/context.ts b/packages/api/src/admin/context.ts
new file mode 100644
index 0000000000..2ab6710753
--- /dev/null
+++ b/packages/api/src/admin/context.ts
@@ -0,0 +1,21 @@
+import type { AuditContext } from '@librechat/data-schemas';
+import type { ServerRequest } from '~/types/http';
+
+/** Normalizes a possibly-repeated header to its first string value. */
+function firstHeaderValue(value: string | string[] | undefined): string | undefined {
+ if (Array.isArray(value)) return value[0];
+ return typeof value === 'string' ? value : undefined;
+}
+
+/** Extracts forensic request context (IP, user agent, correlation id) for an
+ * audit record. Fields are undefined when the data isn't available. */
+export function buildAuditContext(req: ServerRequest): AuditContext {
+ const headers = req.headers ?? {};
+ const forwarded = firstHeaderValue(headers['x-forwarded-for']);
+ const forwardedIp = forwarded ? forwarded.split(',')[0]?.trim() : undefined;
+ return {
+ ip: req.ip || forwardedIp || req.socket?.remoteAddress || undefined,
+ userAgent: firstHeaderValue(headers['user-agent']),
+ requestId: firstHeaderValue(headers['x-request-id'] ?? headers['x-correlation-id']),
+ };
+}
diff --git a/packages/api/src/admin/grants.spec.ts b/packages/api/src/admin/grants.spec.ts
index cd6d1e8d38..fd22a2c7f3 100644
--- a/packages/api/src/admin/grants.spec.ts
+++ b/packages/api/src/admin/grants.spec.ts
@@ -53,8 +53,8 @@ function createDeps(overrides: Partial<AdminGrantsDeps> = {}): AdminGrantsDeps {
countGrants: jest.fn().mockResolvedValue(0),
getCapabilitiesForPrincipal: jest.fn().mockResolvedValue([]),
getCapabilitiesForPrincipals: jest.fn().mockResolvedValue([]),
- grantCapability: jest.fn().mockResolvedValue(mockGrant()),
- revokeCapability: jest.fn().mockResolvedValue(undefined),
+ grantCapability: jest.fn().mockResolvedValue({ grant: mockGrant(), created: true }),
+ revokeCapability: jest.fn().mockResolvedValue({ deletedCount: 1 }),
getUserPrincipals: jest.fn().mockResolvedValue([
{ principalType: PrincipalType.USER, principalId: new Types.ObjectId() },
{ principalType: PrincipalType.ROLE, principalId: 'admin' },
@@ -599,7 +599,9 @@ describe('createAdminGrantsHandlers', () => {
it('assigns a grant and returns 201', async () => {
const grant = mockGrant();
- const deps = createDeps({ grantCapability: jest.fn().mockResolvedValue(grant) });
+ const deps = createDeps({
+ grantCapability: jest.fn().mockResolvedValue({ grant, created: true }),
+ });
const handlers = createAdminGrantsHandlers(deps);
const { req, res, status, json } = createReqRes({ body: validBody });
@@ -652,7 +654,7 @@ describe('createAdminGrantsHandlers', () => {
capability: 'manage:configs:endpoints' as ISystemGrant['capability'],
});
const deps = createDeps({
- grantCapability: jest.fn().mockResolvedValue(grant),
+ grantCapability: jest.fn().mockResolvedValue({ grant, created: true }),
getHeldCapabilities: jest
.fn()
.mockResolvedValue(
@@ -672,7 +674,7 @@ describe('createAdminGrantsHandlers', () => {
it('accepts config assignment capabilities', async () => {
const grant = mockGrant({ capability: 'assign:configs:group' as ISystemGrant['capability'] });
const deps = createDeps({
- grantCapability: jest.fn().mockResolvedValue(grant),
+ grantCapability: jest.fn().mockResolvedValue({ grant, created: true }),
getHeldCapabilities: jest
.fn()
.mockResolvedValue(new Set([SystemCapabilities.MANAGE_ROLES, 'assign:configs:group'])),
@@ -935,7 +937,7 @@ describe('createAdminGrantsHandlers', () => {
it('returns 500 when grantCapability returns null', async () => {
const deps = createDeps({
- grantCapability: jest.fn().mockResolvedValue(null),
+ grantCapability: jest.fn().mockResolvedValue({ grant: null, created: false }),
});
const handlers = createAdminGrantsHandlers(deps);
const { req, res, status, json } = createReqRes({ body: validBody });
@@ -967,9 +969,11 @@ describe('createAdminGrantsHandlers', () => {
capability: SystemCapabilities.READ_USERS,
};
- it('returns 200 idempotently even if the grant does not exist', async () => {
+ it('returns 200 idempotently and skips audit emission when the grant does not exist', async () => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
const deps = createDeps({
- revokeCapability: jest.fn().mockResolvedValue(undefined),
+ revokeCapability: jest.fn().mockResolvedValue({ deletedCount: 0 }),
+ recordAuditEntry,
});
const handlers = createAdminGrantsHandlers(deps);
const { req, res, status, json } = createReqRes({ params: validParams });
@@ -978,6 +982,9 @@ describe('createAdminGrantsHandlers', () => {
expect(status).toHaveBeenCalledWith(200);
expect(json).toHaveBeenCalledWith({ success: true });
+ /** A no-op revoke must not produce an audit row. The whole point of the
+ * `deletedCount > 0` gate is to avoid logging fictitious revocations. */
+ expect(recordAuditEntry).not.toHaveBeenCalled();
});
it('revokes a grant and returns 200', async () => {
@@ -1165,4 +1172,152 @@ describe('createAdminGrantsHandlers', () => {
expect(json).toHaveBeenCalledWith({ error: 'Failed to revoke grant' });
});
});
+
+ describe('audit emission', () => {
+ const assignBody = {
+ principalType: PrincipalType.ROLE,
+ principalId: 'editor',
+ capability: SystemCapabilities.READ_USERS,
+ };
+
+ function reqUser(overrides: { name?: string; username?: string; email?: string } = {}) {
+ return {
+ _id: new Types.ObjectId(),
+ role: 'admin',
+ tenantId: 'tenant-1',
+ ...overrides,
+ } as { _id: Types.ObjectId; role: string; tenantId?: string };
+ }
+
+ it('emits a grant.assigned entry after a successful assignment', async () => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+ const deps = createDeps({ recordAuditEntry });
+ const handlers = createAdminGrantsHandlers(deps);
+ const user = reqUser({ name: 'Alice Admin' });
+ const { req, res } = createReqRes({ body: assignBody, user });
+
+ await handlers.assignGrant(req, res);
+
+ expect(recordAuditEntry).toHaveBeenCalledTimes(1);
+ expect(recordAuditEntry).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'grant.assigned',
+ outcome: 'success',
+ actor: { type: 'user', id: user._id.toString(), name: 'Alice Admin' },
+ /** ROLE targets carry the human-readable name in `principalId`, so the
+ * audit target id and name are both that role name. */
+ target: { type: PrincipalType.ROLE, id: 'editor', name: 'editor' },
+ metadata: { capability: SystemCapabilities.READ_USERS },
+ tenantId: 'tenant-1',
+ }),
+ );
+ });
+
+ it('emits a grant.removed entry when deletedCount > 0', async () => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+ const deps = createDeps({
+ revokeCapability: jest.fn().mockResolvedValue({ deletedCount: 1 }),
+ recordAuditEntry,
+ });
+ const handlers = createAdminGrantsHandlers(deps);
+ const user = reqUser({ username: 'alice' });
+ const { req, res } = createReqRes({ params: assignBody, user });
+
+ await handlers.revokeGrant(req, res);
+
+ expect(recordAuditEntry).toHaveBeenCalledTimes(1);
+ expect(recordAuditEntry).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'grant.removed',
+ actor: expect.objectContaining({ type: 'user', name: 'alice' }),
+ target: { type: PrincipalType.ROLE, id: 'editor', name: 'editor' },
+ }),
+ );
+ });
+
+ it('does not emit when recordAuditEntry is not configured', async () => {
+ const deps = createDeps();
+ const handlers = createAdminGrantsHandlers(deps);
+ const { req, res, status } = createReqRes({ body: assignBody, user: reqUser() });
+
+ await handlers.assignGrant(req, res);
+
+ expect(status).toHaveBeenCalledWith(201);
+ });
+
+ it('does not audit re-assigning a capability the role already holds', async () => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+ const deps = createDeps({
+ recordAuditEntry,
+ // the upsert reports created:false → idempotent re-assert, no change
+ grantCapability: jest.fn().mockResolvedValue({ grant: mockGrant(), created: false }),
+ });
+ const handlers = createAdminGrantsHandlers(deps);
+ const { req, res, status } = createReqRes({ body: assignBody, user: reqUser() });
+
+ await handlers.assignGrant(req, res);
+
+ expect(status).toHaveBeenCalledWith(201);
+ expect(recordAuditEntry).not.toHaveBeenCalled();
+ });
+
+ it('fail-open: a failed audit write does not fail the grant', async () => {
+ const recordAuditEntry = jest.fn().mockRejectedValue(new Error('audit down'));
+ const deps = createDeps({ recordAuditEntry });
+ const handlers = createAdminGrantsHandlers(deps);
+ const { req, res, status } = createReqRes({ body: assignBody, user: reqUser() });
+
+ await handlers.assignGrant(req, res);
+
+ expect(status).toHaveBeenCalledWith(201);
+ });
+
+ it('fail-closed: a failed assign audit rolls back the grant and 500s', async () => {
+ const recordAuditEntry = jest.fn().mockRejectedValue(new Error('audit down'));
+ const deps = createDeps({ recordAuditEntry, auditFailClosed: true });
+ const handlers = createAdminGrantsHandlers(deps);
+ const { req, res, status } = createReqRes({ body: assignBody, user: reqUser() });
+
+ await handlers.assignGrant(req, res);
+
+ expect(recordAuditEntry).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ failClosed: true }),
+ );
+ // compensating rollback removes the grant we just created
+ expect(deps.revokeCapability).toHaveBeenCalledWith(
+ expect.objectContaining({
+ principalType: PrincipalType.ROLE,
+ principalId: 'editor',
+ capability: SystemCapabilities.READ_USERS,
+ }),
+ );
+ expect(status).toHaveBeenCalledWith(500);
+ });
+
+ it('fail-closed: a failed revoke audit restores the grant and 500s', async () => {
+ const recordAuditEntry = jest.fn().mockRejectedValue(new Error('audit down'));
+ const grantCapability = jest.fn().mockResolvedValue({ grant: { id: 'g1' }, created: true });
+ const deps = createDeps({
+ recordAuditEntry,
+ auditFailClosed: true,
+ grantCapability,
+ revokeCapability: jest.fn().mockResolvedValue({ deletedCount: 1 }),
+ });
+ const handlers = createAdminGrantsHandlers(deps);
+ const { req, res, status } = createReqRes({ params: assignBody, user: reqUser() });
+
+ await handlers.revokeGrant(req, res);
+
+ // compensating re-grant restores access removed before the audit failed
+ expect(grantCapability).toHaveBeenCalledWith(
+ expect.objectContaining({
+ principalType: PrincipalType.ROLE,
+ principalId: 'editor',
+ capability: SystemCapabilities.READ_USERS,
+ }),
+ );
+ expect(status).toHaveBeenCalledWith(500);
+ });
+ });
});
diff --git a/packages/api/src/admin/grants.ts b/packages/api/src/admin/grants.ts
index f5d42ce071..bba4495cfb 100644
--- a/packages/api/src/admin/grants.ts
+++ b/packages/api/src/admin/grants.ts
@@ -5,12 +5,20 @@ import {
SystemCapabilities,
expandImplications,
} from '@librechat/data-schemas';
-import type { ISystemGrant, SystemCapability } from '@librechat/data-schemas';
+import type {
+ AuditAction,
+ AuditContext,
+ ISystemGrant,
+ RecordAuditEntryInput,
+ RecordAuditEntryOptions,
+ SystemCapability,
+} from '@librechat/data-schemas';
import type { Response } from 'express';
import type { Types } from 'mongoose';
import type { ResolvedPrincipal } from '~/types/principal';
import type { ServerRequest } from '~/types/http';
import { parsePagination } from './pagination';
+import { buildAuditContext } from './context';
interface GrantRequestBody {
principalType?: string;
@@ -44,13 +52,13 @@ export interface AdminGrantsDeps {
capability: SystemCapability;
tenantId?: string;
grantedBy?: string | Types.ObjectId;
- }) => Promise<ISystemGrant | null>;
+ }) => Promise<{ grant: ISystemGrant | null; created: boolean }>;
revokeCapability: (params: {
principalType: PrincipalType;
principalId: string | Types.ObjectId;
capability: SystemCapability;
tenantId?: string;
- }) => Promise<void>;
+ }) => Promise<{ deletedCount: number }>;
getUserPrincipals: (params: {
userId: string;
role?: string | null;
@@ -72,6 +80,19 @@ export interface AdminGrantsDeps {
tenantId?: string;
}) => ResolvedPrincipal[] | undefined;
checkRoleExists?: (roleId: string) => Promise<boolean>;
+ /** Optional audit emission. Failure is logged but does not roll back the grant
+ * unless `auditFailClosed` is set. */
+ recordAuditEntry?: (
+ input: RecordAuditEntryInput,
+ options?: RecordAuditEntryOptions,
+ ) => Promise<void>;
+ /**
+ * When true, a failed audit write surfaces as a 5xx instead of being
+ * swallowed. The grant itself is already persisted (and grant writes are
+ * idempotent upserts), so a client retry is safe; an operator must reconcile
+ * the missing audit row. Defaults to fail-open.
+ */
+ auditFailClosed?: boolean;
}
/** Currently ROLE-only; Record/Set structure preserved for future principal-type expansion. */
@@ -97,8 +118,46 @@ export function createAdminGrantsHandlers(deps: AdminGrantsDeps): {
getHeldCapabilities,
getCachedPrincipals,
checkRoleExists,
+ recordAuditEntry,
+ auditFailClosed,
} = deps;
+ async function emitAudit(args: {
+ action: AuditAction;
+ caller: { userId: string; actorName: string; role: string; tenantId?: string };
+ principalType: PrincipalType;
+ principalId: string;
+ capability: SystemCapability;
+ context?: AuditContext;
+ }): Promise<void> {
+ if (!recordAuditEntry) return;
+ /** The grants surface is ROLE-only today (see `MANAGE_CAPABILITY_BY_TYPE`),
+ * and SystemGrant stores the human-readable role name in `principalId` for
+ * ROLE principals, so the audit target's id and name are both `principalId`.
+ * When USER and GROUP grants are enabled, resolve the display name here. */
+ const input: RecordAuditEntryInput = {
+ action: args.action,
+ outcome: 'success',
+ severity: 'warning',
+ actor: { type: 'user', id: args.caller.userId, name: args.caller.actorName },
+ target: { type: args.principalType, id: args.principalId, name: args.principalId },
+ metadata: { capability: args.capability },
+ context: args.context,
+ tenantId: args.caller.tenantId,
+ };
+ if (auditFailClosed) {
+ /** Let the failure propagate to the handler (→ 5xx); see `auditFailClosed`. */
+ await recordAuditEntry(input, { failClosed: true });
+ return;
+ }
+ try {
+ await recordAuditEntry(input);
+ } catch (err) {
+ /** Fail-open: audit failure must not roll back the grant. */
+ logger.error('[adminGrants] audit write failed', err);
+ }
+ }
+
const MANAGE_CAPABILITY_BY_TYPE: Record<GrantPrincipalType, SystemCapability> = {
[PrincipalType.ROLE]: SystemCapabilities.MANAGE_ROLES,
};
@@ -113,7 +172,7 @@ export function createAdminGrantsHandlers(deps: AdminGrantsDeps): {
function resolveUser(
req: ServerRequest,
- ): { userId: string; role: string; tenantId?: string } | null {
+ ): { userId: string; role: string; actorName: string; tenantId?: string } | null {
const user = req.user;
if (!user) {
return null;
@@ -122,7 +181,10 @@ export function createAdminGrantsHandlers(deps: AdminGrantsDeps): {
if (!userId || !user.role) {
return null;
}
- return { userId, role: user.role, tenantId: user.tenantId };
+ /** JWT-loaded `req.user` already carries name/username/email, so the actor
+ * display name is available without a database round-trip. */
+ const actorName = user.name || user.username || user.email || userId;
+ return { userId, role: user.role, actorName, tenantId: user.tenantId };
}
async function resolvePrincipals(user: {
@@ -342,7 +404,11 @@ export function createAdminGrantsHandlers(deps: AdminGrantsDeps): {
}
}
- const grant = await grantCapability({
+ /** `created` comes from the atomic upsert result, so a re-assert of a
+ * capability the role already holds (or a concurrent double-assign) is not
+ * audited as a new change — and a new tenant-scoped grant is correctly
+ * distinguished from an inherited platform-level one. */
+ const { grant, created } = await grantCapability({
principalType,
principalId,
capability,
@@ -352,6 +418,29 @@ export function createAdminGrantsHandlers(deps: AdminGrantsDeps): {
if (!grant) {
return res.status(500).json({ error: 'Grant operation returned no result' });
}
+ if (created) {
+ try {
+ await emitAudit({
+ action: 'grant.assigned',
+ caller,
+ principalType,
+ principalId,
+ capability,
+ context: buildAuditContext(req),
+ });
+ } catch (auditErr) {
+ /** Fail-closed only (emitAudit rethrows here): roll back the grant we
+ * just created so a 5xx never leaves an unaudited grant in place. */
+ await revokeCapability({ principalType, principalId, capability, tenantId }).catch((e) =>
+ logger.error('[adminGrants] compensating revoke after audit failure failed', e),
+ );
+ logger.error(
+ '[adminGrants] assignGrant audit failed (fail-closed) — rolled back grant',
+ auditErr,
+ );
+ return res.status(500).json({ error: 'Failed to record audit entry' });
+ }
+ }
return res.status(201).json({ grant });
} catch (error) {
logger.error('[adminGrants] assignGrant error:', error);
@@ -392,12 +481,46 @@ export function createAdminGrantsHandlers(deps: AdminGrantsDeps): {
return res.status(403).json({ error: 'Insufficient permissions' });
}
- await revokeCapability({
+ const revokeResult = await revokeCapability({
principalType: principalType as PrincipalType,
principalId,
capability: capability as SystemCapability,
tenantId,
});
+ // Only emit the audit entry when a grant document was actually deleted —
+ // a no-op revoke (the grant never existed) must not appear in the audit
+ // trail or the forensic record becomes misleading.
+ if (revokeResult.deletedCount > 0) {
+ try {
+ await emitAudit({
+ action: 'grant.removed',
+ caller,
+ principalType: principalType as PrincipalType,
+ principalId,
+ capability: capability as SystemCapability,
+ context: buildAuditContext(req),
+ });
+ } catch (auditErr) {
+ /** Fail-closed only (emitAudit rethrows here): restore the grant we
+ * just removed so a 5xx never leaves an unaudited revoke. The original
+ * `grantedBy`/`grantedAt` are not recoverable here; restoring access is
+ * the priority on this rare error path. */
+ await grantCapability({
+ principalType: principalType as PrincipalType,
+ principalId,
+ capability: capability as SystemCapability,
+ tenantId,
+ grantedBy: caller.userId,
+ }).catch((e) =>
+ logger.error('[adminGrants] compensating re-grant after audit failure failed', e),
+ );
+ logger.error(
+ '[adminGrants] revokeGrant audit failed (fail-closed) — restored grant',
+ auditErr,
+ );
+ return res.status(500).json({ error: 'Failed to record audit entry' });
+ }
+ }
return res.status(200).json({ success: true });
} catch (error) {
logger.error('[adminGrants] revokeGrant error:', error);
diff --git a/packages/api/src/admin/index.ts b/packages/api/src/admin/index.ts
index 90f826d7bf..52f0d68e71 100644
--- a/packages/api/src/admin/index.ts
+++ b/packages/api/src/admin/index.ts
@@ -4,9 +4,11 @@ export { createAdminGroupsHandlers } from './groups';
export { createAdminRolesHandlers } from './roles';
export { createAdminSkillsSyncAccess, createAdminSkillsSyncHandlers } from './skills';
export { createAdminUsersHandlers } from './users';
+export { createAdminAuditLogHandlers } from './auditLog';
export type { AdminConfigDeps } from './config';
export type { AdminGrantsDeps, GrantPrincipalType } from './grants';
export type { AdminGroupsDeps } from './groups';
export type { AdminRolesDeps } from './roles';
export type { AdminSkillSyncAccessDeps, AdminSkillSyncDeps } from './skills';
export type { AdminUsersDeps } from './users';
+export type { AdminAuditLogDeps } from './auditLog';
diff --git a/packages/api/src/admin/roles.spec.ts b/packages/api/src/admin/roles.spec.ts
index edbd14ba0b..dc96975b41 100644
--- a/packages/api/src/admin/roles.spec.ts
+++ b/packages/api/src/admin/roles.spec.ts
@@ -75,7 +75,7 @@ function createDeps(overrides: Partial<AdminRolesDeps> = {}): AdminRolesDeps {
countUsersByRole: jest.fn().mockResolvedValue(0),
deleteConfig: jest.fn().mockResolvedValue(null),
deleteAclEntries: jest.fn().mockResolvedValue(undefined),
- deleteGrantsForPrincipal: jest.fn().mockResolvedValue(undefined),
+ deleteGrantsForPrincipal: jest.fn().mockResolvedValue([]),
...overrides,
};
}
@@ -990,6 +990,84 @@ describe('createAdminRolesHandlers', () => {
expect(json).toHaveBeenCalledWith({ success: true });
});
+ it('emits a grant.removed audit entry for each grant removed by the cascade', async () => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+ const deps = createDeps({
+ deleteGrantsForPrincipal: jest.fn().mockResolvedValue([
+ { capability: 'manage:users', tenantId: 'tenant-1' },
+ { capability: 'read:users', tenantId: 'tenant-1' },
+ ]),
+ recordAuditEntry,
+ });
+ const handlers = createAdminRolesHandlers(deps);
+ const userId = new Types.ObjectId();
+ const { req, res, status } = createReqRes({
+ params: { name: 'editor' },
+ user: { _id: userId, role: 'admin', tenantId: 'tenant-1' },
+ });
+
+ await handlers.deleteRole(req, res);
+
+ expect(status).toHaveBeenCalledWith(200);
+ expect(recordAuditEntry).toHaveBeenCalledTimes(2);
+ expect(recordAuditEntry).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'grant.removed',
+ actor: expect.objectContaining({ type: 'user', id: userId.toString() }),
+ target: { type: PrincipalType.ROLE, id: 'editor', name: 'editor' },
+ metadata: { capability: 'manage:users' },
+ tenantId: 'tenant-1',
+ }),
+ );
+ });
+
+ it('scopes each cascade audit entry to the removed grant’s own tenant', async () => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+ const deps = createDeps({
+ // a platform admin (no tenantId) deletes a role holding both a
+ // platform-level grant and a tenant-scoped one
+ deleteGrantsForPrincipal: jest
+ .fn()
+ .mockResolvedValue([
+ { capability: 'read:users' },
+ { capability: 'manage:users', tenantId: 'tenant-x' },
+ ]),
+ recordAuditEntry,
+ });
+ const handlers = createAdminRolesHandlers(deps);
+ const { req, res, status } = createReqRes({
+ params: { name: 'editor' },
+ user: { _id: new Types.ObjectId(), role: 'admin' },
+ });
+
+ await handlers.deleteRole(req, res);
+
+ expect(status).toHaveBeenCalledWith(200);
+ // platform grant → platform chain (tenantId undefined)
+ expect(recordAuditEntry).toHaveBeenCalledWith(
+ expect.objectContaining({ metadata: { capability: 'read:users' }, tenantId: undefined }),
+ );
+ // tenant grant → that tenant's chain, not the caller's (undefined) scope
+ expect(recordAuditEntry).toHaveBeenCalledWith(
+ expect.objectContaining({ metadata: { capability: 'manage:users' }, tenantId: 'tenant-x' }),
+ );
+ });
+
+ it('does not audit when the deleted role had no grants', async () => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+ const deps = createDeps({ recordAuditEntry });
+ const handlers = createAdminRolesHandlers(deps);
+ const { req, res, status } = createReqRes({
+ params: { name: 'editor' },
+ user: { _id: new Types.ObjectId(), role: 'admin' },
+ });
+
+ await handlers.deleteRole(req, res);
+
+ expect(status).toHaveBeenCalledWith(200);
+ expect(recordAuditEntry).not.toHaveBeenCalled();
+ });
+
it('succeeds even when all cascade operations fail', async () => {
const deps = createDeps({
deleteConfig: jest.fn().mockRejectedValue(new Error('config cleanup failed')),
diff --git a/packages/api/src/admin/roles.ts b/packages/api/src/admin/roles.ts
index 910e962a5c..484e1efe2f 100644
--- a/packages/api/src/admin/roles.ts
+++ b/packages/api/src/admin/roles.ts
@@ -1,10 +1,19 @@
import { PrincipalType, SystemRoles } from 'librechat-data-provider';
import { logger, isValidObjectIdString, RoleConflictError } from '@librechat/data-schemas';
-import type { IRole, IUser, IConfig, AdminMember } from '@librechat/data-schemas';
+import type {
+ IRole,
+ IUser,
+ IConfig,
+ AdminMember,
+ ISystemGrant,
+ RecordAuditEntryInput,
+ RecordAuditEntryOptions,
+} from '@librechat/data-schemas';
import type { FilterQuery, Types } from 'mongoose';
import type { Response } from 'express';
import type { ServerRequest } from '~/types/http';
import { parsePagination } from './pagination';
+import { buildAuditContext } from './context';
const systemRoleValues = new Set<string>(Object.values(SystemRoles));
@@ -115,11 +124,18 @@ export interface AdminRolesDeps {
principalType: PrincipalType;
principalId: string | Types.ObjectId;
}) => Promise<void>;
- /** Removes all system capability grants held by this principal. */
+ /** Removes all system capability grants held by this principal and returns
+ * the removed grants so each can be audited. */
deleteGrantsForPrincipal: (
principalType: PrincipalType,
principalId: string | Types.ObjectId,
options?: { tenantId?: string },
+ ) => Promise<ISystemGrant[]>;
+ /** Optional audit emission for grants removed by the role-deletion cascade.
+ * Failure is logged but never blocks the deletion (which has already happened). */
+ recordAuditEntry?: (
+ input: RecordAuditEntryInput,
+ options?: RecordAuditEntryOptions,
) => Promise<void>;
}
@@ -152,8 +168,45 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
deleteConfig,
deleteAclEntries,
deleteGrantsForPrincipal,
+ recordAuditEntry,
} = deps;
+ /** Emits a `grant.removed` audit entry for each grant the role-deletion cascade
+ * removed, so the cascade leaves the same forensic trail as an explicit revoke.
+ * Fail-open: the role is already deleted, so a failed audit is logged, not
+ * propagated. Sequential to keep the per-tenant hash chain ordered. */
+ async function emitGrantRemovals(
+ req: ServerRequest,
+ roleName: string,
+ grants: ISystemGrant[],
+ ): Promise<void> {
+ if (!recordAuditEntry || grants.length === 0) return;
+ const user = req.user;
+ const userId = user?._id?.toString() ?? user?.id;
+ if (!user || !userId) return;
+ const actorName = user.name || user.username || user.email || userId;
+ const context = buildAuditContext(req);
+ for (const grant of grants) {
+ try {
+ await recordAuditEntry({
+ action: 'grant.removed',
+ outcome: 'success',
+ severity: 'warning',
+ actor: { type: 'user', id: userId, name: actorName },
+ target: { type: PrincipalType.ROLE, id: roleName, name: roleName },
+ metadata: { capability: grant.capability },
+ context,
+ /** Scope each entry to the removed grant's own tenant — a platform
+ * admin's role deletion can remove tenant-scoped grants, and those
+ * removals must land in the affected tenant's chain, not the caller's. */
+ tenantId: grant.tenantId,
+ });
+ } catch (err) {
+ logger.error('[adminRoles] grant.removed audit failed during role deletion', err);
+ }
+ }
+ }
+
async function listRolesHandler(req: ServerRequest, res: Response) {
try {
const { limit, offset } = parsePagination(req.query);
@@ -398,16 +451,19 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
}
const tenantId = req.user?.tenantId;
- const cleanupResults = await Promise.allSettled([
+ const [configResult, aclResult, grantsResult] = await Promise.allSettled([
deleteConfig(PrincipalType.ROLE, name),
deleteAclEntries({ principalType: PrincipalType.ROLE, principalId: name }),
deleteGrantsForPrincipal(PrincipalType.ROLE, name, { tenantId }),
]);
- for (const result of cleanupResults) {
+ for (const result of [configResult, aclResult, grantsResult]) {
if (result.status === 'rejected') {
logger.error('[adminRoles] cascade cleanup failed for role:', name, result.reason);
}
}
+ if (grantsResult.status === 'fulfilled') {
+ await emitGrantRemovals(req, name, grantsResult.value);
+ }
return res.status(200).json({ success: true });
} catch (error) {
diff --git a/packages/data-schemas/package.json b/packages/data-schemas/package.json
index a3c76db9a9..90f05b1fa4 100644
--- a/packages/data-schemas/package.json
+++ b/packages/data-schemas/package.json
@@ -1,6 +1,6 @@
{
"name": "@librechat/data-schemas",
- "version": "0.0.53",
+ "version": "0.0.54",
"description": "Mongoose schemas and models for LibreChat",
"type": "module",
"main": "dist/index.cjs",
diff --git a/packages/data-schemas/src/admin/capabilities.ts b/packages/data-schemas/src/admin/capabilities.ts
index 7a966c0062..33a6c2ecf9 100644
--- a/packages/data-schemas/src/admin/capabilities.ts
+++ b/packages/data-schemas/src/admin/capabilities.ts
@@ -42,6 +42,12 @@ export const SystemCapabilities = {
/** Reserved — not yet enforced by any middleware. */
READ_ASSISTANTS: 'read:assistants',
MANAGE_ASSISTANTS: 'manage:assistants',
+ /**
+ * Required to list, view, and CSV-export the SystemGrant audit log. Append-only
+ * by design, so there is no MANAGE counterpart — modifying historical entries
+ * would defeat the forensic guarantee.
+ */
+ READ_AUDIT_LOG: 'read:audit_log',
} as const;
/**
@@ -224,6 +230,10 @@ export const CAPABILITY_CATEGORIES: CapabilityCategory[] = [
{
key: 'system',
labelKey: 'com_cap_cat_system',
- capabilities: [SystemCapabilities.ACCESS_ADMIN, SystemCapabilities.READ_USAGE],
+ capabilities: [
+ SystemCapabilities.ACCESS_ADMIN,
+ SystemCapabilities.READ_USAGE,
+ SystemCapabilities.READ_AUDIT_LOG,
+ ],
},
];
diff --git a/packages/data-schemas/src/index.ts b/packages/data-schemas/src/index.ts
index 3d99b90675..e35c29e2e3 100644
--- a/packages/data-schemas/src/index.ts
+++ b/packages/data-schemas/src/index.ts
@@ -24,9 +24,21 @@ export {
validateSkillFrontmatter,
validateSkillDescription,
deriveStructuredFrontmatterFields,
+ AUDIT_SCHEMA_VERSION,
+ MAX_AUDIT_EXPORT_ROWS,
+ MAX_AUDIT_LOG_LIMIT,
} from './methods';
export type * from './types';
export type * from './methods';
+export {
+ AUDIT_ACTIONS,
+ AUDIT_CATEGORIES,
+ AUDIT_OUTCOMES,
+ AUDIT_SEVERITIES,
+ AUDIT_ACTOR_TYPES,
+ AUDIT_ACTION_CATEGORY,
+} from './types/admin';
+export { GENESIS_HASH, PLATFORM_CHAIN_KEY } from './schema/auditLog';
export { default as logger } from './config/winston';
export { default as meiliLogger } from './config/meiliLogger';
export { redactMessage } from './config/parsers';
diff --git a/packages/data-schemas/src/methods/auditLog.spec.ts b/packages/data-schemas/src/methods/auditLog.spec.ts
new file mode 100644
index 0000000000..eb5504b738
--- /dev/null
+++ b/packages/data-schemas/src/methods/auditLog.spec.ts
@@ -0,0 +1,494 @@
+import mongoose, { Types } from 'mongoose';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import type { RecordAuditEntryInput } from '~/types';
+import type * as t from '~/types';
+import auditLogSchema, { GENESIS_HASH, PLATFORM_CHAIN_KEY } from '~/schema/auditLog';
+import { auditChainKey, createAuditLogMethods } from './auditLog';
+
+jest.mock('~/config/winston', () => ({
+ error: jest.fn(),
+ warn: jest.fn(),
+ info: jest.fn(),
+ debug: jest.fn(),
+}));
+
+let mongoServer: MongoMemoryServer;
+let AuditLog: mongoose.Model<t.IAuditLog>;
+let methods: ReturnType<typeof createAuditLogMethods>;
+
+const actorObjectId = new Types.ObjectId();
+const CK_A = auditChainKey('tenant-a');
+const CK_B = auditChainKey('tenant-b');
+
+function baseInput(over: Partial<RecordAuditEntryInput> = {}): RecordAuditEntryInput {
+ return {
+ action: 'grant.assigned',
+ actor: { type: 'user', id: actorObjectId, name: 'Alice Admin' },
+ target: { type: 'role', id: 'ADMIN', name: 'ADMIN' },
+ metadata: { capability: 'manage:users' },
+ tenantId: 'tenant-a',
+ ...over,
+ };
+}
+
+async function seed(count: number, over: Partial<RecordAuditEntryInput> = {}): Promise<void> {
+ for (let i = 0; i < count; i++) {
+ await methods.recordAuditEntry(baseInput({ metadata: { capability: `cap:${i}` }, ...over }));
+ }
+}
+
+beforeAll(async () => {
+ mongoServer = await MongoMemoryServer.create();
+ AuditLog = mongoose.models.AuditLog || mongoose.model<t.IAuditLog>('AuditLog', auditLogSchema);
+ methods = createAuditLogMethods(mongoose);
+ await mongoose.connect(mongoServer.getUri());
+ await AuditLog.init();
+});
+
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer.stop();
+});
+
+beforeEach(async () => {
+ await AuditLog.collection.deleteMany({});
+});
+
+describe('auditLog methods', () => {
+ describe('recordAuditEntry', () => {
+ it('persists a tenant-scoped entry with denormalized + derived fields', async () => {
+ const doc = await methods.recordAuditEntry(baseInput());
+ expect(doc).not.toBeNull();
+
+ const persisted = await AuditLog.findOne({ chainKey: CK_A }).lean();
+ expect(persisted).toMatchObject({
+ schemaVersion: 1,
+ category: 'grant',
+ action: 'grant.assigned',
+ outcome: 'success',
+ severity: 'info',
+ actor: { type: 'user', id: actorObjectId.toString(), name: 'Alice Admin' },
+ target: { type: 'role', id: 'ADMIN', name: 'ADMIN' },
+ metadata: { capability: 'manage:users' },
+ tenantId: 'tenant-a',
+ chainKey: CK_A,
+ seq: 1,
+ prevHash: GENESIS_HASH,
+ });
+ expect(persisted?.hash).toMatch(/^[a-f0-9]{64}$/);
+ expect(persisted?.createdAt).toBeInstanceOf(Date);
+ });
+
+ it('derives a warning severity for non-success outcomes', async () => {
+ await methods.recordAuditEntry(baseInput({ outcome: 'denied' }));
+ const persisted = await AuditLog.findOne({ chainKey: CK_A }).lean();
+ expect(persisted?.outcome).toBe('denied');
+ expect(persisted?.severity).toBe('warning');
+ });
+
+ it('starts each chain at the genesis hash and links subsequent entries', async () => {
+ const first = await methods.recordAuditEntry(baseInput());
+ const second = await methods.recordAuditEntry(baseInput());
+ expect(first?.seq).toBe(1);
+ expect(first?.prevHash).toBe(GENESIS_HASH);
+ expect(second?.seq).toBe(2);
+ expect(second?.prevHash).toBe(first?.hash);
+ });
+
+ it('keeps tenant and platform chains independent', async () => {
+ await methods.recordAuditEntry(baseInput({ tenantId: 'tenant-a' }));
+ await methods.recordAuditEntry(baseInput({ tenantId: 'tenant-b' }));
+ await methods.recordAuditEntry(baseInput({ tenantId: undefined }));
+
+ const a = await AuditLog.findOne({ chainKey: CK_A }).lean();
+ const b = await AuditLog.findOne({ chainKey: CK_B }).lean();
+ const platform = await AuditLog.findOne({ chainKey: PLATFORM_CHAIN_KEY }).lean();
+
+ expect(a?.seq).toBe(1);
+ expect(b?.seq).toBe(1);
+ expect(platform?.seq).toBe(1);
+ expect(platform?.tenantId).toBeUndefined();
+ });
+
+ it('treats a blank tenantId as platform scope (no literal "" stored)', async () => {
+ await methods.recordAuditEntry(baseInput({ tenantId: ' ' }));
+ const platform = await AuditLog.findOne({ chainKey: PLATFORM_CHAIN_KEY }).lean();
+ expect(platform).not.toBeNull();
+ expect(platform?.tenantId).toBeUndefined();
+ const blank = await AuditLog.findOne({ tenantId: '' }).lean();
+ expect(blank).toBeNull();
+ });
+
+ it('omits metadata/context entirely when empty', async () => {
+ await methods.recordAuditEntry(
+ baseInput({ metadata: {}, context: { ip: '', userAgent: undefined } }),
+ );
+ const persisted = await AuditLog.findOne({ chainKey: CK_A }).lean();
+ expect(persisted?.metadata).toBeUndefined();
+ expect(persisted?.context).toBeUndefined();
+ });
+
+ it('persists request context when provided', async () => {
+ await methods.recordAuditEntry(
+ baseInput({ context: { ip: '10.0.0.1', userAgent: 'jest', requestId: 'req-1' } }),
+ );
+ const persisted = await AuditLog.findOne({ chainKey: CK_A }).lean();
+ expect(persisted?.context).toMatchObject({
+ ip: '10.0.0.1',
+ userAgent: 'jest',
+ requestId: 'req-1',
+ });
+ });
+
+ it('fail-open returns null on write failure; fail-closed throws', async () => {
+ const spy = jest
+ .spyOn(AuditLog, 'create')
+ .mockRejectedValueOnce(new Error('boom'))
+ .mockRejectedValueOnce(new Error('boom'));
+
+ await expect(methods.recordAuditEntry(baseInput())).resolves.toBeNull();
+ await expect(methods.recordAuditEntry(baseInput(), { failClosed: true })).rejects.toThrow(
+ 'boom',
+ );
+
+ spy.mockRestore();
+ });
+ });
+
+ describe('append-only enforcement', () => {
+ it('rejects every query-level update and delete path', async () => {
+ await methods.recordAuditEntry(baseInput());
+ await expect(
+ AuditLog.updateOne({ chainKey: CK_A }, { action: 'grant.removed' }),
+ ).rejects.toThrow(/append-only/);
+ await expect(AuditLog.updateMany({}, { seq: 9 })).rejects.toThrow(/append-only/);
+ await expect(AuditLog.findOneAndUpdate({}, { seq: 9 })).rejects.toThrow(/append-only/);
+ await expect(AuditLog.deleteOne({ chainKey: CK_A })).rejects.toThrow(/append-only/);
+ await expect(AuditLog.deleteMany({ chainKey: CK_A })).rejects.toThrow(/append-only/);
+ await expect(AuditLog.findOneAndDelete({})).rejects.toThrow(/append-only/);
+ });
+
+ it('rejects document-level re-save and deleteOne', async () => {
+ await methods.recordAuditEntry(baseInput());
+ const doc = await AuditLog.findOne({ chainKey: CK_A });
+ expect(doc).not.toBeNull();
+ await expect(doc!.save()).rejects.toThrow(/append-only/);
+ await expect(doc!.deleteOne()).rejects.toThrow(/append-only/);
+ });
+
+ it('rejects bulkWrite (which would bypass query/document middleware)', async () => {
+ await methods.recordAuditEntry(baseInput());
+ await expect(
+ AuditLog.bulkWrite([
+ {
+ updateOne: {
+ filter: { chainKey: CK_A },
+ update: { $set: { 'actor.name': 'x' } },
+ },
+ },
+ ]),
+ ).rejects.toThrow(/append-only/);
+ });
+
+ it('rejects insertMany (which would let callers poison the chain)', async () => {
+ await expect(
+ AuditLog.insertMany([
+ {
+ schemaVersion: 1,
+ category: 'grant',
+ action: 'grant.assigned',
+ outcome: 'success',
+ severity: 'info',
+ actor: { type: 'user', name: 'Mallory' },
+ target: { type: 'role', id: 'ADMIN', name: 'ADMIN' },
+ chainKey: CK_A,
+ seq: 999,
+ prevHash: GENESIS_HASH,
+ hash: 'f'.repeat(64),
+ createdAt: new Date(),
+ },
+ ]),
+ ).rejects.toThrow(/append-only/);
+ });
+ });
+
+ describe('listAuditLogPage', () => {
+ it('returns newest-first entries with total and nextCursor', async () => {
+ await seed(3);
+ const page = await methods.listAuditLogPage('tenant-a', { limit: 2 });
+ expect(page.total).toBe(3);
+ expect(page.entries).toHaveLength(2);
+ expect(page.entries[0].integrity.seq).toBe(3);
+ expect(page.entries[1].integrity.seq).toBe(2);
+ expect(page.nextCursor).toBe(2);
+ });
+
+ it('paginates by keyset cursor without duplicating rows under concurrent appends', async () => {
+ await seed(4);
+ const page1 = await methods.listAuditLogPage('tenant-a', { limit: 2 });
+ const seenIds = new Set(page1.entries.map((e) => e.id));
+ // a new entry lands at the head between page fetches
+ await methods.recordAuditEntry(baseInput());
+ const page2 = await methods.listAuditLogPage('tenant-a', {
+ limit: 2,
+ cursor: page1.nextCursor ?? undefined,
+ });
+ for (const entry of page2.entries) {
+ expect(seenIds.has(entry.id)).toBe(false);
+ }
+ expect(page2.entries.map((e) => e.integrity.seq)).toEqual([2, 1]);
+ expect(page2.nextCursor).toBeNull();
+ });
+
+ it('supports offset pagination', async () => {
+ await seed(3);
+ const page = await methods.listAuditLogPage('tenant-a', { limit: 1, offset: 1 });
+ expect(page.entries[0].integrity.seq).toBe(2);
+ });
+
+ it('isolates tenants', async () => {
+ await methods.recordAuditEntry(baseInput({ tenantId: 'tenant-a' }));
+ await methods.recordAuditEntry(baseInput({ tenantId: 'tenant-b' }));
+ const page = await methods.listAuditLogPage('tenant-a', {});
+ expect(page.total).toBe(1);
+ expect(page.entries[0].tenantId).toBe('tenant-a');
+ });
+
+ it('filters by action, outcome, severity, and actorType', async () => {
+ await methods.recordAuditEntry(baseInput({ action: 'grant.assigned' }));
+ await methods.recordAuditEntry(baseInput({ action: 'grant.removed', outcome: 'denied' }));
+
+ expect(
+ (await methods.listAuditLogPage('tenant-a', { action: ['grant.removed'] })).total,
+ ).toBe(1);
+ expect((await methods.listAuditLogPage('tenant-a', { outcome: ['denied'] })).total).toBe(1);
+ expect((await methods.listAuditLogPage('tenant-a', { severity: ['warning'] })).total).toBe(1);
+ expect((await methods.listAuditLogPage('tenant-a', { actorType: 'user' })).total).toBe(2);
+ expect((await methods.listAuditLogPage('tenant-a', { actorType: 'agent' })).total).toBe(0);
+ });
+
+ it('substring-matches actorQuery, targetQuery, and capability case-insensitively', async () => {
+ await methods.recordAuditEntry(
+ baseInput({
+ actor: { type: 'user', id: actorObjectId, name: 'Alice Admin' },
+ target: { type: 'role', id: 'ADMIN', name: 'ADMIN' },
+ metadata: { capability: 'manage:users' },
+ }),
+ );
+ expect((await methods.listAuditLogPage('tenant-a', { actorQuery: 'alice' })).total).toBe(1);
+ expect((await methods.listAuditLogPage('tenant-a', { targetQuery: 'admin' })).total).toBe(1);
+ expect((await methods.listAuditLogPage('tenant-a', { capability: 'manage' })).total).toBe(1);
+ expect((await methods.listAuditLogPage('tenant-a', { actorQuery: 'zzz' })).total).toBe(0);
+ });
+
+ it('filters by date window', async () => {
+ await seed(2);
+ const future = new Date(Date.now() + 60_000);
+ const past = new Date(Date.now() - 60_000);
+ expect((await methods.listAuditLogPage('tenant-a', { from: past, to: future })).total).toBe(
+ 2,
+ );
+ expect((await methods.listAuditLogPage('tenant-a', { from: future })).total).toBe(0);
+ });
+ });
+
+ describe('findAuditLogEntry', () => {
+ it('returns a single entry scoped to its tenant', async () => {
+ const doc = await methods.recordAuditEntry(baseInput());
+ const id = doc!._id.toString();
+ const found = await methods.findAuditLogEntry('tenant-a', id);
+ expect(found?.id).toBe(id);
+ expect(await methods.findAuditLogEntry('tenant-b', id)).toBeNull();
+ });
+
+ it('returns null for a non-ObjectId id', async () => {
+ expect(await methods.findAuditLogEntry('tenant-a', 'not-an-id')).toBeNull();
+ });
+ });
+
+ describe('streamAuditLogEntries', () => {
+ it('streams all matching rows newest-first', async () => {
+ await seed(3);
+ const seen: number[] = [];
+ const { count, truncated } = await methods.streamAuditLogEntries('tenant-a', {}, (e) => {
+ seen.push(e.integrity.seq);
+ });
+ expect(count).toBe(3);
+ expect(truncated).toBe(false);
+ expect(seen).toEqual([3, 2, 1]);
+ });
+
+ it('honors isCancelled and reports truncation only when the cap cuts rows off', async () => {
+ await seed(5);
+ const cancelled = await methods.streamAuditLogEntries('tenant-a', {}, () => {}, {
+ isCancelled: () => true,
+ });
+ expect(cancelled.count).toBe(0);
+
+ const capped = await methods.streamAuditLogEntries('tenant-a', {}, () => {}, { maxRows: 2 });
+ expect(capped.count).toBe(2);
+ expect(capped.truncated).toBe(true);
+
+ // exact-cap match exhausts naturally and is NOT truncated
+ const exact = await methods.streamAuditLogEntries('tenant-a', {}, () => {}, { maxRows: 5 });
+ expect(exact.count).toBe(5);
+ expect(exact.truncated).toBe(false);
+ });
+ });
+
+ describe('verifyAuditChain', () => {
+ it('verifies an intact chain', async () => {
+ await seed(4);
+ const result = await methods.verifyAuditChain('tenant-a');
+ expect(result.ok).toBe(true);
+ expect(result.checked).toBe(4);
+ expect(result.range).toEqual({ firstSeq: 1, lastSeq: 4 });
+ });
+
+ it('reports ok for an empty chain', async () => {
+ const result = await methods.verifyAuditChain('tenant-a');
+ expect(result.ok).toBe(true);
+ expect(result.checked).toBe(0);
+ });
+
+ it('detects a tampered field (hash mismatch)', async () => {
+ await seed(3);
+ // mutate a field via the raw driver, bypassing the append-only hooks
+ await AuditLog.collection.updateOne(
+ { chainKey: CK_A, seq: 2 },
+ { $set: { 'actor.name': 'Mallory' } },
+ );
+ const result = await methods.verifyAuditChain('tenant-a');
+ expect(result.ok).toBe(false);
+ expect(result.brokenAt).toBe(2);
+ expect(result.reason).toBe('hash mismatch');
+ });
+
+ it('detects a deleted entry (sequence gap)', async () => {
+ await seed(3);
+ await AuditLog.collection.deleteOne({ chainKey: CK_A, seq: 2 });
+ const result = await methods.verifyAuditChain('tenant-a');
+ expect(result.ok).toBe(false);
+ expect(result.reason).toMatch(/sequence gap/);
+ });
+
+ it('detects a forged hash link', async () => {
+ await seed(3);
+ await AuditLog.collection.updateOne(
+ { chainKey: CK_A, seq: 2 },
+ { $set: { hash: 'f'.repeat(64) } },
+ );
+ const result = await methods.verifyAuditChain('tenant-a');
+ expect(result.ok).toBe(false);
+ expect(result.brokenAt).toBe(2);
+ });
+
+ it('does not silently trust a deleted prefix without a checkpoint', async () => {
+ await seed(3);
+ // attacker deletes the oldest row through the raw driver
+ await AuditLog.collection.deleteOne({ chainKey: CK_A, seq: 1 });
+ const result = await methods.verifyAuditChain('tenant-a');
+ expect(result.ok).toBe(false);
+ expect(result.brokenAt).toBe(2);
+ expect(result.reason).toMatch(/non-genesis|prefix/);
+ });
+
+ it('rejects a checkpoint that does not match the remaining chain', async () => {
+ await seed(3);
+ await AuditLog.collection.deleteOne({ chainKey: CK_A, seq: 1 });
+ const result = await methods.verifyAuditChain('tenant-a', {
+ trustedCheckpoint: { throughSeq: 1, prevHash: 'f'.repeat(64) },
+ });
+ expect(result.ok).toBe(false);
+ expect(result.reason).toMatch(/checkpoint mismatch/);
+ });
+ });
+
+ describe('purgeAuditLogEntries', () => {
+ it('is a no-op unless confirmed', async () => {
+ await seed(2);
+ const result = await methods.purgeAuditLogEntries('tenant-a', {
+ before: new Date(Date.now() + 60_000),
+ confirm: false,
+ });
+ expect(result.deletedCount).toBe(0);
+ expect(await AuditLog.countDocuments({ chainKey: CK_A })).toBe(2);
+ });
+
+ it('purges a prefix and leaves the chain verifiable from a checkpoint', async () => {
+ // space writes so createdAt is strictly increasing for a deterministic cutoff
+ for (let i = 0; i < 4; i++) {
+ await methods.recordAuditEntry(baseInput());
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+ const third = await AuditLog.findOne({ chainKey: CK_A, seq: 3 }).lean();
+ const cutoff = third!.createdAt;
+
+ const result = await methods.purgeAuditLogEntries('tenant-a', {
+ before: cutoff,
+ confirm: true,
+ });
+ expect(result.deletedCount).toBeGreaterThanOrEqual(1);
+ expect(result.checkpoint?.throughSeq).toBeGreaterThanOrEqual(1);
+
+ // Without the checkpoint, the now non-genesis start is flagged, not trusted.
+ const unverified = await methods.verifyAuditChain('tenant-a');
+ expect(unverified.ok).toBe(false);
+
+ // With the checkpoint the purge returned, the shorter chain verifies.
+ const verified = await methods.verifyAuditChain('tenant-a', {
+ trustedCheckpoint: result.checkpoint,
+ });
+ expect(verified.ok).toBe(true);
+ expect(verified.range?.firstSeq).toBeGreaterThan(1);
+ });
+
+ it('purges only a contiguous seq prefix under createdAt clock skew', async () => {
+ for (let i = 0; i < 4; i++) {
+ await methods.recordAuditEntry(baseInput());
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+ const fourth = await AuditLog.findOne({ chainKey: CK_A, seq: 4 }).lean();
+ // simulate multi-instance clock skew: the earliest seq carries a late timestamp
+ await AuditLog.collection.updateOne(
+ { chainKey: CK_A, seq: 1 },
+ { $set: { createdAt: new Date(fourth!.createdAt.getTime() + 60_000) } },
+ );
+ // a naive `createdAt < before` delete would drop interior rows (seq 2 & 3)
+ // while keeping seq 1, creating a gap — the seq-boundary purge must refuse,
+ // since seq 1 (the lowest seq) is now within the retention window.
+ const result = await methods.purgeAuditLogEntries('tenant-a', {
+ before: fourth!.createdAt,
+ confirm: true,
+ });
+ expect(result.deletedCount).toBe(0);
+ const remaining = await AuditLog.find({ chainKey: CK_A })
+ .sort({ seq: 1 })
+ .select('seq')
+ .lean<{ seq: number }[]>();
+ expect(remaining.map((r) => r.seq)).toEqual([1, 2, 3, 4]);
+ });
+
+ it('does not mint a checkpoint when a confirmed purge removed nothing', async () => {
+ await seed(2);
+ const result = await methods.purgeAuditLogEntries('tenant-a', {
+ // cutoff before every entry → nothing matches → no authorized prefix
+ before: new Date(Date.now() - 60_000),
+ confirm: true,
+ });
+ expect(result.deletedCount).toBe(0);
+ expect(result.checkpoint).toBeUndefined();
+ });
+ });
+
+ describe('append index safety', () => {
+ it('builds the unique seq index before appending (independent of autoIndex)', async () => {
+ const spy = jest.spyOn(AuditLog, 'createIndexes');
+ // a fresh methods instance has not yet memoized the index build
+ const freshMethods = createAuditLogMethods(mongoose);
+ await freshMethods.recordAuditEntry(baseInput());
+ expect(spy).toHaveBeenCalled();
+ spy.mockRestore();
+ });
+ });
+});
diff --git a/packages/data-schemas/src/methods/auditLog.ts b/packages/data-schemas/src/methods/auditLog.ts
new file mode 100644
index 0000000000..6d520df07f
--- /dev/null
+++ b/packages/data-schemas/src/methods/auditLog.ts
@@ -0,0 +1,685 @@
+import { createHash } from 'node:crypto';
+import type { FilterQuery, Model } from 'mongoose';
+import type {
+ AdminAuditLogEntry,
+ AuditChainVerification,
+ AuditContext,
+ AuditLogFilters,
+ AuditLogPage,
+ AuditMetadata,
+ IAuditLog,
+ PurgeAuditLogOptions,
+ PurgeAuditLogResult,
+ RecordAuditEntryInput,
+ RecordAuditEntryOptions,
+ VerifyAuditChainOptions,
+} from '~/types';
+import { GENESIS_HASH, PLATFORM_CHAIN_KEY } from '~/schema/auditLog';
+import { AUDIT_ACTION_CATEGORY } from '~/types/admin';
+import logger from '~/config/winston';
+
+const DEFAULT_LIMIT = 100;
+export const MAX_AUDIT_LOG_LIMIT = 500;
+/**
+ * Upper bound on rows emitted by the CSV export stream. At 100k rows per tenant
+ * per export request, a careless admin script (or a hostile auditor) can keep a
+ * cursor and a Node worker busy without saturating either; beyond that, exports
+ * should be sliced by `from`/`to`.
+ */
+export const MAX_AUDIT_EXPORT_ROWS = 100_000;
+/** Record-format version stamped on every new entry. */
+export const AUDIT_SCHEMA_VERSION = 1;
+const MAX_SEARCH_LENGTH = 200;
+/**
+ * Retries when concurrent appends race for the same `seq`. Generous because a
+ * lost append on the default fail-open path means a silently missing audit row;
+ * with jittered backoff this resolves contention well beyond any realistic burst
+ * of parallel admin writes.
+ */
+const MAX_APPEND_RETRIES = 12;
+/** Base unit (ms) for jittered backoff between duplicate-key retries. */
+const APPEND_BACKOFF_MS = 5;
+const OBJECT_ID_RE = /^[a-fA-F0-9]{24}$/;
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+export interface AuditLogMethods {
+ recordAuditEntry: (
+ input: RecordAuditEntryInput,
+ options?: RecordAuditEntryOptions,
+ ) => Promise<IAuditLog | null>;
+ listAuditLogPage: (
+ tenantId: string | undefined,
+ filters: AuditLogFilters,
+ ) => Promise<AuditLogPage>;
+ findAuditLogEntry: (
+ tenantId: string | undefined,
+ id: string,
+ ) => Promise<AdminAuditLogEntry | null>;
+ streamAuditLogEntries: (
+ tenantId: string | undefined,
+ filters: Omit<AuditLogFilters, 'offset' | 'limit' | 'cursor'>,
+ onEntry: (entry: AdminAuditLogEntry) => void | Promise<void>,
+ options?: { isCancelled?: () => boolean; maxRows?: number },
+ ) => Promise<{ count: number; truncated: boolean }>;
+ verifyAuditChain: (
+ tenantId: string | undefined,
+ options?: VerifyAuditChainOptions,
+ ) => Promise<AuditChainVerification>;
+ purgeAuditLogEntries: (
+ tenantId: string | undefined,
+ options: PurgeAuditLogOptions,
+ ) => Promise<PurgeAuditLogResult>;
+}
+
+function escapeRegex(input: string): string {
+ return input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function regexFilter(value: string): { $regex: string; $options: string } {
+ return { $regex: escapeRegex(value), $options: 'i' };
+}
+
+function oneOrIn<T>(values: T[]): T | { $in: T[] } {
+ return values.length === 1 ? values[0] : { $in: values };
+}
+
+function idToString(id: string | { toString(): string }): string {
+ return typeof id === 'string' ? id : id.toString();
+}
+
+function isDuplicateKeyError(err: unknown): boolean {
+ return typeof err === 'object' && err !== null && (err as { code?: number }).code === 11000;
+}
+
+/** Distinguishes tenant chains from the platform chain so a tenant whose id is
+ * literally the platform sentinel cannot share the platform's audit chain. */
+const TENANT_CHAIN_PREFIX = 'tenant:';
+
+/** Tenant scope → chain key. Blank/whitespace tenant is the platform chain;
+ * tenant ids are namespaced so they can never collide with `PLATFORM_CHAIN_KEY`. */
+export function auditChainKey(tenantId?: string): string {
+ return typeof tenantId === 'string' && tenantId.trim().length > 0
+ ? `${TENANT_CHAIN_PREFIX}${tenantId}`
+ : PLATFORM_CHAIN_KEY;
+}
+
+function normalizeTenantId(tenantId?: string): string | undefined {
+ return typeof tenantId === 'string' && tenantId.trim().length > 0 ? tenantId : undefined;
+}
+
+/** Drop undefined values; collapse an empty map to `undefined` so the field is
+ * omitted entirely (and hashes identically on read-back). */
+function normalizeMetadata(metadata?: AuditMetadata): AuditMetadata | undefined {
+ if (!metadata) return undefined;
+ const out: AuditMetadata = {};
+ for (const [key, value] of Object.entries(metadata)) {
+ if (value !== undefined) out[key] = value;
+ }
+ return Object.keys(out).length > 0 ? out : undefined;
+}
+
+function normalizeContext(context?: AuditContext): AuditContext | undefined {
+ if (!context) return undefined;
+ const out: AuditContext = {};
+ if (context.requestId) out.requestId = context.requestId;
+ if (context.ip) out.ip = context.ip;
+ if (context.userAgent) out.userAgent = context.userAgent;
+ if (context.sessionId) out.sessionId = context.sessionId;
+ return Object.keys(out).length > 0 ? out : undefined;
+}
+
+/** Deterministic JSON: object keys sorted recursively so two semantically equal
+ * entries always serialize to the same string. */
+function stableStringify(value: unknown): string {
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
+ const record = value as Record<string, unknown>;
+ const keys = Object.keys(record).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(record[k])}`).join(',')}}`;
+}
+
+/** Fields covered by the per-entry hash. Mirrors the stored shape so write-time
+ * and verify-time recomputation agree exactly. */
+interface HashableEntry {
+ schemaVersion: number;
+ category: IAuditLog['category'];
+ action: IAuditLog['action'];
+ outcome: IAuditLog['outcome'];
+ severity: IAuditLog['severity'];
+ actor: IAuditLog['actor'];
+ target: IAuditLog['target'];
+ metadata?: AuditMetadata;
+ context?: AuditContext;
+ tenantId?: string;
+ chainKey: string;
+ seq: number;
+ prevHash: string;
+ createdAt: Date;
+}
+
+function computeEntryHash(entry: HashableEntry): string {
+ const canonical = {
+ v: entry.schemaVersion,
+ category: entry.category,
+ action: entry.action,
+ outcome: entry.outcome,
+ severity: entry.severity,
+ actor: {
+ type: entry.actor.type,
+ id: entry.actor.id ?? null,
+ name: entry.actor.name,
+ },
+ target: {
+ type: entry.target.type,
+ id: entry.target.id ?? null,
+ name: entry.target.name ?? null,
+ },
+ metadata: entry.metadata ?? null,
+ context: entry.context
+ ? {
+ requestId: entry.context.requestId ?? null,
+ ip: entry.context.ip ?? null,
+ userAgent: entry.context.userAgent ?? null,
+ sessionId: entry.context.sessionId ?? null,
+ }
+ : null,
+ tenantId: entry.tenantId ?? null,
+ chainKey: entry.chainKey,
+ seq: entry.seq,
+ prevHash: entry.prevHash,
+ createdAt: entry.createdAt.toISOString(),
+ };
+ return createHash('sha256').update(stableStringify(canonical)).digest('hex');
+}
+
+function toWire(doc: IAuditLog): AdminAuditLogEntry {
+ const entry: AdminAuditLogEntry = {
+ id: doc._id.toString(),
+ schemaVersion: doc.schemaVersion,
+ category: doc.category,
+ action: doc.action,
+ outcome: doc.outcome,
+ severity: doc.severity,
+ actor: {
+ type: doc.actor.type,
+ name: doc.actor.name,
+ ...(doc.actor.id != null ? { id: doc.actor.id } : {}),
+ },
+ target: {
+ type: doc.target.type,
+ ...(doc.target.id != null ? { id: doc.target.id } : {}),
+ ...(doc.target.name != null ? { name: doc.target.name } : {}),
+ },
+ integrity: { seq: doc.seq, hash: doc.hash, prevHash: doc.prevHash },
+ timestamp: doc.createdAt.toISOString(),
+ };
+ if (doc.metadata != null) entry.metadata = doc.metadata;
+ const context = normalizeContext(doc.context);
+ if (context) entry.context = context;
+ if (doc.tenantId != null) entry.tenantId = doc.tenantId;
+ return entry;
+}
+
+function clampLimit(limit?: number): number {
+ if (!limit || Number.isNaN(limit) || limit < 1) return DEFAULT_LIMIT;
+ return Math.min(Math.floor(limit), MAX_AUDIT_LOG_LIMIT);
+}
+
+/**
+ * Builds the Mongo `find` filter for audit-log queries. Chain scoping is always
+ * applied first and uses the compound `{ chainKey, ... }` indexes. The substring
+ * regex filters (`actor.name`, `target.name`, `metadata.capability`, `search`)
+ * are case-insensitive and cannot use a B-tree index: within the chain slice
+ * they degrade to a partition scan. The primary listing combines `chainKey` with
+ * `seq`/`createdAt` pagination, so the scan stays bounded by the date window.
+ */
+function buildFilter(chainKey: string, filters: AuditLogFilters): FilterQuery<IAuditLog> {
+ const query: FilterQuery<IAuditLog> = { chainKey };
+
+ if (filters.category && filters.category.length > 0) {
+ query.category = oneOrIn(filters.category);
+ }
+ if (filters.action && filters.action.length > 0) {
+ query.action = oneOrIn(filters.action);
+ }
+ if (filters.outcome && filters.outcome.length > 0) {
+ query.outcome = oneOrIn(filters.outcome);
+ }
+ if (filters.severity && filters.severity.length > 0) {
+ query.severity = oneOrIn(filters.severity);
+ }
+ if (filters.actorType) {
+ query['actor.type'] = filters.actorType;
+ }
+ if (filters.actorQuery) {
+ query['actor.name'] = regexFilter(filters.actorQuery);
+ }
+ if (filters.targetType) {
+ query['target.type'] = filters.targetType;
+ }
+ if (filters.targetQuery) {
+ query['target.name'] = regexFilter(filters.targetQuery);
+ }
+ if (filters.capability) {
+ query['metadata.capability'] = regexFilter(filters.capability);
+ }
+ if (filters.from || filters.to) {
+ const createdAt: { $gte?: Date; $lte?: Date } = {};
+ if (filters.from) createdAt.$gte = filters.from;
+ if (filters.to) createdAt.$lte = filters.to;
+ query.createdAt = createdAt;
+ }
+ if (filters.search && filters.search.length > 0) {
+ const safe = regexFilter(filters.search.slice(0, MAX_SEARCH_LENGTH));
+ query.$or = [
+ { 'actor.name': safe },
+ { 'target.name': safe },
+ { action: safe },
+ { 'metadata.capability': safe },
+ ];
+ }
+
+ return query;
+}
+
+export function createAuditLogMethods(mongoose: typeof import('mongoose')): AuditLogMethods {
+ function model(): Model<IAuditLog> {
+ return mongoose.models.AuditLog as Model<IAuditLog>;
+ }
+
+ /**
+ * The read-then-create append only serializes concurrent writers when the
+ * unique `{ chainKey, seq }` index exists. With `MONGO_AUTO_INDEX=false`, or
+ * during the startup window before a background build finishes, two writers
+ * could insert the same `seq` with no duplicate-key error and silently fork
+ * the chain. Build the indexes once before the first append so serialization
+ * never depends on a background build. Memoized; reset on failure so a later
+ * write retries.
+ */
+ let indexPromise: Promise<unknown> | null = null;
+ function ensureIndexes(): Promise<unknown> {
+ if (!indexPromise) {
+ indexPromise = model()
+ .createIndexes()
+ .catch((err) => {
+ indexPromise = null;
+ throw err;
+ });
+ }
+ return indexPromise;
+ }
+
+ async function recordAuditEntry(
+ input: RecordAuditEntryInput,
+ options?: RecordAuditEntryOptions,
+ ): Promise<IAuditLog | null> {
+ const AuditLog = model();
+ const tenantId = normalizeTenantId(input.tenantId);
+ const chainKey = auditChainKey(input.tenantId);
+ const category = input.category ?? AUDIT_ACTION_CATEGORY[input.action];
+ const outcome = input.outcome ?? 'success';
+ const severity =
+ input.severity ?? (outcome === 'failure' || outcome === 'denied' ? 'warning' : 'info');
+ const actor = {
+ type: input.actor.type,
+ name: input.actor.name,
+ ...(input.actor.id != null ? { id: idToString(input.actor.id) } : {}),
+ };
+ const target = {
+ type: input.target.type,
+ ...(input.target.id != null ? { id: idToString(input.target.id) } : {}),
+ ...(input.target.name != null ? { name: input.target.name } : {}),
+ };
+ const metadata = normalizeMetadata(input.metadata);
+ const context = normalizeContext(input.context);
+
+ for (let attempt = 0; attempt < MAX_APPEND_RETRIES; attempt++) {
+ try {
+ /** Guarantee the unique seq index exists before serializing on it. */
+ await ensureIndexes();
+ const last = await AuditLog.findOne({ chainKey })
+ .sort({ seq: -1 })
+ .select('seq hash')
+ .lean<{ seq: number; hash: string }>();
+ const prevSeq = last?.seq ?? 0;
+ const prevHash = last?.hash ?? GENESIS_HASH;
+ const seq = prevSeq + 1;
+ const createdAt = new Date();
+ const hash = computeEntryHash({
+ schemaVersion: AUDIT_SCHEMA_VERSION,
+ category,
+ action: input.action,
+ outcome,
+ severity,
+ actor,
+ target,
+ metadata,
+ context,
+ tenantId,
+ chainKey,
+ seq,
+ prevHash,
+ createdAt,
+ });
+ const doc = await AuditLog.create({
+ schemaVersion: AUDIT_SCHEMA_VERSION,
+ category,
+ action: input.action,
+ outcome,
+ severity,
+ actor,
+ target,
+ ...(metadata !== undefined && { metadata }),
+ ...(context !== undefined && { context }),
+ ...(tenantId !== undefined && { tenantId }),
+ chainKey,
+ seq,
+ prevHash,
+ hash,
+ createdAt,
+ });
+ return doc;
+ } catch (err) {
+ if (isDuplicateKeyError(err) && attempt < MAX_APPEND_RETRIES - 1) {
+ /** Jittered backoff de-correlates racing writers before they recompute
+ * the tail `seq`, so the next attempt is very unlikely to collide. */
+ await sleep(Math.floor(Math.random() * APPEND_BACKOFF_MS * (attempt + 1)));
+ continue;
+ }
+ /**
+ * Fail-open by default: a failed write must never block the privileged
+ * operation, so it returns null and leaves a structured forensic trail.
+ * Callers that require a durable record pass `failClosed` to surface the
+ * failure instead.
+ */
+ logger.error('[auditLog] failed to record audit entry', {
+ action: input.action,
+ category,
+ outcome,
+ chainKey,
+ tenantId,
+ actorId: actor.id ?? null,
+ actorType: actor.type,
+ targetType: target.type,
+ targetId: target.id ?? null,
+ err,
+ });
+ if (options?.failClosed) {
+ throw err instanceof Error ? err : new Error('Failed to record audit entry');
+ }
+ return null;
+ }
+ }
+ return null;
+ }
+
+ async function listAuditLogPage(
+ tenantId: string | undefined,
+ filters: AuditLogFilters,
+ ): Promise<AuditLogPage> {
+ const AuditLog = model();
+ const chainKey = auditChainKey(tenantId);
+ const limit = clampLimit(filters.limit);
+ const base = buildFilter(chainKey, filters);
+
+ const cursorSeq =
+ typeof filters.cursor === 'number' && Number.isFinite(filters.cursor)
+ ? filters.cursor
+ : undefined;
+ const paged: FilterQuery<IAuditLog> =
+ cursorSeq !== undefined ? { ...base, seq: { $lt: cursorSeq } } : base;
+ const offset =
+ cursorSeq === undefined && filters.offset && filters.offset > 0
+ ? Math.floor(filters.offset)
+ : 0;
+
+ let pageQuery = AuditLog.find(paged)
+ .sort({ seq: -1 })
+ .limit(limit + 1);
+ if (offset > 0) pageQuery = pageQuery.skip(offset);
+
+ const [rowsPlusOne, total] = await Promise.all([
+ pageQuery.lean<IAuditLog[]>(),
+ AuditLog.countDocuments(base),
+ ]);
+
+ const hasMore = rowsPlusOne.length > limit;
+ const rows = hasMore ? rowsPlusOne.slice(0, limit) : rowsPlusOne;
+ const nextCursor = hasMore && rows.length > 0 ? rows[rows.length - 1].seq : null;
+
+ return { entries: rows.map(toWire), total, nextCursor };
+ }
+
+ async function findAuditLogEntry(
+ tenantId: string | undefined,
+ id: string,
+ ): Promise<AdminAuditLogEntry | null> {
+ if (!OBJECT_ID_RE.test(id)) return null;
+ const AuditLog = model();
+ const query: FilterQuery<IAuditLog> = { _id: id, chainKey: auditChainKey(tenantId) };
+ const doc = await AuditLog.findOne(query).lean<IAuditLog>();
+ return doc ? toWire(doc) : null;
+ }
+
+ async function streamAuditLogEntries(
+ tenantId: string | undefined,
+ filters: Omit<AuditLogFilters, 'offset' | 'limit' | 'cursor'>,
+ onEntry: (entry: AdminAuditLogEntry) => void | Promise<void>,
+ options?: { isCancelled?: () => boolean; maxRows?: number },
+ ): Promise<{ count: number; truncated: boolean }> {
+ const AuditLog = model();
+ const query = buildFilter(auditChainKey(tenantId), filters);
+ const cursor = AuditLog.find(query)
+ .sort({ seq: -1 })
+ .lean<IAuditLog[]>()
+ .cursor({ batchSize: 500 });
+
+ const isCancelled = options?.isCancelled;
+ const maxRows = options?.maxRows;
+ let count = 0;
+ let truncated = false;
+ try {
+ for await (const doc of cursor) {
+ if (isCancelled?.()) {
+ await cursor.close();
+ break;
+ }
+ if (maxRows != null && count >= maxRows) {
+ /** The cap fired only because at least one more row exists beyond it,
+ * so this is a genuine truncation — an exact-cap match exhausts the
+ * cursor naturally and never reaches here. */
+ truncated = true;
+ await cursor.close();
+ break;
+ }
+ await onEntry(toWire(doc));
+ count++;
+ }
+ } finally {
+ await cursor.close().catch(() => undefined);
+ }
+ return { count, truncated };
+ }
+
+ async function verifyAuditChain(
+ tenantId: string | undefined,
+ options?: VerifyAuditChainOptions,
+ ): Promise<AuditChainVerification> {
+ const AuditLog = model();
+ const chainKey = auditChainKey(tenantId);
+ const cursor = AuditLog.find({ chainKey })
+ .sort({ seq: 1 })
+ .lean<IAuditLog[]>()
+ .cursor({ batchSize: 500 });
+
+ const trustedCheckpoint = options?.trustedCheckpoint;
+ let prevHash = GENESIS_HASH;
+ let expectedSeq: number | null = null;
+ let firstSeq: number | null = null;
+ let lastSeq = 0;
+ let checked = 0;
+
+ try {
+ for await (const doc of cursor) {
+ if (firstSeq === null) {
+ firstSeq = doc.seq;
+ expectedSeq = doc.seq;
+ /**
+ * A non-genesis start (firstSeq > 1) means a prefix is gone. Only a
+ * matching trusted checkpoint proves it was an authorized retention
+ * purge; otherwise this is an attacker deleting the oldest rows, so we
+ * must NOT silently trust the first row's prevHash.
+ */
+ if (doc.seq === 1) {
+ prevHash = GENESIS_HASH;
+ } else if (
+ trustedCheckpoint &&
+ trustedCheckpoint.throughSeq === doc.seq - 1 &&
+ trustedCheckpoint.prevHash === doc.prevHash
+ ) {
+ prevHash = doc.prevHash;
+ } else {
+ await cursor.close();
+ return {
+ ok: false,
+ chainKey,
+ checked,
+ brokenAt: doc.seq,
+ reason: trustedCheckpoint
+ ? 'checkpoint mismatch: purged prefix does not match the trusted checkpoint'
+ : `non-genesis start at seq ${doc.seq}: prefix purged or deleted (supply a trusted checkpoint to verify)`,
+ range: { firstSeq, lastSeq: doc.seq },
+ };
+ }
+ }
+ if (doc.seq !== expectedSeq) {
+ return {
+ ok: false,
+ chainKey,
+ checked,
+ brokenAt: expectedSeq ?? doc.seq,
+ reason: `sequence gap: expected ${expectedSeq}, found ${doc.seq}`,
+ range: { firstSeq, lastSeq },
+ };
+ }
+ if (doc.prevHash !== prevHash) {
+ return {
+ ok: false,
+ chainKey,
+ checked,
+ brokenAt: doc.seq,
+ reason: 'broken hash link',
+ range: { firstSeq, lastSeq },
+ };
+ }
+ if (computeEntryHash(doc) !== doc.hash) {
+ return {
+ ok: false,
+ chainKey,
+ checked,
+ brokenAt: doc.seq,
+ reason: 'hash mismatch',
+ range: { firstSeq, lastSeq },
+ };
+ }
+ prevHash = doc.hash;
+ lastSeq = doc.seq;
+ expectedSeq = doc.seq + 1;
+ checked++;
+ }
+ } finally {
+ await cursor.close().catch(() => undefined);
+ }
+
+ return {
+ ok: true,
+ chainKey,
+ checked,
+ range: firstSeq !== null ? { firstSeq, lastSeq } : undefined,
+ };
+ }
+
+ async function purgeAuditLogEntries(
+ tenantId: string | undefined,
+ options: PurgeAuditLogOptions,
+ ): Promise<PurgeAuditLogResult> {
+ if (!options.confirm) return { deletedCount: 0 };
+ if (!(options.before instanceof Date) || Number.isNaN(options.before.getTime())) {
+ throw new Error('purgeAuditLogEntries: `before` must be a valid Date');
+ }
+ const AuditLog = model();
+ const chainKey = auditChainKey(tenantId);
+
+ /**
+ * Translate the date intent into a contiguous `seq` boundary before deleting.
+ * `createdAt` is app-generated, so under multi-instance clock skew a later
+ * `seq` can carry an earlier timestamp; a raw date delete could then remove
+ * an interior row and permanently break verification. Instead, find the
+ * earliest entry that must be retained (the first by `seq` whose `createdAt`
+ * is on/after `before`) and delete only the strictly-lower `seq` prefix. This
+ * never deletes past a retained entry, so the remaining chain stays
+ * contiguous even with skew (it may retain a few old rows, which is safe).
+ */
+ const firstRetained = await AuditLog.findOne({ chainKey, createdAt: { $gte: options.before } })
+ .sort({ seq: 1 })
+ .select('seq')
+ .lean<{ seq: number }>();
+
+ const deleteFilter: FilterQuery<IAuditLog> = firstRetained
+ ? { chainKey, seq: { $lt: firstRetained.seq } }
+ : { chainKey };
+
+ /**
+ * Retention purge is the one privileged path that removes audit rows. It
+ * intentionally uses the raw driver to bypass the append-only Mongoose hooks
+ * (the model blocks every delete). Tenant isolation is applied via `chainKey`.
+ */
+ // eslint-disable-next-line no-restricted-syntax -- privileged retention purge; append-only hooks block deleteMany, tenant scoped via chainKey
+ const result = await AuditLog.collection.deleteMany(deleteFilter);
+ const deletedCount = result.deletedCount ?? 0;
+
+ logger.warn('[auditLog] retention purge executed', {
+ chainKey,
+ before: options.before.toISOString(),
+ deletedCount,
+ });
+
+ /**
+ * Only a purge that actually removed rows may mint a trust boundary. A no-op
+ * purge returning a checkpoint for the current first entry would let a caller
+ * legitimize a prefix this purge never authorized (e.g. one an attacker
+ * deleted), so `verifyAuditChain` could be tricked into accepting it.
+ */
+ if (deletedCount === 0) {
+ return { deletedCount: 0 };
+ }
+
+ const newFirst = await AuditLog.findOne({ chainKey })
+ .sort({ seq: 1 })
+ .select('seq prevHash')
+ .lean<{ seq: number; prevHash: string }>();
+
+ return {
+ deletedCount,
+ /** Boundary for `verifyAuditChain`: the new earliest entry resumes the
+ * chain at `seq`, so the purged prefix ran through `seq - 1` and its last
+ * hash is this entry's `prevHash`. Callers persist this to later prove the
+ * purge was authorized. */
+ checkpoint: newFirst
+ ? { throughSeq: newFirst.seq - 1, prevHash: newFirst.prevHash }
+ : undefined,
+ };
+ }
+
+ return {
+ recordAuditEntry,
+ listAuditLogPage,
+ findAuditLogEntry,
+ streamAuditLogEntries,
+ verifyAuditChain,
+ purgeAuditLogEntries,
+ };
+}
diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.ts
index 9ea9e5f1e5..b98dab3a36 100644
--- a/packages/data-schemas/src/methods/index.ts
+++ b/packages/data-schemas/src/methods/index.ts
@@ -20,6 +20,13 @@ import { createAccessRoleMethods, type AccessRoleMethods } from './accessRole';
import { createUserGroupMethods, type UserGroupMethods } from './userGroup';
import { createAclEntryMethods, permissionBitSupersets, type AclEntryMethods } from './aclEntry';
import { createSystemGrantMethods, type SystemGrantMethods } from './systemGrant';
+import {
+ createAuditLogMethods,
+ AUDIT_SCHEMA_VERSION,
+ MAX_AUDIT_EXPORT_ROWS,
+ MAX_AUDIT_LOG_LIMIT,
+ type AuditLogMethods,
+} from './auditLog';
import { createShareMethods, type ShareMethods } from './share';
/* Tier 1 — Simple CRUD */
import { createActionMethods, type ActionMethods } from './action';
@@ -101,6 +108,7 @@ export {
deriveStructuredFrontmatterFields,
inferSkillFileCategory,
};
+export { AUDIT_SCHEMA_VERSION, MAX_AUDIT_EXPORT_ROWS, MAX_AUDIT_LOG_LIMIT };
export type AllMethods = UserMethods &
SessionMethods &
@@ -115,6 +123,7 @@ export type AllMethods = UserMethods &
UserGroupMethods &
AclEntryMethods &
SystemGrantMethods &
+ AuditLogMethods &
ShareMethods &
AccessRoleMethods &
PluginAuthMethods &
@@ -242,6 +251,7 @@ export function createMethods(
...createUserGroupMethods(mongoose),
...aclEntryMethods,
...systemGrantMethods,
+ ...createAuditLogMethods(mongoose),
...createShareMethods(mongoose),
...createPluginAuthMethods(mongoose),
/* Tier 1 */
@@ -284,6 +294,7 @@ export type {
UserGroupMethods,
AclEntryMethods,
SystemGrantMethods,
+ AuditLogMethods,
ShareMethods,
AccessRoleMethods,
PluginAuthMethods,
diff --git a/packages/data-schemas/src/methods/systemGrant.spec.ts b/packages/data-schemas/src/methods/systemGrant.spec.ts
index 1eef781fa9..b58a9431fa 100644
--- a/packages/data-schemas/src/methods/systemGrant.spec.ts
+++ b/packages/data-schemas/src/methods/systemGrant.spec.ts
@@ -1,8 +1,8 @@
import mongoose, { Types } from 'mongoose';
-import { PrincipalType, SystemRoles } from 'librechat-data-provider';
import { MongoMemoryServer } from 'mongodb-memory-server';
-import type * as t from '~/types';
+import { PrincipalType, SystemRoles } from 'librechat-data-provider';
import type { SystemCapability } from '~/types/admin';
+import type * as t from '~/types';
import { SystemCapabilities, CapabilityImplications } from '~/admin/capabilities';
import { createSystemGrantMethods } from './systemGrant';
import systemGrantSchema from '~/schema/systemGrant';
@@ -113,13 +113,14 @@ describe('systemGrant methods', () => {
describe('grantCapability', () => {
it('creates a grant and returns the document', async () => {
const userId = new Types.ObjectId();
- const doc = await methods.grantCapability({
+ const { grant: doc, created } = await methods.grantCapability({
principalType: PrincipalType.USER,
principalId: userId,
capability: SystemCapabilities.READ_USERS,
});
expect(doc).toBeTruthy();
+ expect(created).toBe(true);
expect(doc!.principalType).toBe(PrincipalType.USER);
expect(doc!.capability).toBe(SystemCapabilities.READ_USERS);
expect(doc!.grantedAt).toBeInstanceOf(Date);
@@ -255,7 +256,7 @@ describe('systemGrant methods', () => {
capability: SystemCapabilities.READ_USERS as SystemCapability,
};
- const original = await methods.grantCapability(params);
+ const { grant: original } = await methods.grantCapability(params);
// Simulate a race: findOneAndUpdate upserts but hits a duplicate key
const model = mongoose.models.SystemGrant;
@@ -265,8 +266,10 @@ describe('systemGrant methods', () => {
Object.assign(new Error('E11000 duplicate key error'), { code: 11000 }),
);
- const result = await methods.grantCapability(params);
+ const { grant: result, created } = await methods.grantCapability(params);
expect(result).toBeTruthy();
+ // a lost upsert race is not a new creation, so it must not be audited
+ expect(created).toBe(false);
expect(result!.capability).toBe(SystemCapabilities.READ_USERS);
expect(result!.principalId.toString()).toBe(original!.principalId.toString());
});
@@ -305,7 +308,7 @@ describe('systemGrant methods', () => {
});
it('accepts any string for ROLE principal without ObjectId validation', async () => {
- const doc = await methods.grantCapability({
+ const { grant: doc } = await methods.grantCapability({
principalType: PrincipalType.ROLE,
principalId: 'ANY_STRING_HERE',
capability: SystemCapabilities.READ_CONFIGS,
diff --git a/packages/data-schemas/src/methods/systemGrant.ts b/packages/data-schemas/src/methods/systemGrant.ts
index c3ef6100af..6d82e9cd56 100644
--- a/packages/data-schemas/src/methods/systemGrant.ts
+++ b/packages/data-schemas/src/methods/systemGrant.ts
@@ -62,7 +62,7 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
grantedBy?: string | Types.ObjectId;
},
session?: ClientSession,
- ) => Promise<ISystemGrant | null>;
+ ) => Promise<{ grant: ISystemGrant | null; created: boolean }>;
seedSystemGrants: () => Promise<void>;
revokeCapability: (
{
@@ -77,7 +77,7 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
tenantId?: string;
},
session?: ClientSession,
- ) => Promise<void>;
+ ) => Promise<{ deletedCount: number }>;
hasCapabilityForPrincipals: ({
principals,
capability,
@@ -126,7 +126,7 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
principalType: PrincipalType,
principalId: string | Types.ObjectId,
options?: { tenantId?: string; session?: ClientSession },
- ) => Promise<void>;
+ ) => Promise<ISystemGrant[]>;
} {
function tenantCondition(tenantId?: string): FilterQuery<ISystemGrant> {
return tenantId != null
@@ -265,7 +265,7 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
grantedBy?: string | Types.ObjectId;
},
session?: ClientSession,
- ): Promise<ISystemGrant | null> {
+ ): Promise<{ grant: ISystemGrant | null; created: boolean }> {
const SystemGrant = mongoose.models.SystemGrant as Model<ISystemGrant>;
const normalizedPrincipalId = normalizePrincipalId(principalId, principalType);
@@ -277,37 +277,50 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
tenantId: tenantId != null ? tenantId : { $exists: false },
};
+ /**
+ * Insert-only: re-asserting an existing grant is a true no-op (no field is
+ * mutated), so `created === false` reliably means "nothing changed" and the
+ * caller can safely skip audit emission. `grantedAt`/`grantedBy` therefore
+ * record the original grant, not the last re-assert.
+ */
const update = {
- $set: {
- grantedAt: new Date(),
- ...(grantedBy != null && { grantedBy }),
- },
$setOnInsert: {
principalType,
principalId: normalizedPrincipalId,
capability,
+ grantedAt: new Date(),
+ ...(grantedBy != null && { grantedBy }),
...(tenantId != null && { tenantId }),
},
};
- const options = {
- upsert: true,
- new: true,
- ...(session ? { session } : {}),
- };
-
try {
- return await SystemGrant.findOneAndUpdate(filter, update, options);
+ /** `includeResultMetadata` surfaces `lastErrorObject.upserted` so callers
+ * (audit emission) can tell a brand-new grant from an idempotent re-assert
+ * atomically, without a racy pre-read. Passed inline so the metadata
+ * overload is selected. */
+ const result = await SystemGrant.findOneAndUpdate(filter, update, {
+ upsert: true,
+ new: true,
+ includeResultMetadata: true,
+ session,
+ });
+ return { grant: result.value, created: result.lastErrorObject?.upserted != null };
} catch (err) {
if ((err as { code?: number }).code === 11000) {
- return (await SystemGrant.findOne(filter).lean()) as ISystemGrant | null;
+ /** A concurrent insert won the race: the row exists and we did not create
+ * it, so this is not an auditable change. */
+ const grant = (await SystemGrant.findOne(filter).lean()) as ISystemGrant | null;
+ return { grant, created: false };
}
throw err;
}
}
/**
- * Revoke a capability from a principal.
+ * Revoke a capability from a principal. Returns the deletion result so
+ * callers (e.g. audit emission) can distinguish a real revoke from a
+ * no-op against a grant that didn't exist.
*/
async function revokeCapability(
{
@@ -322,7 +335,7 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
tenantId?: string;
},
session?: ClientSession,
- ): Promise<void> {
+ ): Promise<{ deletedCount: number }> {
const SystemGrant = mongoose.models.SystemGrant as Model<ISystemGrant>;
const normalizedPrincipalId = normalizePrincipalId(principalId, principalType);
@@ -335,7 +348,8 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
};
const options = session ? { session } : {};
- await SystemGrant.deleteOne(filter, options);
+ const result = await SystemGrant.deleteOne(filter, options);
+ return { deletedCount: result.deletedCount ?? 0 };
}
/**
@@ -498,7 +512,7 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
principalType: PrincipalType,
principalId: string | Types.ObjectId,
options?: { tenantId?: string; session?: ClientSession },
- ): Promise<void> {
+ ): Promise<ISystemGrant[]> {
const SystemGrant = mongoose.models.SystemGrant as Model<ISystemGrant>;
const normalizedPrincipalId = normalizePrincipalId(principalId, principalType);
@@ -508,7 +522,11 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
...(options?.tenantId != null && { tenantId: options.tenantId }),
};
const queryOptions = options?.session ? { session: options.session } : {};
+ /** Read the matching grants before deleting so cascade callers (e.g. role
+ * deletion) can emit a `grant.removed` audit entry for each one. */
+ const removed = await SystemGrant.find(filter, null, queryOptions).lean<ISystemGrant[]>();
await SystemGrant.deleteMany(filter, queryOptions);
+ return removed;
}
return {
diff --git a/packages/data-schemas/src/models/auditLog.ts b/packages/data-schemas/src/models/auditLog.ts
new file mode 100644
index 0000000000..0efd65391d
--- /dev/null
+++ b/packages/data-schemas/src/models/auditLog.ts
@@ -0,0 +1,15 @@
+import type { Model } from 'mongoose';
+import type * as t from '~/types';
+import auditLogSchema from '~/schema/auditLog';
+
+/**
+ * AuditLog is an append-only, hash-chained compliance record.
+ *
+ * Like SystemGrant, the tenant-isolation plugin is intentionally not applied:
+ * every query is scoped by `chainKey` (the JWT-resolved tenantId, or the
+ * platform sentinel for admin operations outside any tenant), which is also the
+ * serialization key for the per-tenant hash chain.
+ */
+export function createAuditLogModel(mongoose: typeof import('mongoose')): Model<t.IAuditLog> {
+ return mongoose.models.AuditLog || mongoose.model<t.IAuditLog>('AuditLog', auditLogSchema);
+}
diff --git a/packages/data-schemas/src/models/index.ts b/packages/data-schemas/src/models/index.ts
index 476091ec9c..6493013f2c 100644
--- a/packages/data-schemas/src/models/index.ts
+++ b/packages/data-schemas/src/models/index.ts
@@ -16,6 +16,7 @@ import { createSkillFileModel } from './skillFile';
import { createConversationModel } from './convo';
import { createToolCallModel } from './toolCall';
import { createAclEntryModel } from './aclEntry';
+import { createAuditLogModel } from './auditLog';
import { createSessionModel } from './session';
import { createBalanceModel } from './balance';
import { createMessageModel } from './message';
@@ -71,6 +72,7 @@ export function createModels(mongoose: typeof import('mongoose')): {
AccessRole: ReturnType<typeof createAccessRoleModel>;
AclEntry: ReturnType<typeof createAclEntryModel>;
SystemGrant: ReturnType<typeof createSystemGrantModel>;
+ AuditLog: ReturnType<typeof createAuditLogModel>;
Group: ReturnType<typeof createGroupModel>;
Config: ReturnType<typeof createConfigModel>;
} {
@@ -108,6 +110,7 @@ export function createModels(mongoose: typeof import('mongoose')): {
AccessRole: createAccessRoleModel(mongoose),
AclEntry: createAclEntryModel(mongoose),
SystemGrant: createSystemGrantModel(mongoose),
+ AuditLog: createAuditLogModel(mongoose),
Group: createGroupModel(mongoose),
Config: createConfigModel(mongoose),
};
diff --git a/packages/data-schemas/src/models/plugins/tenantIsolation.coverage.spec.ts b/packages/data-schemas/src/models/plugins/tenantIsolation.coverage.spec.ts
index 61708666f1..6f318abe10 100644
--- a/packages/data-schemas/src/models/plugins/tenantIsolation.coverage.spec.ts
+++ b/packages/data-schemas/src/models/plugins/tenantIsolation.coverage.spec.ts
@@ -13,10 +13,12 @@ const TENANT_ISOLATION_APPLIED = Symbol.for('librechat:tenantIsolation');
* tenant-isolation plugin. SystemGrant scopes tenancy manually inside its
* methods (see models/systemGrant). SkillSyncStatus stores both app-wide YAML
* status rows and tenant-scoped override rows, so its methods apply explicit
- * tenant filters instead of ambient ALS scoping. Adding an entry here must be a
- * deliberate, reviewed decision — that is the whole point of this guard.
+ * tenant filters instead of ambient ALS scoping. AuditLog composes its tenant
+ * filter from the JWT-resolved caller and uses `{ tenantId: { $exists: false } }`
+ * for platform-level entries. Adding an entry here must be a deliberate,
+ * reviewed decision — that is the whole point of this guard.
*/
-const MANUAL_TENANT_SCOPING = new Set<string>(['SystemGrant', 'SkillSyncStatus']);
+const MANUAL_TENANT_SCOPING = new Set<string>(['SystemGrant', 'SkillSyncStatus', 'AuditLog']);
function isPluginApplied(schema: mongoose.Schema): boolean {
return (schema as unknown as { [key: symbol]: boolean })[TENANT_ISOLATION_APPLIED] === true;
diff --git a/packages/data-schemas/src/schema/auditLog.ts b/packages/data-schemas/src/schema/auditLog.ts
new file mode 100644
index 0000000000..51a33f7a73
--- /dev/null
+++ b/packages/data-schemas/src/schema/auditLog.ts
@@ -0,0 +1,182 @@
+import { Schema } from 'mongoose';
+import type { IAuditLog } from '~/types';
+import {
+ AUDIT_ACTIONS,
+ AUDIT_ACTOR_TYPES,
+ AUDIT_CATEGORIES,
+ AUDIT_OUTCOMES,
+ AUDIT_SEVERITIES,
+} from '~/types/admin';
+
+/** Sentinel `chainKey` for platform-level (non-tenant) audit entries. */
+export const PLATFORM_CHAIN_KEY = '__platform__';
+
+/** Genesis link: the `prevHash` of the first entry in any chain. */
+export const GENESIS_HASH: string = '0'.repeat(64);
+
+const actorSchema = new Schema(
+ {
+ type: { type: String, enum: [...AUDIT_ACTOR_TYPES], required: true, immutable: true },
+ id: { type: String, required: false, immutable: true },
+ name: { type: String, required: true, immutable: true },
+ },
+ { _id: false },
+);
+
+const targetSchema = new Schema(
+ {
+ type: { type: String, required: true, immutable: true },
+ id: { type: String, required: false, immutable: true },
+ name: { type: String, required: false, immutable: true },
+ },
+ { _id: false },
+);
+
+const contextSchema = new Schema(
+ {
+ requestId: { type: String, required: false, immutable: true },
+ ip: { type: String, required: false, immutable: true },
+ userAgent: { type: String, required: false, immutable: true },
+ sessionId: { type: String, required: false, immutable: true },
+ },
+ { _id: false },
+);
+
+/**
+ * Append-only by schema contract: every field is `immutable`, every
+ * update-style operation is short-circuited in the pre-hooks below, and there
+ * is no `updatedAt` — a mutable timestamp would imply mutation is allowed.
+ * `createdAt` is set explicitly by the writer (not by `timestamps`) so it is
+ * covered by the per-entry hash. Tamper-evidence beyond these app-layer guards
+ * comes from the hash chain (`prevHash`/`hash`/`seq`) maintained in
+ * `~/methods/auditLog`.
+ */
+const auditLogSchema: Schema<IAuditLog> = new Schema<IAuditLog>({
+ schemaVersion: { type: Number, required: true, immutable: true },
+ category: {
+ type: String,
+ enum: [...AUDIT_CATEGORIES],
+ required: true,
+ immutable: true,
+ },
+ action: {
+ type: String,
+ enum: [...AUDIT_ACTIONS],
+ required: true,
+ immutable: true,
+ },
+ outcome: {
+ type: String,
+ enum: [...AUDIT_OUTCOMES],
+ required: true,
+ immutable: true,
+ },
+ severity: {
+ type: String,
+ enum: [...AUDIT_SEVERITIES],
+ required: true,
+ immutable: true,
+ },
+ actor: { type: actorSchema, required: true, immutable: true },
+ target: { type: targetSchema, required: true, immutable: true },
+ /** Event-specific payload (e.g. `{ capability }` for grants). Open by design;
+ * never store raw prompts, secrets, or full tool outputs here. */
+ metadata: { type: Schema.Types.Mixed, required: false, immutable: true },
+ context: { type: contextSchema, required: false, immutable: true },
+ /**
+ * Platform-level entries MUST omit this field entirely — never set it to null.
+ * Tenant-scoped queries derive `chainKey` from `tenantId`; absence here maps
+ * to the platform chain.
+ */
+ tenantId: {
+ type: String,
+ required: false,
+ immutable: true,
+ validate: {
+ validator: (v: unknown) => typeof v === 'string' && v.trim().length > 0,
+ message:
+ 'tenantId must be a non-empty string or omitted entirely — never null, empty, or a non-string value',
+ },
+ },
+ chainKey: { type: String, required: true, immutable: true },
+ seq: { type: Number, required: true, immutable: true },
+ prevHash: { type: String, required: true, immutable: true },
+ hash: { type: String, required: true, immutable: true },
+ createdAt: { type: Date, required: true, immutable: true },
+});
+
+const APPEND_ONLY_MESSAGE = 'AuditLog is append-only — updates and deletes are forbidden';
+
+/** Block every query-level update path. */
+auditLogSchema.pre(
+ ['updateOne', 'updateMany', 'findOneAndUpdate', 'findOneAndReplace', 'replaceOne'],
+ function (next) {
+ next(new Error(APPEND_ONLY_MESSAGE));
+ },
+);
+
+/** Block every query-level delete path. */
+auditLogSchema.pre(['deleteOne', 'deleteMany', 'findOneAndDelete'], function (next) {
+ next(new Error(APPEND_ONLY_MESSAGE));
+});
+
+/**
+ * Mongoose registers `deleteOne` / `updateOne` pre-hooks as query middleware
+ * by default, leaving `Document.prototype.deleteOne()` and
+ * `Document.prototype.updateOne()` as escape hatches: a caller holding a loaded
+ * doc could invoke either on the instance and bypass the query-level hooks.
+ * The explicit `{ document: true, query: false }` registrations close both.
+ */
+auditLogSchema.pre('deleteOne', { document: true, query: false }, function (next) {
+ next(new Error(APPEND_ONLY_MESSAGE));
+});
+auditLogSchema.pre('updateOne', { document: true, query: false }, function (next) {
+ next(new Error(APPEND_ONLY_MESSAGE));
+});
+
+/** Document-level `save` is allowed for new docs only; a second save mutates. */
+auditLogSchema.pre('save', function (next) {
+ if (!this.isNew) {
+ next(new Error(APPEND_ONLY_MESSAGE));
+ return;
+ }
+ next();
+});
+
+/**
+ * `Model.bulkWrite()` dispatches update/delete operations through the raw driver
+ * and skips the query/document middleware above. Block it wholesale: audit rows
+ * are only ever written via `recordAuditEntry` (`Model.create`), and a bulk
+ * insert would also break the sequential hash chain, so there is no legitimate
+ * bulkWrite path. The privileged retention purge uses `Model.collection` and is
+ * unaffected by this hook.
+ */
+auditLogSchema.pre('bulkWrite', function (next) {
+ next(new Error(APPEND_ONLY_MESSAGE));
+});
+
+/**
+ * `Model.insertMany()` is another bulk path that skips the document `save`
+ * hook, so it could insert rows with attacker-chosen `seq`/`prevHash`/`hash`
+ * and poison the chain. Entries are only ever written one-at-a-time via
+ * `recordAuditEntry` (`Model.create`), so block bulk inserts outright.
+ */
+auditLogSchema.pre('insertMany', function (next) {
+ next(new Error(APPEND_ONLY_MESSAGE));
+});
+
+/**
+ * Unique per-chain sequence. This is both the keyset-pagination key and the
+ * integrity backstop: concurrent appends race to claim the next `seq`, one wins,
+ * and the losers retry — so the chain can never fork.
+ */
+auditLogSchema.index({ chainKey: 1, seq: 1 }, { unique: true });
+
+/** Primary listing: newest-first within a chain, bounded by a date window. */
+auditLogSchema.index({ chainKey: 1, createdAt: -1, seq: -1 });
+
+/** Faceted reads. */
+auditLogSchema.index({ chainKey: 1, category: 1, createdAt: -1 });
+auditLogSchema.index({ chainKey: 1, 'target.type': 1, 'target.id': 1, createdAt: -1 });
+
+export default auditLogSchema;
diff --git a/packages/data-schemas/src/schema/index.ts b/packages/data-schemas/src/schema/index.ts
index 0dfd4dcb30..08471bf5c8 100644
--- a/packages/data-schemas/src/schema/index.ts
+++ b/packages/data-schemas/src/schema/index.ts
@@ -28,4 +28,5 @@ export { default as userSchema } from './user';
export { default as memorySchema } from './memory';
export { default as groupSchema } from './group';
export { default as systemGrantSchema } from './systemGrant';
+export { default as auditLogSchema } from './auditLog';
export { default as configSchema } from './config';
diff --git a/packages/data-schemas/src/types/admin.ts b/packages/data-schemas/src/types/admin.ts
index 755bb7a2e6..0fcbf450e7 100644
--- a/packages/data-schemas/src/types/admin.ts
+++ b/packages/data-schemas/src/types/admin.ts
@@ -65,8 +65,109 @@ export type AdminConfigDeleteResponse = {
success: boolean;
};
-/** Audit action types for grant changes. */
-export type AuditAction = 'grant_assigned' | 'grant_removed';
+/* ── Audit log taxonomy ─────────────────────────────────────────────── */
+
+/**
+ * High-level domains an audit entry can belong to. The audit log is a
+ * general-purpose, append-only compliance record; new domains (agent runs,
+ * tool/MCP calls, config and permission changes, approvals) are added here as
+ * the surface grows, without reshaping the record.
+ */
+export const AUDIT_CATEGORIES = [
+ 'grant',
+ 'agent_run',
+ 'tool_call',
+ 'mcp',
+ 'config',
+ 'permission',
+ 'auth',
+ 'approval',
+] as const;
+export type AuditCategory = (typeof AUDIT_CATEGORIES)[number];
+
+/**
+ * Single source of truth for the audit-action enum. Actions are namespaced
+ * `<category>.<verb>` so the registry stays readable as it grows and every
+ * action maps unambiguously to a category. The Mongoose schema enum and the
+ * HTTP handler's whitelist both consume this constant so they cannot drift.
+ */
+export const AUDIT_ACTIONS = ['grant.assigned', 'grant.removed'] as const;
+export type AuditAction = (typeof AUDIT_ACTIONS)[number];
+
+/** Maps each action to its category so writers never pass both. */
+export const AUDIT_ACTION_CATEGORY: Record<AuditAction, AuditCategory> = {
+ 'grant.assigned': 'grant',
+ 'grant.removed': 'grant',
+};
+
+/** Result of the audited operation. Kept first-class instead of being encoded
+ * into the action so `allowed` vs `denied` vs `failed` is queryable. */
+export const AUDIT_OUTCOMES = ['success', 'failure', 'denied', 'pending'] as const;
+export type AuditOutcome = (typeof AUDIT_OUTCOMES)[number];
+
+/** Coarse severity for SIEM routing and alerting. */
+export const AUDIT_SEVERITIES = ['info', 'warning', 'critical'] as const;
+export type AuditSeverity = (typeof AUDIT_SEVERITIES)[number];
+
+/**
+ * Who initiated the action. Non-human actors are first-class: a scheduled job,
+ * an agent acting autonomously, an internal service, or a webhook are all
+ * representable without forcing a `User` id.
+ */
+export const AUDIT_ACTOR_TYPES = [
+ 'user',
+ 'system',
+ 'agent',
+ 'service',
+ 'schedule',
+ 'webhook',
+ 'api',
+] as const;
+export type AuditActorType = (typeof AUDIT_ACTOR_TYPES)[number];
+
+/** Primitive metadata values; event-specific payload is a flat string-keyed map
+ * (e.g. `{ capability }` for grants, `{ runId, triggerType }` for agent runs). */
+export type AuditMetadataValue = string | number | boolean | null;
+export type AuditMetadata = Record<string, AuditMetadataValue>;
+
+/** Denormalized actor identity captured at write time. */
+export type AuditActor = {
+ type: AuditActorType;
+ /** Stable id (user id, service-account id, agent id); absent for anonymous
+ * system events. */
+ id?: string;
+ /** Display name captured at write time so the record stays readable after the
+ * underlying principal is renamed or deleted. */
+ name: string;
+};
+
+/** Generic target of the action — not principal-locked, so it can describe a
+ * role, agent, MCP server, config section, etc. */
+export type AuditTarget = {
+ type: string;
+ id?: string;
+ name?: string;
+};
+
+/** Request context for forensic joins and SIEM correlation. */
+export type AuditContext = {
+ /** Correlation id (`x-request-id` / `x-correlation-id`). */
+ requestId?: string;
+ ip?: string;
+ userAgent?: string;
+ sessionId?: string;
+};
+
+/** Per-entry tamper-evidence surfaced to readers. The full chain is verifiable
+ * via the verify endpoint. */
+export type AuditIntegrity = {
+ /** Monotonic per-chain sequence number (1-based). */
+ seq: number;
+ /** SHA-256 of this entry's canonical content linked to `prevHash`. */
+ hash: string;
+ /** Hash of the previous entry in the chain (genesis links to a zero hash). */
+ prevHash: string;
+};
/** SystemGrant document as returned by the admin API. */
export type AdminSystemGrant = {
@@ -79,16 +180,22 @@ export type AdminSystemGrant = {
expiresAt?: string;
};
-/** Audit log entry for grant changes as returned by the admin API. */
+/** Audit log entry as returned by the admin API. */
export type AdminAuditLogEntry = {
id: string;
+ schemaVersion: number;
+ category: AuditCategory;
action: AuditAction;
- actorId: string;
- actorName: string;
- targetPrincipalType: PrincipalType;
- targetPrincipalId: string;
- targetName: string;
- capability: string;
+ outcome: AuditOutcome;
+ severity: AuditSeverity;
+ actor: AuditActor;
+ target: AuditTarget;
+ metadata?: AuditMetadata;
+ context?: AuditContext;
+ /** Absent = platform-operator entry; present = tenant-scoped entry. */
+ tenantId?: string;
+ integrity: AuditIntegrity;
+ /** `createdAt` as an ISO 8601 string. */
timestamp: string;
};
diff --git a/packages/data-schemas/src/types/auditLog.ts b/packages/data-schemas/src/types/auditLog.ts
new file mode 100644
index 0000000000..f1f6a94dda
--- /dev/null
+++ b/packages/data-schemas/src/types/auditLog.ts
@@ -0,0 +1,190 @@
+import type { Document, Types } from 'mongoose';
+import type {
+ AdminAuditLogEntry,
+ AuditAction,
+ AuditActor,
+ AuditActorType,
+ AuditCategory,
+ AuditContext,
+ AuditIntegrity,
+ AuditMetadata,
+ AuditOutcome,
+ AuditSeverity,
+ AuditTarget,
+} from './admin';
+
+/**
+ * AuditLog is an append-only, hash-chained compliance record. Enforcement lives
+ * in `~/schema/auditLog` (immutable fields, pre-update/delete/save hooks) and in
+ * `~/methods/auditLog` (per-chain hash linking + a unique `{ chainKey, seq }`
+ * index that serializes concurrent appends). `createdAt` is set explicitly by
+ * the writer so it is covered by the entry hash.
+ */
+export type AuditLog = {
+ /** Record-format version, so future migrations can interpret older rows. */
+ schemaVersion: number;
+ category: AuditCategory;
+ action: AuditAction;
+ outcome: AuditOutcome;
+ severity: AuditSeverity;
+ actor: AuditActor;
+ target: AuditTarget;
+ metadata?: AuditMetadata;
+ context?: AuditContext;
+ /** Absent = platform-level entry; present = tenant-scoped entry. */
+ tenantId?: string;
+ /**
+ * Always present; equals `tenantId` or the platform sentinel. The hash chain
+ * and keyset pagination are scoped to this key, and `{ chainKey, seq }` is the
+ * unique index that serializes appends.
+ */
+ chainKey: string;
+ /** Monotonic per-chain sequence number (1-based). */
+ seq: number;
+ /** Hash of the previous entry in the chain; genesis links to the zero hash. */
+ prevHash: string;
+ /** SHA-256 over this entry's canonical content (including `seq` and `prevHash`). */
+ hash: string;
+ createdAt: Date;
+};
+
+export type IAuditLog = AuditLog &
+ Document & {
+ _id: Types.ObjectId;
+ };
+
+/** Actor as accepted by writers; `id` may be an ObjectId for convenience. */
+export interface AuditActorInput {
+ type: AuditActorType;
+ id?: string | Types.ObjectId;
+ name: string;
+}
+
+/** Target as accepted by writers; `id` may be an ObjectId for convenience. */
+export interface AuditTargetInput {
+ type: string;
+ id?: string | Types.ObjectId;
+ name?: string;
+}
+
+export interface RecordAuditEntryInput {
+ action: AuditAction;
+ /** Derived from `action` when omitted. */
+ category?: AuditCategory;
+ /** Defaults to `'success'`. */
+ outcome?: AuditOutcome;
+ /** Defaults to `'warning'` for `failure`/`denied`, else `'info'`. */
+ severity?: AuditSeverity;
+ actor: AuditActorInput;
+ target: AuditTargetInput;
+ metadata?: AuditMetadata;
+ context?: AuditContext;
+ tenantId?: string;
+}
+
+/** Options that shape a single audit write. */
+export interface RecordAuditEntryOptions {
+ /**
+ * When true, a failed write throws instead of resolving to `null`. Callers
+ * that must not proceed without a durable audit record opt in here; the
+ * default is fail-open so audit emission never blocks a privileged operation.
+ */
+ failClosed?: boolean;
+}
+
+export interface AuditLogFilters {
+ search?: string;
+ category?: AuditCategory[];
+ action?: AuditAction[];
+ outcome?: AuditOutcome[];
+ severity?: AuditSeverity[];
+ /** Exact match on `actor.type`. */
+ actorType?: AuditActorType;
+ /** Case-insensitive substring match against the denormalized `actor.name`. */
+ actorQuery?: string;
+ /** Exact match on `target.type`. */
+ targetType?: string;
+ /** Case-insensitive substring match against the denormalized `target.name`. */
+ targetQuery?: string;
+ /** Case-insensitive substring match against `metadata.capability`. */
+ capability?: string;
+ from?: Date;
+ to?: Date;
+ /** Offset pagination (legacy / random-access). Prefer `cursor`. */
+ offset?: number;
+ limit?: number;
+ /**
+ * Keyset cursor: the `seq` of the last entry from the previous page. Results
+ * are newest-first, so the next page is `seq < cursor`. Stable under
+ * concurrent appends, unlike `offset`.
+ */
+ cursor?: number;
+}
+
+export interface AuditLogPage {
+ entries: AdminAuditLogEntry[];
+ total: number;
+ /** Pass as `cursor` to fetch the next page; `null` when the page is the last. */
+ nextCursor: number | null;
+}
+
+/** Outcome of verifying a chain's tamper-evidence. */
+export interface AuditChainVerification {
+ ok: boolean;
+ chainKey: string;
+ /** Number of entries inspected. */
+ checked: number;
+ /** First `seq` where the chain broke (gap, broken link, or hash mismatch). */
+ brokenAt?: number;
+ reason?: string;
+ /** Earliest/latest `seq` present. `firstSeq > 1` indicates a purged prefix. */
+ range?: { firstSeq: number; lastSeq: number };
+}
+
+export interface PurgeAuditLogOptions {
+ /** Delete entries strictly older than this instant (a contiguous prefix). */
+ before: Date;
+ /** Required safety latch; the purge is a no-op unless explicitly confirmed. */
+ confirm: boolean;
+}
+
+/** A trusted boundary marker proving a prefix was purged by an authorized
+ * retention run rather than deleted by an attacker. Persisted by the caller
+ * (e.g. alongside retention-job records) and passed back to `verifyAuditChain`. */
+export interface AuditCheckpoint {
+ /** Highest `seq` that was purged; the chain resumes at `throughSeq + 1`. */
+ throughSeq: number;
+ /** Hash of the last purged entry === `prevHash` of the new earliest entry. */
+ prevHash: string;
+}
+
+export interface PurgeAuditLogResult {
+ deletedCount: number;
+ /** The boundary the verifier must be given to accept the now-shorter chain.
+ * Absent when the chain is now empty or nothing was purged. */
+ checkpoint?: AuditCheckpoint;
+}
+
+export interface VerifyAuditChainOptions {
+ /** When the chain no longer starts at `seq: 1` (a prefix was purged), the
+ * verifier requires this boundary to distinguish an authorized retention purge
+ * from an attacker deleting the oldest rows. Without it, a non-genesis start
+ * fails verification rather than being silently trusted. */
+ trustedCheckpoint?: AuditCheckpoint;
+}
+
+/** Re-exported so consumers can import the entry shape and its supporting types
+ * from one module. */
+export type {
+ AdminAuditLogEntry,
+ AuditAction,
+ AuditActor,
+ AuditActorType,
+ AuditCategory,
+ AuditContext,
+ AuditIntegrity,
+ AuditMetadata,
+ AuditOutcome,
+ AuditSeverity,
+ AuditTarget,
+};
diff --git a/packages/data-schemas/src/types/index.ts b/packages/data-schemas/src/types/index.ts
index da4f42c435..3dc5228532 100644
--- a/packages/data-schemas/src/types/index.ts
+++ b/packages/data-schemas/src/types/index.ts
@@ -31,6 +31,7 @@ export * from './skillSync';
export * from './accessRole';
export * from './aclEntry';
export * from './systemGrant';
+export * from './auditLog';
export * from './group';
/* Config */
export * from './config';