@stackone/audit
v1.11.0
Published
Audit logging client for StackOne projects. Records events to Kafka and queries them via Tinybird OLAP database.
Keywords
Readme
@stackone/audit
Audit 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.
Features
- 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
AuditEventtype - Error Handling: Graceful error handling with detailed logging
Requirements
Please check the root README for requirements.
Installation
npm install @stackone/auditUsage
Basic Setup
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();Recording Events
Basic Event
await client.recordEvent({
service: 'idp',
organizationId: 'org-123',
userId: 'user-456',
action: 'user.login',
success: true
});Event with Details
await client.recordEvent({
service: 'api',
organizationId: 'org-123',
action: 'document.created',
details: {
documentId: 'doc-789',
documentType: 'invoice',
fileSize: 1024
}
});Disabled Event (for testing)
await client.recordEvent(event, { enabled: false });Querying Events
Query by Single Organization
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 eventsQuery Multiple Actions with Date Range
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}`);
console.log(`Showing ${result.events.length} events`);Query Multiple Organizations and Users
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 countQuery Failed Actions
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`);API Reference
AuditClient
Main client for recording and querying audit events.
Constructor Options
kafkaClientConfig- Kafka broker configurationolapConfig- OLAP database (Tinybird) configurationbaseUrl- Tinybird API base URLtoken- Tinybird authentication token
logger- Logger instance for audit operationsgetKafkaClient- Custom Kafka client builder (optional, for testing)getHttpClient- Custom HTTP client builder (optional, for testing)
Methods
initialize(): Promise<void>
Initializes the audit client by connecting to Kafka. Must be called before recording events.
recordEvent(event: AuditEvent, options?: AuditOptions): Promise<void>
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<AuditQueryResult>
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:
Errorif HTTP client is not configured or OLAP token is missingZodErrorif the response fails schema validation
AuditEvent
Type representing an audit event.
type AuditEvent = {
eventId?: string;
service: string;
organizationId?: string;
userId?: string;
action?: string;
subAction?: string;
success?: boolean;
details?: Record<string, unknown>;
eventTime?: Date;
};AuditQueryResult
Type representing the result of a query operation.
type AuditQueryResult = {
events: AuditEvent[];
total: number;
pageNumber: number;
pageSize: number;
};Available commands
# clean build output
$ npm run clean# build package
$ npm run build# run tests
$ npm run test# run tests on watch mode
$ npm run test:watch# run linter
$ npm run lint# run linter and try to fix any error
$ npm run lint:fix