@geekmidas/audit 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/TECHNICAL.md +937 -0
- package/dist/Auditor-CZ8lkASv.d.cts +260 -0
- package/dist/Auditor-ii62d_pF.d.mts +260 -0
- package/dist/Auditor.cjs +0 -0
- package/dist/Auditor.d.cts +2 -0
- package/dist/Auditor.d.mts +2 -0
- package/dist/Auditor.mjs +0 -0
- package/dist/DefaultAuditor-1HDUGMub.cjs +124 -0
- package/dist/DefaultAuditor-1HDUGMub.cjs.map +1 -0
- package/dist/DefaultAuditor-B9Unin1g.d.mts +59 -0
- package/dist/DefaultAuditor-BAVnNmRh.mjs +96 -0
- package/dist/DefaultAuditor-BAVnNmRh.mjs.map +1 -0
- package/dist/DefaultAuditor-Dqc4UZA1.d.cts +59 -0
- package/dist/DefaultAuditor.cjs +3 -0
- package/dist/DefaultAuditor.d.cts +4 -0
- package/dist/DefaultAuditor.d.mts +4 -0
- package/dist/DefaultAuditor.mjs +3 -0
- package/dist/index.cjs +3 -0
- package/dist/index.d.cts +4 -0
- package/dist/index.d.mts +4 -0
- package/dist/index.mjs +3 -0
- package/dist/kysely.cjs +193 -0
- package/dist/kysely.cjs.map +1 -0
- package/dist/kysely.d.cts +165 -0
- package/dist/kysely.d.mts +165 -0
- package/dist/kysely.mjs +191 -0
- package/dist/kysely.mjs.map +1 -0
- package/dist/storage-BtFY7Rha.d.cts +102 -0
- package/dist/storage-DnAMfOA7.d.mts +102 -0
- package/dist/storage.cjs +0 -0
- package/dist/storage.d.cts +3 -0
- package/dist/storage.d.mts +3 -0
- package/dist/storage.mjs +0 -0
- package/dist/types.cjs +0 -0
- package/dist/types.d.cts +2 -0
- package/dist/types.d.mts +2 -0
- package/dist/types.mjs +0 -0
- package/package.json +34 -0
- package/src/Auditor.ts +157 -0
- package/src/DefaultAuditor.ts +141 -0
- package/src/__tests__/DefaultAuditor.spec.ts +420 -0
- package/src/__tests__/KyselyAuditStorage.integration.spec.ts +517 -0
- package/src/__tests__/KyselyAuditStorage.spec.ts +359 -0
- package/src/index.ts +23 -0
- package/src/kysely.ts +391 -0
- package/src/storage.ts +101 -0
- package/src/types.ts +147 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { AuditRecord } from "./Auditor-ii62d_pF.mjs";
|
|
2
|
+
import { AuditQueryOptions, AuditStorage } from "./storage-DnAMfOA7.mjs";
|
|
3
|
+
import { ControlledTransaction, IsolationLevel, Kysely, Transaction } from "kysely";
|
|
4
|
+
|
|
5
|
+
//#region src/kysely.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Minimal interface for transaction-aware audit flushing.
|
|
9
|
+
* Use this when you need to flush audits within a database transaction.
|
|
10
|
+
*
|
|
11
|
+
* @template TTransaction - Transaction type (e.g., Kysely Transaction)
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import { withAuditableTransaction } from '@geekmidas/audit/kysely';
|
|
16
|
+
* import type { TransactionAwareAuditor } from '@geekmidas/audit/kysely';
|
|
17
|
+
*
|
|
18
|
+
* const result = await withAuditableTransaction(
|
|
19
|
+
* db,
|
|
20
|
+
* auditor as TransactionAwareAuditor<Transaction<DB>>,
|
|
21
|
+
* async (trx) => {
|
|
22
|
+
* // Your transactional operations
|
|
23
|
+
* return result;
|
|
24
|
+
* },
|
|
25
|
+
* );
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
interface TransactionAwareAuditor<TTransaction = unknown> {
|
|
29
|
+
/** Register the transaction with the auditor for use during flush */
|
|
30
|
+
setTransaction(trx: TTransaction): void;
|
|
31
|
+
/** Flush all pending audits, optionally within a transaction */
|
|
32
|
+
flush(trx?: TTransaction): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
interface TransactionSettings {
|
|
35
|
+
isolationLevel?: IsolationLevel;
|
|
36
|
+
}
|
|
37
|
+
type DatabaseConnection<T> = ControlledTransaction<T> | Kysely<T> | Transaction<T>;
|
|
38
|
+
/**
|
|
39
|
+
* Execute a callback within a database transaction with automatic audit handling.
|
|
40
|
+
*
|
|
41
|
+
* This wrapper ensures that:
|
|
42
|
+
* 1. The transaction is automatically registered with the auditor
|
|
43
|
+
* 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits
|
|
44
|
+
* 3. If audit flush fails, the entire transaction rolls back
|
|
45
|
+
* 4. If the callback fails, audits are NOT written (atomic consistency)
|
|
46
|
+
*
|
|
47
|
+
* **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)
|
|
48
|
+
* are processed AFTER the handler returns, so they run outside this transaction.
|
|
49
|
+
* If you need all audits to be atomic with your database operations, use manual
|
|
50
|
+
* audits via `auditor.audit()` inside this wrapper.
|
|
51
|
+
*
|
|
52
|
+
* @param db - Database connection (Kysely, Transaction, or ControlledTransaction)
|
|
53
|
+
* @param auditor - Auditor instance that will receive the transaction
|
|
54
|
+
* @param cb - Callback to execute within the transaction
|
|
55
|
+
* @param settings - Optional transaction settings (isolation level)
|
|
56
|
+
* @returns The result of the callback
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```typescript
|
|
60
|
+
* import { withAuditableTransaction } from '@geekmidas/audit/kysely';
|
|
61
|
+
*
|
|
62
|
+
* const result = await withAuditableTransaction(
|
|
63
|
+
* services.database,
|
|
64
|
+
* auditor,
|
|
65
|
+
* async (trx) => {
|
|
66
|
+
* const user = await trx
|
|
67
|
+
* .insertInto('users')
|
|
68
|
+
* .values(data)
|
|
69
|
+
* .returningAll()
|
|
70
|
+
* .executeTakeFirstOrThrow();
|
|
71
|
+
*
|
|
72
|
+
* // Manual audits are atomic with the transaction
|
|
73
|
+
* auditor.audit('user.created', { userId: user.id, email: user.email });
|
|
74
|
+
*
|
|
75
|
+
* return user;
|
|
76
|
+
* },
|
|
77
|
+
* );
|
|
78
|
+
* // Audits are automatically flushed inside the transaction before commit
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
declare function withAuditableTransaction<DB, T>(db: DatabaseConnection<DB>, auditor: TransactionAwareAuditor<Transaction<DB>>, cb: (trx: Transaction<DB>) => Promise<T>, settings?: TransactionSettings): Promise<T>;
|
|
82
|
+
/**
|
|
83
|
+
* Database table interface for audit records.
|
|
84
|
+
* Use this to define your audit_logs table in your Kysely database schema.
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* ```typescript
|
|
88
|
+
* interface Database {
|
|
89
|
+
* audit_logs: AuditLogTable;
|
|
90
|
+
* // ... other tables
|
|
91
|
+
* }
|
|
92
|
+
* ```
|
|
93
|
+
*/
|
|
94
|
+
interface AuditLogTable {
|
|
95
|
+
id: string;
|
|
96
|
+
type: string;
|
|
97
|
+
operation: string;
|
|
98
|
+
table: string | null;
|
|
99
|
+
entityId: string | null;
|
|
100
|
+
oldValues: string | null;
|
|
101
|
+
newValues: string | null;
|
|
102
|
+
payload: string | null;
|
|
103
|
+
timestamp: Date;
|
|
104
|
+
actorId: string | null;
|
|
105
|
+
actorType: string | null;
|
|
106
|
+
actorData: string | null;
|
|
107
|
+
metadata: string | null;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Configuration for KyselyAuditStorage.
|
|
111
|
+
*/
|
|
112
|
+
interface KyselyAuditStorageConfig<DB> {
|
|
113
|
+
/** Kysely database instance */
|
|
114
|
+
db: Kysely<DB>;
|
|
115
|
+
/** Table name for audit logs (must be a key in DB that extends AuditLogTable) */
|
|
116
|
+
tableName: keyof DB & string;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Kysely-based audit storage implementation.
|
|
120
|
+
* Stores audit records in a database table using Kysely.
|
|
121
|
+
*
|
|
122
|
+
* @template DB - Your Kysely database schema
|
|
123
|
+
*
|
|
124
|
+
* @example
|
|
125
|
+
* ```typescript
|
|
126
|
+
* interface Database {
|
|
127
|
+
* audit_logs: AuditLogTable;
|
|
128
|
+
* }
|
|
129
|
+
*
|
|
130
|
+
* const storage = new KyselyAuditStorage({
|
|
131
|
+
* db: kyselyDb,
|
|
132
|
+
* tableName: 'audit_logs',
|
|
133
|
+
* });
|
|
134
|
+
*
|
|
135
|
+
* const auditor = new DefaultAuditor({
|
|
136
|
+
* actor: { id: 'user-123', type: 'user' },
|
|
137
|
+
* storage,
|
|
138
|
+
* });
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
declare class KyselyAuditStorage<DB> implements AuditStorage {
|
|
142
|
+
private readonly db;
|
|
143
|
+
private readonly tableName;
|
|
144
|
+
constructor(config: KyselyAuditStorageConfig<DB>);
|
|
145
|
+
write(records: AuditRecord[], trx?: unknown): Promise<void>;
|
|
146
|
+
query(options: AuditQueryOptions): Promise<AuditRecord[]>;
|
|
147
|
+
count(options: Omit<AuditQueryOptions, 'limit' | 'offset'>): Promise<number>;
|
|
148
|
+
/**
|
|
149
|
+
* Get the Kysely database instance for transactional operations.
|
|
150
|
+
* Used by endpoint adaptors to automatically wrap handlers in transactions.
|
|
151
|
+
*/
|
|
152
|
+
getDatabase(): Kysely<DB>;
|
|
153
|
+
private applyFilters;
|
|
154
|
+
private toRow;
|
|
155
|
+
private fromRow;
|
|
156
|
+
/**
|
|
157
|
+
* Parse a JSON value that may already be parsed (e.g., from jsonb columns).
|
|
158
|
+
*/
|
|
159
|
+
private parseJson;
|
|
160
|
+
private getActorData;
|
|
161
|
+
private parseEntityId;
|
|
162
|
+
}
|
|
163
|
+
//#endregion
|
|
164
|
+
export { AuditLogTable, DatabaseConnection, KyselyAuditStorage, KyselyAuditStorageConfig, TransactionAwareAuditor, TransactionSettings, withAuditableTransaction };
|
|
165
|
+
//# sourceMappingURL=kysely.d.mts.map
|
package/dist/kysely.mjs
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
//#region src/kysely.ts
|
|
2
|
+
/**
|
|
3
|
+
* Execute a callback within a database transaction with automatic audit handling.
|
|
4
|
+
*
|
|
5
|
+
* This wrapper ensures that:
|
|
6
|
+
* 1. The transaction is automatically registered with the auditor
|
|
7
|
+
* 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits
|
|
8
|
+
* 3. If audit flush fails, the entire transaction rolls back
|
|
9
|
+
* 4. If the callback fails, audits are NOT written (atomic consistency)
|
|
10
|
+
*
|
|
11
|
+
* **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)
|
|
12
|
+
* are processed AFTER the handler returns, so they run outside this transaction.
|
|
13
|
+
* If you need all audits to be atomic with your database operations, use manual
|
|
14
|
+
* audits via `auditor.audit()` inside this wrapper.
|
|
15
|
+
*
|
|
16
|
+
* @param db - Database connection (Kysely, Transaction, or ControlledTransaction)
|
|
17
|
+
* @param auditor - Auditor instance that will receive the transaction
|
|
18
|
+
* @param cb - Callback to execute within the transaction
|
|
19
|
+
* @param settings - Optional transaction settings (isolation level)
|
|
20
|
+
* @returns The result of the callback
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* import { withAuditableTransaction } from '@geekmidas/audit/kysely';
|
|
25
|
+
*
|
|
26
|
+
* const result = await withAuditableTransaction(
|
|
27
|
+
* services.database,
|
|
28
|
+
* auditor,
|
|
29
|
+
* async (trx) => {
|
|
30
|
+
* const user = await trx
|
|
31
|
+
* .insertInto('users')
|
|
32
|
+
* .values(data)
|
|
33
|
+
* .returningAll()
|
|
34
|
+
* .executeTakeFirstOrThrow();
|
|
35
|
+
*
|
|
36
|
+
* // Manual audits are atomic with the transaction
|
|
37
|
+
* auditor.audit('user.created', { userId: user.id, email: user.email });
|
|
38
|
+
*
|
|
39
|
+
* return user;
|
|
40
|
+
* },
|
|
41
|
+
* );
|
|
42
|
+
* // Audits are automatically flushed inside the transaction before commit
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
async function withAuditableTransaction(db, auditor, cb, settings) {
|
|
46
|
+
const execute = async (trx) => {
|
|
47
|
+
auditor.setTransaction(trx);
|
|
48
|
+
const result = await cb(trx);
|
|
49
|
+
await auditor.flush(trx);
|
|
50
|
+
return result;
|
|
51
|
+
};
|
|
52
|
+
if (db.isTransaction) return execute(db);
|
|
53
|
+
const builder = db.transaction();
|
|
54
|
+
if (settings?.isolationLevel) return builder.setIsolationLevel(settings.isolationLevel).execute(execute);
|
|
55
|
+
return builder.execute(execute);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Kysely-based audit storage implementation.
|
|
59
|
+
* Stores audit records in a database table using Kysely.
|
|
60
|
+
*
|
|
61
|
+
* @template DB - Your Kysely database schema
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```typescript
|
|
65
|
+
* interface Database {
|
|
66
|
+
* audit_logs: AuditLogTable;
|
|
67
|
+
* }
|
|
68
|
+
*
|
|
69
|
+
* const storage = new KyselyAuditStorage({
|
|
70
|
+
* db: kyselyDb,
|
|
71
|
+
* tableName: 'audit_logs',
|
|
72
|
+
* });
|
|
73
|
+
*
|
|
74
|
+
* const auditor = new DefaultAuditor({
|
|
75
|
+
* actor: { id: 'user-123', type: 'user' },
|
|
76
|
+
* storage,
|
|
77
|
+
* });
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
var KyselyAuditStorage = class {
|
|
81
|
+
db;
|
|
82
|
+
tableName;
|
|
83
|
+
constructor(config) {
|
|
84
|
+
this.db = config.db;
|
|
85
|
+
this.tableName = config.tableName;
|
|
86
|
+
}
|
|
87
|
+
async write(records, trx) {
|
|
88
|
+
if (records.length === 0) return;
|
|
89
|
+
const db = trx ?? this.db;
|
|
90
|
+
const rows = records.map((record) => this.toRow(record));
|
|
91
|
+
await db.insertInto(this.tableName).values(rows).execute();
|
|
92
|
+
}
|
|
93
|
+
async query(options) {
|
|
94
|
+
let query = this.db.selectFrom(this.tableName).selectAll();
|
|
95
|
+
query = this.applyFilters(query, options);
|
|
96
|
+
const orderBy = options.orderBy ?? "timestamp";
|
|
97
|
+
const orderDirection = options.orderDirection ?? "desc";
|
|
98
|
+
query = query.orderBy(orderBy === "timestamp" ? "timestamp" : "type", orderDirection);
|
|
99
|
+
if (options.limit !== void 0) query = query.limit(options.limit);
|
|
100
|
+
if (options.offset !== void 0) query = query.offset(options.offset);
|
|
101
|
+
const rows = await query.execute();
|
|
102
|
+
return rows.map((row) => this.fromRow(row));
|
|
103
|
+
}
|
|
104
|
+
async count(options) {
|
|
105
|
+
let query = this.db.selectFrom(this.tableName).select((eb) => eb.fn.count("id").as("count"));
|
|
106
|
+
query = this.applyFilters(query, options);
|
|
107
|
+
const result = await query.executeTakeFirst();
|
|
108
|
+
return Number(result?.count ?? 0);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Get the Kysely database instance for transactional operations.
|
|
112
|
+
* Used by endpoint adaptors to automatically wrap handlers in transactions.
|
|
113
|
+
*/
|
|
114
|
+
getDatabase() {
|
|
115
|
+
return this.db;
|
|
116
|
+
}
|
|
117
|
+
applyFilters(query, options) {
|
|
118
|
+
if (options.type !== void 0) if (Array.isArray(options.type)) query = query.where("type", "in", options.type);
|
|
119
|
+
else query = query.where("type", "=", options.type);
|
|
120
|
+
if (options.entityId !== void 0) {
|
|
121
|
+
const entityId = typeof options.entityId === "string" ? options.entityId : JSON.stringify(options.entityId);
|
|
122
|
+
query = query.where("entityId", "=", entityId);
|
|
123
|
+
}
|
|
124
|
+
if (options.table !== void 0) query = query.where("table", "=", options.table);
|
|
125
|
+
if (options.actorId !== void 0) query = query.where("actorId", "=", options.actorId);
|
|
126
|
+
if (options.from !== void 0) query = query.where("timestamp", ">=", options.from);
|
|
127
|
+
if (options.to !== void 0) query = query.where("timestamp", "<=", options.to);
|
|
128
|
+
return query;
|
|
129
|
+
}
|
|
130
|
+
toRow(record) {
|
|
131
|
+
return {
|
|
132
|
+
id: record.id,
|
|
133
|
+
type: record.type,
|
|
134
|
+
operation: record.operation,
|
|
135
|
+
table: record.table ?? null,
|
|
136
|
+
entityId: record.entityId === void 0 ? null : typeof record.entityId === "string" ? record.entityId : JSON.stringify(record.entityId),
|
|
137
|
+
oldValues: record.oldValues !== void 0 ? JSON.stringify(record.oldValues) : null,
|
|
138
|
+
newValues: record.newValues !== void 0 ? JSON.stringify(record.newValues) : null,
|
|
139
|
+
payload: record.payload !== void 0 ? JSON.stringify(record.payload) : null,
|
|
140
|
+
timestamp: record.timestamp,
|
|
141
|
+
actorId: record.actor?.id ?? null,
|
|
142
|
+
actorType: record.actor?.type ?? null,
|
|
143
|
+
actorData: record.actor !== void 0 ? JSON.stringify(this.getActorData(record.actor)) : null,
|
|
144
|
+
metadata: record.metadata !== void 0 ? JSON.stringify(record.metadata) : null
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
fromRow(row) {
|
|
148
|
+
const actor = row.actorId !== null || row.actorType !== null ? {
|
|
149
|
+
id: row.actorId ?? void 0,
|
|
150
|
+
type: row.actorType ?? void 0,
|
|
151
|
+
...row.actorData ? this.parseJson(row.actorData) : {}
|
|
152
|
+
} : void 0;
|
|
153
|
+
return {
|
|
154
|
+
id: row.id,
|
|
155
|
+
type: row.type,
|
|
156
|
+
operation: row.operation,
|
|
157
|
+
table: row.table ?? void 0,
|
|
158
|
+
entityId: row.entityId ? this.parseEntityId(row.entityId) : void 0,
|
|
159
|
+
oldValues: row.oldValues ? this.parseJson(row.oldValues) : void 0,
|
|
160
|
+
newValues: row.newValues ? this.parseJson(row.newValues) : void 0,
|
|
161
|
+
payload: row.payload ? this.parseJson(row.payload) : void 0,
|
|
162
|
+
timestamp: row.timestamp,
|
|
163
|
+
actor,
|
|
164
|
+
metadata: row.metadata ? this.parseJson(row.metadata) : void 0
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Parse a JSON value that may already be parsed (e.g., from jsonb columns).
|
|
169
|
+
*/
|
|
170
|
+
parseJson(value) {
|
|
171
|
+
if (typeof value === "object") return value;
|
|
172
|
+
return JSON.parse(value);
|
|
173
|
+
}
|
|
174
|
+
getActorData(actor) {
|
|
175
|
+
const { id, type,...rest } = actor;
|
|
176
|
+
return rest;
|
|
177
|
+
}
|
|
178
|
+
parseEntityId(entityId) {
|
|
179
|
+
try {
|
|
180
|
+
const parsed = JSON.parse(entityId);
|
|
181
|
+
if (typeof parsed === "object" && parsed !== null) return parsed;
|
|
182
|
+
return entityId;
|
|
183
|
+
} catch {
|
|
184
|
+
return entityId;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
//#endregion
|
|
190
|
+
export { KyselyAuditStorage, withAuditableTransaction };
|
|
191
|
+
//# sourceMappingURL=kysely.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kysely.mjs","names":["db: DatabaseConnection<DB>","auditor: TransactionAwareAuditor<Transaction<DB>>","cb: (trx: Transaction<DB>) => Promise<T>","settings?: TransactionSettings","trx: Transaction<DB>","config: KyselyAuditStorageConfig<DB>","records: AuditRecord[]","trx?: unknown","options: AuditQueryOptions","row: AuditLogTable","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","eb: any","query: any","record: AuditRecord","value: string | object","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/kysely.ts"],"sourcesContent":["import type {\n ControlledTransaction,\n IsolationLevel,\n Kysely,\n Transaction,\n} from 'kysely';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditRecord } from './types';\n\n/**\n * Minimal interface for transaction-aware audit flushing.\n * Use this when you need to flush audits within a database transaction.\n *\n * @template TTransaction - Transaction type (e.g., Kysely Transaction)\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n * import type { TransactionAwareAuditor } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * db,\n * auditor as TransactionAwareAuditor<Transaction<DB>>,\n * async (trx) => {\n * // Your transactional operations\n * return result;\n * },\n * );\n * ```\n */\nexport interface TransactionAwareAuditor<TTransaction = unknown> {\n /** Register the transaction with the auditor for use during flush */\n setTransaction(trx: TTransaction): void;\n /** Flush all pending audits, optionally within a transaction */\n flush(trx?: TTransaction): Promise<void>;\n}\n\nexport interface TransactionSettings {\n isolationLevel?: IsolationLevel;\n}\n\nexport type DatabaseConnection<T> =\n | ControlledTransaction<T>\n | Kysely<T>\n | Transaction<T>;\n\n/**\n * Execute a callback within a database transaction with automatic audit handling.\n *\n * This wrapper ensures that:\n * 1. The transaction is automatically registered with the auditor\n * 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits\n * 3. If audit flush fails, the entire transaction rolls back\n * 4. If the callback fails, audits are NOT written (atomic consistency)\n *\n * **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)\n * are processed AFTER the handler returns, so they run outside this transaction.\n * If you need all audits to be atomic with your database operations, use manual\n * audits via `auditor.audit()` inside this wrapper.\n *\n * @param db - Database connection (Kysely, Transaction, or ControlledTransaction)\n * @param auditor - Auditor instance that will receive the transaction\n * @param cb - Callback to execute within the transaction\n * @param settings - Optional transaction settings (isolation level)\n * @returns The result of the callback\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * services.database,\n * auditor,\n * async (trx) => {\n * const user = await trx\n * .insertInto('users')\n * .values(data)\n * .returningAll()\n * .executeTakeFirstOrThrow();\n *\n * // Manual audits are atomic with the transaction\n * auditor.audit('user.created', { userId: user.id, email: user.email });\n *\n * return user;\n * },\n * );\n * // Audits are automatically flushed inside the transaction before commit\n * ```\n */\nexport async function withAuditableTransaction<DB, T>(\n db: DatabaseConnection<DB>,\n auditor: TransactionAwareAuditor<Transaction<DB>>,\n cb: (trx: Transaction<DB>) => Promise<T>,\n settings?: TransactionSettings,\n): Promise<T> {\n const execute = async (trx: Transaction<DB>): Promise<T> => {\n // Register transaction with auditor\n auditor.setTransaction(trx);\n\n // Execute the callback\n const result = await cb(trx);\n\n // Flush audits BEFORE transaction commits\n // If this fails, the transaction will roll back\n await auditor.flush(trx);\n\n return result;\n };\n\n // If already in a transaction, just run with it\n if (db.isTransaction) {\n return execute(db as Transaction<DB>);\n }\n\n const builder = db.transaction();\n\n if (settings?.isolationLevel) {\n return builder.setIsolationLevel(settings.isolationLevel).execute(execute);\n }\n\n return builder.execute(execute);\n}\n\n/**\n * Database table interface for audit records.\n * Use this to define your audit_logs table in your Kysely database schema.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * // ... other tables\n * }\n * ```\n */\nexport interface AuditLogTable {\n id: string;\n type: string;\n operation: string;\n table: string | null;\n entityId: string | null;\n oldValues: string | null;\n newValues: string | null;\n payload: string | null;\n timestamp: Date;\n actorId: string | null;\n actorType: string | null;\n actorData: string | null;\n metadata: string | null;\n}\n\n/**\n * Configuration for KyselyAuditStorage.\n */\nexport interface KyselyAuditStorageConfig<DB> {\n /** Kysely database instance */\n db: Kysely<DB>;\n /** Table name for audit logs (must be a key in DB that extends AuditLogTable) */\n tableName: keyof DB & string;\n}\n\n/**\n * Kysely-based audit storage implementation.\n * Stores audit records in a database table using Kysely.\n *\n * @template DB - Your Kysely database schema\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * const storage = new KyselyAuditStorage({\n * db: kyselyDb,\n * tableName: 'audit_logs',\n * });\n *\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n * ```\n */\nexport class KyselyAuditStorage<DB> implements AuditStorage {\n private readonly db: Kysely<DB>;\n private readonly tableName: keyof DB & string;\n\n constructor(config: KyselyAuditStorageConfig<DB>) {\n this.db = config.db;\n this.tableName = config.tableName;\n }\n\n async write(records: AuditRecord[], trx?: unknown): Promise<void> {\n if (records.length === 0) {\n return;\n }\n\n const db = (trx as Transaction<DB>) ?? this.db;\n const rows = records.map((record) => this.toRow(record));\n\n await (db as any)\n .insertInto(this.tableName)\n .values(rows)\n .execute();\n }\n\n async query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n let query = (this.db as any)\n .selectFrom(this.tableName)\n .selectAll();\n\n query = this.applyFilters(query, options);\n\n // Ordering\n const orderBy = options.orderBy ?? 'timestamp';\n const orderDirection = options.orderDirection ?? 'desc';\n query = query.orderBy(\n orderBy === 'timestamp' ? 'timestamp' : 'type',\n orderDirection,\n );\n\n // Pagination\n if (options.limit !== undefined) {\n query = query.limit(options.limit);\n }\n if (options.offset !== undefined) {\n query = query.offset(options.offset);\n }\n\n const rows = await query.execute();\n return rows.map((row: AuditLogTable) => this.fromRow(row));\n }\n\n async count(\n options: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n ): Promise<number> {\n let query = (this.db as any)\n .selectFrom(this.tableName)\n .select((eb: any) => eb.fn.count('id').as('count'));\n\n query = this.applyFilters(query, options);\n\n const result = await query.executeTakeFirst();\n return Number(result?.count ?? 0);\n }\n\n /**\n * Get the Kysely database instance for transactional operations.\n * Used by endpoint adaptors to automatically wrap handlers in transactions.\n */\n getDatabase(): Kysely<DB> {\n return this.db;\n }\n\n private applyFilters(query: any, options: AuditQueryOptions): any {\n // Type filter\n if (options.type !== undefined) {\n if (Array.isArray(options.type)) {\n query = query.where('type', 'in', options.type);\n } else {\n query = query.where('type', '=', options.type);\n }\n }\n\n // Entity ID filter\n if (options.entityId !== undefined) {\n const entityId =\n typeof options.entityId === 'string'\n ? options.entityId\n : JSON.stringify(options.entityId);\n query = query.where('entityId', '=', entityId);\n }\n\n // Table filter\n if (options.table !== undefined) {\n query = query.where('table', '=', options.table);\n }\n\n // Actor ID filter\n if (options.actorId !== undefined) {\n query = query.where('actorId', '=', options.actorId);\n }\n\n // Date range filters\n if (options.from !== undefined) {\n query = query.where('timestamp', '>=', options.from);\n }\n if (options.to !== undefined) {\n query = query.where('timestamp', '<=', options.to);\n }\n\n return query;\n }\n\n private toRow(record: AuditRecord): AuditLogTable {\n return {\n id: record.id,\n type: record.type,\n operation: record.operation,\n table: record.table ?? null,\n entityId:\n record.entityId === undefined\n ? null\n : typeof record.entityId === 'string'\n ? record.entityId\n : JSON.stringify(record.entityId),\n oldValues:\n record.oldValues !== undefined\n ? JSON.stringify(record.oldValues)\n : null,\n newValues:\n record.newValues !== undefined\n ? JSON.stringify(record.newValues)\n : null,\n payload:\n record.payload !== undefined ? JSON.stringify(record.payload) : null,\n timestamp: record.timestamp,\n actorId: record.actor?.id ?? null,\n actorType: record.actor?.type ?? null,\n actorData:\n record.actor !== undefined\n ? JSON.stringify(this.getActorData(record.actor))\n : null,\n metadata:\n record.metadata !== undefined ? JSON.stringify(record.metadata) : null,\n };\n }\n\n private fromRow(row: AuditLogTable): AuditRecord {\n const actor =\n row.actorId !== null || row.actorType !== null\n ? {\n id: row.actorId ?? undefined,\n type: row.actorType ?? undefined,\n ...(row.actorData ? this.parseJson(row.actorData) : {}),\n }\n : undefined;\n\n return {\n id: row.id,\n type: row.type,\n operation: row.operation as AuditRecord['operation'],\n table: row.table ?? undefined,\n entityId: row.entityId\n ? this.parseEntityId(row.entityId)\n : undefined,\n oldValues: row.oldValues\n ? this.parseJson(row.oldValues)\n : undefined,\n newValues: row.newValues\n ? this.parseJson(row.newValues)\n : undefined,\n payload: row.payload ? this.parseJson(row.payload) : undefined,\n timestamp: row.timestamp,\n actor,\n metadata: row.metadata ? this.parseJson(row.metadata) : undefined,\n };\n }\n\n /**\n * Parse a JSON value that may already be parsed (e.g., from jsonb columns).\n */\n private parseJson(value: string | object): Record<string, unknown> {\n if (typeof value === 'object') {\n return value as Record<string, unknown>;\n }\n return JSON.parse(value);\n }\n\n private getActorData(\n actor: NonNullable<AuditRecord['actor']>,\n ): Record<string, unknown> {\n const { id, type, ...rest } = actor;\n return rest;\n }\n\n private parseEntityId(\n entityId: string,\n ): string | Record<string, unknown> {\n try {\n const parsed = JSON.parse(entityId);\n if (typeof parsed === 'object' && parsed !== null) {\n return parsed;\n }\n return entityId;\n } catch {\n return entityId;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { AuditRecord } from "./Auditor-CZ8lkASv.cjs";
|
|
2
|
+
|
|
3
|
+
//#region src/storage.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Options for querying audit records.
|
|
7
|
+
*/
|
|
8
|
+
interface AuditQueryOptions {
|
|
9
|
+
/** Filter by audit type */
|
|
10
|
+
type?: string | string[];
|
|
11
|
+
/** Filter by entity ID */
|
|
12
|
+
entityId?: string | Record<string, unknown>;
|
|
13
|
+
/** Filter by table name */
|
|
14
|
+
table?: string;
|
|
15
|
+
/** Filter by actor ID */
|
|
16
|
+
actorId?: string;
|
|
17
|
+
/** Filter by date range (start) */
|
|
18
|
+
from?: Date;
|
|
19
|
+
/** Filter by date range (end) */
|
|
20
|
+
to?: Date;
|
|
21
|
+
/** Limit number of results */
|
|
22
|
+
limit?: number;
|
|
23
|
+
/** Offset for pagination */
|
|
24
|
+
offset?: number;
|
|
25
|
+
/** Sort order */
|
|
26
|
+
orderBy?: 'timestamp' | 'type';
|
|
27
|
+
/** Sort direction */
|
|
28
|
+
orderDirection?: 'asc' | 'desc';
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Interface for audit storage backends.
|
|
32
|
+
* Implement this to store audits in your preferred location.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```typescript
|
|
36
|
+
* // Same database storage (recommended for transactions)
|
|
37
|
+
* const auditStorage: AuditStorage = {
|
|
38
|
+
* async write(records, trx) {
|
|
39
|
+
* const db = trx ?? getDatabase();
|
|
40
|
+
* await db.insertInto('audit_logs').values(records).execute();
|
|
41
|
+
* },
|
|
42
|
+
* };
|
|
43
|
+
*
|
|
44
|
+
* // External audit service
|
|
45
|
+
* const externalAuditStorage: AuditStorage = {
|
|
46
|
+
* async write(records) {
|
|
47
|
+
* await fetch('https://audit.example.com/api/audits', {
|
|
48
|
+
* method: 'POST',
|
|
49
|
+
* body: JSON.stringify({ records }),
|
|
50
|
+
* });
|
|
51
|
+
* },
|
|
52
|
+
* };
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
interface AuditStorage {
|
|
56
|
+
/**
|
|
57
|
+
* Write audit records to storage.
|
|
58
|
+
* Called by Auditor.flush() to persist collected audits.
|
|
59
|
+
*
|
|
60
|
+
* @param records - The audit records to write
|
|
61
|
+
* @param trx - Optional transaction context (for same-DB storage)
|
|
62
|
+
*/
|
|
63
|
+
write(records: AuditRecord[], trx?: unknown): Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Optional: Query audit records for retrieval.
|
|
66
|
+
* Implement this for audit log viewing/searching.
|
|
67
|
+
*
|
|
68
|
+
* @param options - Query filters and pagination
|
|
69
|
+
* @returns Matching audit records
|
|
70
|
+
*/
|
|
71
|
+
query?(options: AuditQueryOptions): Promise<AuditRecord[]>;
|
|
72
|
+
/**
|
|
73
|
+
* Optional: Count audit records matching filters.
|
|
74
|
+
* Useful for pagination.
|
|
75
|
+
*
|
|
76
|
+
* @param options - Query filters (limit/offset ignored)
|
|
77
|
+
* @returns Count of matching records
|
|
78
|
+
*/
|
|
79
|
+
count?(options: Omit<AuditQueryOptions, 'limit' | 'offset'>): Promise<number>;
|
|
80
|
+
/**
|
|
81
|
+
* Optional: Get the database connection for transactional audit writes.
|
|
82
|
+
* When implemented, the endpoint adaptor can automatically wrap handlers
|
|
83
|
+
* in a transaction, ensuring audits are atomic with other database operations.
|
|
84
|
+
*
|
|
85
|
+
* @returns Database connection (e.g., Kysely instance)
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```typescript
|
|
89
|
+
* class KyselyAuditStorage implements AuditStorage {
|
|
90
|
+
* constructor(private db: Kysely<DB>) {}
|
|
91
|
+
*
|
|
92
|
+
* getDatabase() {
|
|
93
|
+
* return this.db;
|
|
94
|
+
* }
|
|
95
|
+
* }
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
getDatabase?(): unknown;
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
export { AuditQueryOptions, AuditStorage };
|
|
102
|
+
//# sourceMappingURL=storage-BtFY7Rha.d.cts.map
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { AuditRecord } from "./Auditor-ii62d_pF.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/storage.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Options for querying audit records.
|
|
7
|
+
*/
|
|
8
|
+
interface AuditQueryOptions {
|
|
9
|
+
/** Filter by audit type */
|
|
10
|
+
type?: string | string[];
|
|
11
|
+
/** Filter by entity ID */
|
|
12
|
+
entityId?: string | Record<string, unknown>;
|
|
13
|
+
/** Filter by table name */
|
|
14
|
+
table?: string;
|
|
15
|
+
/** Filter by actor ID */
|
|
16
|
+
actorId?: string;
|
|
17
|
+
/** Filter by date range (start) */
|
|
18
|
+
from?: Date;
|
|
19
|
+
/** Filter by date range (end) */
|
|
20
|
+
to?: Date;
|
|
21
|
+
/** Limit number of results */
|
|
22
|
+
limit?: number;
|
|
23
|
+
/** Offset for pagination */
|
|
24
|
+
offset?: number;
|
|
25
|
+
/** Sort order */
|
|
26
|
+
orderBy?: 'timestamp' | 'type';
|
|
27
|
+
/** Sort direction */
|
|
28
|
+
orderDirection?: 'asc' | 'desc';
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Interface for audit storage backends.
|
|
32
|
+
* Implement this to store audits in your preferred location.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```typescript
|
|
36
|
+
* // Same database storage (recommended for transactions)
|
|
37
|
+
* const auditStorage: AuditStorage = {
|
|
38
|
+
* async write(records, trx) {
|
|
39
|
+
* const db = trx ?? getDatabase();
|
|
40
|
+
* await db.insertInto('audit_logs').values(records).execute();
|
|
41
|
+
* },
|
|
42
|
+
* };
|
|
43
|
+
*
|
|
44
|
+
* // External audit service
|
|
45
|
+
* const externalAuditStorage: AuditStorage = {
|
|
46
|
+
* async write(records) {
|
|
47
|
+
* await fetch('https://audit.example.com/api/audits', {
|
|
48
|
+
* method: 'POST',
|
|
49
|
+
* body: JSON.stringify({ records }),
|
|
50
|
+
* });
|
|
51
|
+
* },
|
|
52
|
+
* };
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
interface AuditStorage {
|
|
56
|
+
/**
|
|
57
|
+
* Write audit records to storage.
|
|
58
|
+
* Called by Auditor.flush() to persist collected audits.
|
|
59
|
+
*
|
|
60
|
+
* @param records - The audit records to write
|
|
61
|
+
* @param trx - Optional transaction context (for same-DB storage)
|
|
62
|
+
*/
|
|
63
|
+
write(records: AuditRecord[], trx?: unknown): Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Optional: Query audit records for retrieval.
|
|
66
|
+
* Implement this for audit log viewing/searching.
|
|
67
|
+
*
|
|
68
|
+
* @param options - Query filters and pagination
|
|
69
|
+
* @returns Matching audit records
|
|
70
|
+
*/
|
|
71
|
+
query?(options: AuditQueryOptions): Promise<AuditRecord[]>;
|
|
72
|
+
/**
|
|
73
|
+
* Optional: Count audit records matching filters.
|
|
74
|
+
* Useful for pagination.
|
|
75
|
+
*
|
|
76
|
+
* @param options - Query filters (limit/offset ignored)
|
|
77
|
+
* @returns Count of matching records
|
|
78
|
+
*/
|
|
79
|
+
count?(options: Omit<AuditQueryOptions, 'limit' | 'offset'>): Promise<number>;
|
|
80
|
+
/**
|
|
81
|
+
* Optional: Get the database connection for transactional audit writes.
|
|
82
|
+
* When implemented, the endpoint adaptor can automatically wrap handlers
|
|
83
|
+
* in a transaction, ensuring audits are atomic with other database operations.
|
|
84
|
+
*
|
|
85
|
+
* @returns Database connection (e.g., Kysely instance)
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```typescript
|
|
89
|
+
* class KyselyAuditStorage implements AuditStorage {
|
|
90
|
+
* constructor(private db: Kysely<DB>) {}
|
|
91
|
+
*
|
|
92
|
+
* getDatabase() {
|
|
93
|
+
* return this.db;
|
|
94
|
+
* }
|
|
95
|
+
* }
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
getDatabase?(): unknown;
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
export { AuditQueryOptions, AuditStorage };
|
|
102
|
+
//# sourceMappingURL=storage-DnAMfOA7.d.mts.map
|
package/dist/storage.cjs
ADDED
|
File without changes
|
package/dist/storage.mjs
ADDED
|
File without changes
|
package/dist/types.cjs
ADDED
|
File without changes
|
package/dist/types.d.cts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, MappedAudit } from "./Auditor-CZ8lkASv.cjs";
|
|
2
|
+
export { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, MappedAudit };
|
package/dist/types.d.mts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, MappedAudit } from "./Auditor-ii62d_pF.mjs";
|
|
2
|
+
export { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, MappedAudit };
|
package/dist/types.mjs
ADDED
|
File without changes
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@geekmidas/audit",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": {
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"import": "./dist/index.mjs",
|
|
9
|
+
"require": "./dist/index.cjs"
|
|
10
|
+
},
|
|
11
|
+
"./kysely": {
|
|
12
|
+
"types": "./dist/kysely.d.ts",
|
|
13
|
+
"import": "./dist/kysely.mjs",
|
|
14
|
+
"require": "./dist/kysely.cjs"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"registry": "https://registry.npmjs.org/",
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@standard-schema/spec": "~1.0.0",
|
|
23
|
+
"nanoid": "~5.1.5",
|
|
24
|
+
"@geekmidas/schema": "0.0.2"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"kysely": "^0.28.0"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"kysely": "~0.28.2",
|
|
31
|
+
"pg": "~8.16.0",
|
|
32
|
+
"@types/pg": "~8.15.6"
|
|
33
|
+
}
|
|
34
|
+
}
|