forked from Talenttrust/Talenttrust-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.ts
More file actions
208 lines (193 loc) · 5.58 KB
/
Copy pathservice.ts
File metadata and controls
208 lines (193 loc) · 5.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/**
* @module audit/service
* @description High-level audit logging service.
*
* Provides a clean API for application code to emit audit events without
* coupling directly to the store implementation. All sensitive state changes
* (contract lifecycle, payments, user management, auth events) must go through
* this service.
*
* Security notes:
* - Callers MUST sanitise metadata before passing it in — no raw PII.
* - Logging failures are caught and reported via console.error to avoid
* disrupting the primary request flow, but they are also re-thrown in
* strict mode so tests can assert on them.
*/
import type { AuditEntry, AuditQuery, AuditSeverity, CreateAuditEntryInput, IntegrityReport, AuditQueryResult } from './types';
import type { AuditAction } from './types';
import { createDefaultAuditRepository, type AuditLogRepository } from './repository';
export interface AuditServiceOptions {
/** Reserved for future use. */
_reserved?: never;
}
/**
* AuditService — application-level facade over AuditStore.
*
* @example
* ```ts
* import { auditService } from './audit/service';
*
* await auditService.log({
* action: 'CONTRACT_CREATED',
* severity: 'INFO',
* actor: req.user.id,
* resource: 'contract',
* resourceId: contract.id,
* metadata: { clientId: contract.clientId },
* ipAddress: req.ip,
* correlationId: req.headers['x-correlation-id'] as string,
* });
* ```
*/
export class AuditService {
constructor(
private readonly repository: AuditLogRepository = createDefaultAuditRepository(),
private readonly options: AuditServiceOptions = {},
) {}
/**
* Records an audit event.
*
* @param input - Event details. metadata must be pre-sanitised.
* @returns The persisted, immutable AuditEntry.
* @throws Only when options.strict is true and the store throws.
*/
log(input: CreateAuditEntryInput): AuditEntry {
try {
return this.repository.append(input);
} catch (err) {
console.error('[AuditService] Failed to persist audit entry:', err);
throw err;
}
}
/**
* Convenience wrapper for contract lifecycle events.
*/
logContractEvent(
action: Extract<AuditAction, `CONTRACT_${string}`>,
actor: string,
contractId: string,
metadata: Record<string, unknown> = {},
context: { ipAddress?: string; correlationId?: string } = {},
): AuditEntry {
return this.log({
action,
severity: 'INFO',
actor,
resource: 'contract',
resourceId: contractId,
metadata,
...context,
});
}
/**
* Convenience wrapper for payment events.
* Payment events are always CRITICAL severity.
*/
logPaymentEvent(
action: Extract<AuditAction, `PAYMENT_${string}`>,
actor: string,
paymentId: string,
metadata: Record<string, unknown> = {},
context: { ipAddress?: string; correlationId?: string } = {},
): AuditEntry {
return this.log({
action,
severity: 'CRITICAL',
actor,
resource: 'payment',
resourceId: paymentId,
metadata,
...context,
});
}
/**
* Convenience wrapper for authentication events.
* AUTH_FAILED is WARNING; others are INFO.
*/
logAuthEvent(
action: Extract<AuditAction, `AUTH_${string}`>,
actor: string,
metadata: Record<string, unknown> = {},
context: { ipAddress?: string; correlationId?: string } = {},
): AuditEntry {
const severity: AuditSeverity = action === 'AUTH_FAILED' ? 'WARNING' : 'INFO';
return this.log({
action,
severity,
actor,
resource: 'auth',
resourceId: actor,
metadata,
...context,
});
}
/**
* Convenience wrapper for user management events.
* USER_DELETED is WARNING; others are INFO.
*/
logUserEvent(
action: Extract<AuditAction, `USER_${string}`>,
actor: string,
targetUserId: string,
metadata: Record<string, unknown> = {},
context: { ipAddress?: string; correlationId?: string } = {},
): AuditEntry {
const severity: AuditSeverity = action === 'USER_DELETED' ? 'WARNING' : 'INFO';
return this.log({
action,
severity,
actor,
resource: 'user',
resourceId: targetUserId,
metadata,
...context,
});
}
/**
* Queries the audit log with optional filters.
*
* @param query - Filter and pagination options.
* @returns Matching entries in insertion order.
*/
query(query: AuditQuery = {}): AuditEntry[] {
return this.repository.query(query);
}
/**
* Queries the audit log with cursor-based pagination.
*
* @param query - Filter and pagination options including cursor.
* @returns Paginated result with entries and next cursor.
*/
queryWithCursor(query: AuditQuery = {}): AuditQueryResult {
return this.repository.queryWithCursor(query);
}
/**
* Streams audit entries for export use cases without loading all rows.
*/
stream(query: AuditQuery = {}): IterableIterator<AuditEntry> {
return this.repository.stream(query);
}
/**
* Retrieves a single audit entry by ID.
*/
getById(id: string): AuditEntry | undefined {
return this.repository.getById(id);
}
/**
* Returns the total number of audit entries.
*/
count(): number {
return this.repository.count();
}
/**
* Verifies the integrity of the entire hash chain.
* Should be called by a scheduled monitoring job.
*
* @returns IntegrityReport — escalate immediately if valid === false.
*/
verifyIntegrity(): IntegrityReport {
return this.repository.verifyIntegrity();
}
}
/** Singleton service instance. */
export const auditService = new AuditService();