Audit logging client for StackOne projects. Records events to Kafka and queries them via Tinybird OLAP database.
npm install @stackone/auditAudit logging client for StackOne projects. Records events to Kafka and queries them via Tinybird OLAP database.
This package uses the tech stack provided by the Connect Monorepo global setup. Please check the root README for more information.
- Event Recording: Send audit events to Kafka with automatic enrichment (eventId, eventTime)
- Event Querying: Query audit events from Tinybird with flexible filtering
- Array Parameter Support: Filter by multiple values for organizationId, userId, action, and more
- Type Safety: Full TypeScript support with a single AuditEvent type
- Error Handling: Graceful error handling with detailed logging
Please check the root README for requirements.
``bash`
npm install @stackone/audit
`typescript
import { AuditClient } from '@stackone/audit';
const client = new AuditClient({
kafkaClientConfig: { brokers: ['localhost:9092'] },
olapConfig: {
baseUrl: 'https://api.tinybird.co',
token: process.env.TINYBIRD_TOKEN
},
logger: myLogger
});
await client.initialize();
`
#### Basic Event
`typescript`
await client.recordEvent({
service: 'idp',
organizationId: 'org-123',
userId: 'user-456',
action: 'user.login',
success: true
});
#### Event with Details
`typescript`
await client.recordEvent({
service: 'api',
organizationId: 'org-123',
action: 'document.created',
details: {
documentId: 'doc-789',
documentType: 'invoice',
fileSize: 1024
}
});
#### Disabled Event (for testing)
`typescript`
await client.recordEvent(event, { enabled: false });
#### Query by Single Organization
`typescript
const result = await client.queryEvents({
organizationId: 'org-123',
pageSize: 50
});
console.log(Found ${result.total} events, showing page ${result.pageNumber});`
console.log(result.events); // Array of events
#### Query Multiple Actions with Date Range
`typescript
const result = await client.queryEvents({
organizationId: 'org-123',
action: ['user.login', 'user.logout'],
startTime: new Date('2024-01-01'),
endTime: new Date('2024-01-31'),
pageNumber: 1,
pageSize: 100
});
console.log(Total matching events: ${result.total});Showing ${result.events.length} events
console.log();`
#### Query Multiple Organizations and Users
`typescript
const result = await client.queryEvents({
organizationId: ['org-123', 'org-456'],
userId: ['user-1', 'user-2', 'user-3'],
success: true
});
console.log(result.events); // Matching events
console.log(result.total); // Total count
`
#### Query Failed Actions
`typescript
const result = await client.queryEvents({
service: 'idp',
success: false,
startTime: new Date(Date.now() - 24 60 60 * 1000) // Last 24 hours
});
console.log(Found ${result.total} failures);`
Main client for recording and querying audit events.
#### Constructor Options
- kafkaClientConfig - Kafka broker configurationolapConfig
- - OLAP database (Tinybird) configurationbaseUrl
- - Tinybird API base URLtoken
- - Tinybird authentication tokenlogger
- - Logger instance for audit operationsgetKafkaClient
- - Custom Kafka client builder (optional, for testing)getHttpClient
- - Custom HTTP client builder (optional, for testing)
#### Methods
##### initialize(): Promise
Initializes the audit client by connecting to Kafka. Must be called before recording events.
##### recordEvent(event: AuditEvent, options?: AuditOptions): Promise
Records an audit event to Kafka. The event is automatically enriched with eventId and eventTime.
Event Fields:
- service (required) - Name of the service generating the eventorganizationId
- (optional) - Organization identifieruserId
- (optional) - User identifieraction
- (optional) - Action identifier (e.g., 'user.login', 'document.created')subAction
- (optional) - Sub-action identifiersuccess
- (optional) - Whether the action was successfuldetails
- (optional) - Additional event metadataeventTime
- (optional) - Timestamp of the event (defaults to now)
Options:
- enabled (default: true) - Whether to actually send the event
##### queryEvents(query: AuditQuery): Promise
Queries audit events from the OLAP database. Returns events that match ALL specified filters (AND logic).
Query Filters:
- service - Filter by service name(s) (string or string[])organizationId
- - Filter by organization ID(s) (string or string[])userId
- - Filter by user ID(s) (string or string[])action
- - Filter by action(s) (string or string[])subAction
- - Filter by sub-action(s) (string or string[])success
- - Filter by success status (boolean)startTime
- - Filter events after this timestamp (inclusive)endTime
- - Filter events before this timestamp (inclusive)pageNumber
- - Page number for pagination (1-indexed)pageSize
- - Number of events per page
Returns:
AuditQueryResult containing:events
- - Array of matching audit eventstotal
- - Total count of matching events (before pagination)pageNumber
- - Current page numberpageSize
- - Number of events per page
Throws:
- Error if HTTP client is not configured or OLAP token is missingZodError
- if the response fails schema validation
Type representing an audit event.
`typescript`
type AuditEvent = {
eventId?: string;
service: string;
organizationId?: string;
userId?: string;
action?: string;
subAction?: string;
success?: boolean;
details?: Record
eventTime?: Date;
};
Type representing the result of a query operation.
`typescript`
type AuditQueryResult = {
events: AuditEvent[];
total: number;
pageNumber: number;
pageSize: number;
};
`bash`clean build output
$ npm run clean
`bash`build package
$ npm run build
`bash`run tests
$ npm run test
`bash`run tests on watch mode
$ npm run test:watch
`bash`run linter
$ npm run lint
`bash``run linter and try to fix any error
$ npm run lint:fix