@hazeljs/audit 0.2.0-beta.52

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/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2024 HazelJS Team
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+
19
+ ---
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
191
+
192
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,164 @@
1
+ # @hazeljs/audit
2
+
3
+ **Audit logging and event trail for HazelJS. Record who did what, when, and with what outcome.**
4
+
5
+ Compliance-ready audit events from HTTP requests and custom business logic. Console, file, or Kafka. Redact secrets, add actors from context, and plug in your own transports.
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@hazeljs/audit.svg)](https://www.npmjs.com/package/@hazeljs/audit)
8
+ [![npm downloads](https://img.shields.io/npm/dm/@hazeljs/audit)](https://www.npmjs.com/package/@hazeljs/audit)
9
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
10
+
11
+ ## Features
12
+
13
+ - **HTTP audit** — `AuditInterceptor` logs every request (method, path, result)
14
+ - **Custom events** — Inject `AuditService` and call `log()` with action, resource, actor
15
+ - **Transports** — Console (default), file (JSONL with rotation), Kafka (JSON or Avro)
16
+ - **@Audit decorator** — Mark handlers with action/resource for metadata and tooling
17
+ - **Redaction** — Sensitive keys (password, token, etc.) redacted by default
18
+ - **Actor from context** — `actorFromContext()` maps request user to audit actor
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install @hazeljs/audit @hazeljs/core
24
+ ```
25
+
26
+ ## Quick Start
27
+
28
+ ### 1. Register the module
29
+
30
+ ```typescript
31
+ import { HazelModule } from '@hazeljs/core';
32
+ import { AuditModule } from '@hazeljs/audit';
33
+
34
+ @HazelModule({
35
+ imports: [AuditModule.forRoot()],
36
+ })
37
+ export class AppModule {}
38
+ ```
39
+
40
+ With the module registered, use **AuditInterceptor** to log every HTTP request, or inject **AuditService** and call `log()` for custom events.
41
+
42
+ ### 2. Module options
43
+
44
+ ```typescript
45
+ AuditModule.forRoot({
46
+ transports: [new ConsoleAuditTransport()], // default
47
+ includeRequestContext: true,
48
+ redactKeys: ['password', 'token', 'secret', 'authorization'],
49
+ });
50
+ ```
51
+
52
+ ### 3. Custom events with AuditService
53
+
54
+ ```typescript
55
+ import { Injectable } from '@hazeljs/core';
56
+ import { AuditService } from '@hazeljs/audit';
57
+ import type { RequestContext } from '@hazeljs/core';
58
+
59
+ @Injectable()
60
+ export class OrderService {
61
+ constructor(private readonly audit: AuditService) {}
62
+
63
+ async create(data: CreateOrderDto, context: RequestContext) {
64
+ const order = await this.repo.create(data);
65
+ this.audit.log({
66
+ action: 'order.create',
67
+ actor: this.audit.actorFromContext(context),
68
+ resource: 'Order',
69
+ resourceId: order.id,
70
+ result: 'success',
71
+ metadata: { amount: order.total },
72
+ });
73
+ return order;
74
+ }
75
+ }
76
+ ```
77
+
78
+ ## Audit event shape
79
+
80
+ - **action** — e.g. `user.login`, `order.create`
81
+ - **actor** — `{ id, username?, role? }` from request context when available
82
+ - **resource** / **resourceId** — what was affected
83
+ - **result** — `success` | `failure` | `denied`
84
+ - **timestamp** — ISO string (set automatically if omitted)
85
+ - **method** / **path** — from HTTP context when using the interceptor
86
+ - **metadata** — extra structured data (sensitive keys redacted by default)
87
+
88
+ ## Transports
89
+
90
+ ### Console (default)
91
+
92
+ Writes one JSON line per event to stdout.
93
+
94
+ ```typescript
95
+ import { ConsoleAuditTransport } from '@hazeljs/audit';
96
+
97
+ transports: [new ConsoleAuditTransport()],
98
+ ```
99
+
100
+ ### File (JSONL)
101
+
102
+ Appends to a file. Creates the file and parent dir on first event. Supports rotation by size or by day.
103
+
104
+ ```typescript
105
+ import { FileAuditTransport } from '@hazeljs/audit';
106
+
107
+ transports: [
108
+ new FileAuditTransport({
109
+ filePath: 'logs/audit.jsonl',
110
+ ensureDir: true,
111
+ maxSizeBytes: 10 * 1024 * 1024, // 10MB
112
+ rollDaily: true, // audit.2025-03-01.jsonl
113
+ }),
114
+ ],
115
+ ```
116
+
117
+ ### Kafka
118
+
119
+ Sends each event to a Kafka topic. Use with [@hazeljs/kafka](https://www.npmjs.com/package/@hazeljs/kafka): pass `KafkaProducerService` as the sender. Optional **key** for partitioning; optional **serialize** for custom format (default JSON). For Avro, pass a `serialize` function that returns a `Buffer` (e.g. using `avsc` or Confluent Schema Registry).
120
+
121
+ ```typescript
122
+ import { KafkaAuditTransport } from '@hazeljs/audit';
123
+ import { KafkaProducerService } from '@hazeljs/kafka';
124
+
125
+ const transport = new KafkaAuditTransport({
126
+ sender: kafkaProducerService, // from your app's container
127
+ topic: 'audit',
128
+ key: (e) => e.actor?.id?.toString(), // optional partition key
129
+ // serialize: (e) => avroType.toBuffer(e), // optional Avro
130
+ });
131
+ ```
132
+
133
+ ### Custom transport
134
+
135
+ Implement **AuditTransport** (interface with `log(event: AuditEvent)`) to send events to your database, SIEM, or logging service.
136
+
137
+ ## @Audit decorator
138
+
139
+ Mark handlers with custom action/resource for metadata and tooling:
140
+
141
+ ```typescript
142
+ import { Controller, Post, Body } from '@hazeljs/core';
143
+ import { Audit } from '@hazeljs/audit';
144
+
145
+ @Controller('/orders')
146
+ export class OrderController {
147
+ @Post()
148
+ @Audit({ action: 'order.create', resource: 'Order' })
149
+ async create(@Body() dto: CreateOrderDto) {
150
+ return this.orderService.create(dto);
151
+ }
152
+ }
153
+ ```
154
+
155
+ ## License
156
+
157
+ Apache 2.0 © [HazelJS](https://hazeljs.com)
158
+
159
+ ## Links
160
+
161
+ - [Documentation](https://hazeljs.com/docs/packages/auth)
162
+ - [GitHub](https://github.com/hazel-js/hazeljs)
163
+ - [Issues](https://github.com/hazel-js/hazeljs/issues)
164
+ - [Discord](https://discord.gg/hazeljs)
@@ -0,0 +1,11 @@
1
+ /**
2
+ * AuditModule - Audit logging for HazelJS
3
+ */
4
+ import type { AuditModuleOptions } from './audit.types';
5
+ export declare const AUDIT_SERVICE_TOKEN = "AuditService";
6
+ export declare class AuditModule {
7
+ private static options;
8
+ static forRoot(options?: AuditModuleOptions): typeof AuditModule;
9
+ static getOptions(): AuditModuleOptions;
10
+ }
11
+ //# sourceMappingURL=audit.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.module.d.ts","sourceRoot":"","sources":["../src/audit.module.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAExD,eAAO,MAAM,mBAAmB,iBAAiB,CAAC;AAElD,qBAIa,WAAW;IACtB,OAAO,CAAC,MAAM,CAAC,OAAO,CAA0B;IAEhD,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,kBAAkB,GAAG,OAAO,WAAW;IAQhE,MAAM,CAAC,UAAU,IAAI,kBAAkB;CAGxC"}
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ /**
3
+ * AuditModule - Audit logging for HazelJS
4
+ */
5
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
6
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
7
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
8
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
9
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
10
+ };
11
+ var AuditModule_1;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.AuditModule = exports.AUDIT_SERVICE_TOKEN = void 0;
14
+ const core_1 = require("@hazeljs/core");
15
+ const audit_service_1 = require("./audit.service");
16
+ const audit_interceptor_1 = require("./interceptors/audit.interceptor");
17
+ exports.AUDIT_SERVICE_TOKEN = 'AuditService';
18
+ let AuditModule = AuditModule_1 = class AuditModule {
19
+ static forRoot(options) {
20
+ AuditModule_1.options = options ?? {};
21
+ if (options) {
22
+ audit_service_1.AuditService.configure(options);
23
+ }
24
+ return AuditModule_1;
25
+ }
26
+ static getOptions() {
27
+ return AuditModule_1.options;
28
+ }
29
+ };
30
+ exports.AuditModule = AuditModule;
31
+ AuditModule.options = {};
32
+ exports.AuditModule = AuditModule = AuditModule_1 = __decorate([
33
+ (0, core_1.HazelModule)({
34
+ providers: [audit_service_1.AuditService, audit_interceptor_1.AuditInterceptor],
35
+ exports: [audit_service_1.AuditService, audit_interceptor_1.AuditInterceptor],
36
+ })
37
+ ], AuditModule);
@@ -0,0 +1,32 @@
1
+ /**
2
+ * AuditService - Record audit events and send to configured transports
3
+ */
4
+ import type { RequestContext } from '@hazeljs/core';
5
+ import type { AuditEvent, AuditTransport, AuditActor, AuditModuleOptions } from './audit.types';
6
+ export declare class AuditService {
7
+ private static staticOptions;
8
+ private transports;
9
+ private redactKeys;
10
+ constructor(options?: AuditModuleOptions);
11
+ static configure(options: AuditModuleOptions): void;
12
+ /**
13
+ * Add a transport at runtime (e.g. Kafka after producer is available).
14
+ */
15
+ addTransport(transport: AuditTransport): void;
16
+ /**
17
+ * Record an audit event. Events are sent to all configured transports.
18
+ */
19
+ log(event: Omit<AuditEvent, 'timestamp'> & {
20
+ timestamp?: string;
21
+ }): void;
22
+ /**
23
+ * Create an actor from RequestContext (e.g. authenticated user).
24
+ */
25
+ actorFromContext(context: RequestContext): AuditActor | undefined;
26
+ /**
27
+ * Build a minimal audit event from an HTTP request context (for use by AuditInterceptor).
28
+ */
29
+ eventFromContext(context: RequestContext, result?: 'success' | 'failure' | 'denied', action?: string): AuditEvent;
30
+ private sanitize;
31
+ }
32
+ //# sourceMappingURL=audit.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.service.d.ts","sourceRoot":"","sources":["../src/audit.service.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAGhG,qBACa,YAAY;IACvB,OAAO,CAAC,MAAM,CAAC,aAAa,CAA0B;IACtD,OAAO,CAAC,UAAU,CAAwB;IAC1C,OAAO,CAAC,UAAU,CAA0B;gBAEhC,OAAO,CAAC,EAAE,kBAAkB;IAgBxC,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI;IAInD;;OAEG;IACH,YAAY,CAAC,SAAS,EAAE,cAAc,GAAG,IAAI;IAI7C;;OAEG;IACH,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,GAAG;QAAE,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI;IAoBxE;;OAEG;IACH,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG,UAAU,GAAG,SAAS;IAMjE;;OAEG;IACH,gBAAgB,CACd,OAAO,EAAE,cAAc,EACvB,MAAM,GAAE,SAAS,GAAG,SAAS,GAAG,QAAoB,EACpD,MAAM,CAAC,EAAE,MAAM,GACd,UAAU;IAab,OAAO,CAAC,QAAQ;CAUjB"}
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ /**
3
+ * AuditService - Record audit events and send to configured transports
4
+ */
5
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
6
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
7
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
8
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
9
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
10
+ };
11
+ var __metadata = (this && this.__metadata) || function (k, v) {
12
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
13
+ };
14
+ var AuditService_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.AuditService = void 0;
17
+ const core_1 = require("@hazeljs/core");
18
+ const console_transport_1 = require("./transports/console.transport");
19
+ let AuditService = AuditService_1 = class AuditService {
20
+ constructor(options) {
21
+ this.transports = [];
22
+ this.redactKeys = new Set();
23
+ const opts = options ?? { ...AuditService_1.staticOptions };
24
+ this.redactKeys = new Set((opts.redactKeys ?? ['password', 'token', 'secret', 'authorization']).map((k) => k.toLowerCase()));
25
+ if (opts.transports && opts.transports.length > 0) {
26
+ this.transports = opts.transports;
27
+ }
28
+ else if (AuditService_1.staticOptions.transports?.length) {
29
+ this.transports = AuditService_1.staticOptions.transports;
30
+ }
31
+ else {
32
+ this.transports = [new console_transport_1.ConsoleAuditTransport()];
33
+ }
34
+ }
35
+ static configure(options) {
36
+ AuditService_1.staticOptions = { ...AuditService_1.staticOptions, ...options };
37
+ }
38
+ /**
39
+ * Add a transport at runtime (e.g. Kafka after producer is available).
40
+ */
41
+ addTransport(transport) {
42
+ this.transports.push(transport);
43
+ }
44
+ /**
45
+ * Record an audit event. Events are sent to all configured transports.
46
+ */
47
+ log(event) {
48
+ const full = {
49
+ ...event,
50
+ timestamp: event.timestamp ?? new Date().toISOString(),
51
+ };
52
+ const sanitized = this.sanitize(full);
53
+ for (const transport of this.transports) {
54
+ try {
55
+ const result = transport.log(sanitized);
56
+ if (result instanceof Promise) {
57
+ result.catch((err) => {
58
+ core_1.logger.error('[AuditService] transport error:', err);
59
+ });
60
+ }
61
+ }
62
+ catch (err) {
63
+ core_1.logger.error('[AuditService] transport error:', err);
64
+ }
65
+ }
66
+ }
67
+ /**
68
+ * Create an actor from RequestContext (e.g. authenticated user).
69
+ */
70
+ actorFromContext(context) {
71
+ if (!context.user)
72
+ return undefined;
73
+ const { id, username, role, ...rest } = context.user;
74
+ return { id, username, role, ...rest };
75
+ }
76
+ /**
77
+ * Build a minimal audit event from an HTTP request context (for use by AuditInterceptor).
78
+ */
79
+ eventFromContext(context, result = 'success', action) {
80
+ const actor = this.actorFromContext(context);
81
+ return {
82
+ action: action ?? `http.${context.method?.toLowerCase()}`,
83
+ actor,
84
+ result,
85
+ timestamp: new Date().toISOString(),
86
+ method: context.method,
87
+ path: context.url,
88
+ metadata: context.url ? { path: context.url, method: context.method } : undefined,
89
+ };
90
+ }
91
+ sanitize(event) {
92
+ if (!event.metadata || this.redactKeys.size === 0)
93
+ return event;
94
+ const metadata = { ...event.metadata };
95
+ for (const key of Object.keys(metadata)) {
96
+ if (this.redactKeys.has(key.toLowerCase())) {
97
+ metadata[key] = '[REDACTED]';
98
+ }
99
+ }
100
+ return { ...event, metadata };
101
+ }
102
+ };
103
+ exports.AuditService = AuditService;
104
+ AuditService.staticOptions = {};
105
+ exports.AuditService = AuditService = AuditService_1 = __decorate([
106
+ (0, core_1.Injectable)(),
107
+ __metadata("design:paramtypes", [Object])
108
+ ], AuditService);
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Audit event and module options
3
+ */
4
+ export interface AuditActor {
5
+ id: string | number;
6
+ username?: string;
7
+ role?: string;
8
+ [key: string]: unknown;
9
+ }
10
+ export interface AuditEvent {
11
+ /** Action identifier (e.g. 'user.login', 'order.create') */
12
+ action: string;
13
+ /** Who performed the action (optional if not in request context) */
14
+ actor?: AuditActor;
15
+ /** Resource affected (e.g. 'User', 'Order', entity id) */
16
+ resource?: string;
17
+ /** Resource identifier (e.g. entity id) */
18
+ resourceId?: string | number;
19
+ /** Outcome: success, failure, denied */
20
+ result?: 'success' | 'failure' | 'denied';
21
+ /** ISO timestamp */
22
+ timestamp: string;
23
+ /** Request or correlation id for tracing */
24
+ requestId?: string;
25
+ /** HTTP method when from HTTP request */
26
+ method?: string;
27
+ /** Path/URL when from HTTP request */
28
+ path?: string;
29
+ /** Additional structured data (no PII by default) */
30
+ metadata?: Record<string, unknown>;
31
+ }
32
+ export interface AuditTransport {
33
+ /** Send an audit event to the transport (e.g. console, DB, external service) */
34
+ log(event: AuditEvent): void | Promise<void>;
35
+ }
36
+ export interface AuditModuleOptions {
37
+ /** Transports to use (default: console) */
38
+ transports?: AuditTransport[];
39
+ /** Include request context (method, path) in auto-audit events */
40
+ includeRequestContext?: boolean;
41
+ /** Redact sensitive keys from metadata */
42
+ redactKeys?: string[];
43
+ }
44
+ //# sourceMappingURL=audit.types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.types.d.ts","sourceRoot":"","sources":["../src/audit.types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,GAAG,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,UAAU;IACzB,4DAA4D;IAC5D,MAAM,EAAE,MAAM,CAAC;IACf,oEAAoE;IACpE,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB,0DAA0D;IAC1D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,2CAA2C;IAC3C,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC7B,wCAAwC;IACxC,MAAM,CAAC,EAAE,SAAS,GAAG,SAAS,GAAG,QAAQ,CAAC;IAC1C,oBAAoB;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,4CAA4C;IAC5C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,yCAAyC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sCAAsC;IACtC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,MAAM,WAAW,cAAc;IAC7B,gFAAgF;IAChF,GAAG,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9C;AAED,MAAM,WAAW,kBAAkB;IACjC,2CAA2C;IAC3C,UAAU,CAAC,EAAE,cAAc,EAAE,CAAC;IAC9B,kEAAkE;IAClE,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,0CAA0C;IAC1C,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;CACvB"}
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * Audit event and module options
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @Audit - Mark a handler or method as audited with custom action/resource
3
+ */
4
+ export interface AuditDecoratorOptions {
5
+ /** Action name (e.g. 'order.create', 'user.login') */
6
+ action: string;
7
+ /** Resource type or name (e.g. 'Order', 'User') */
8
+ resource?: string;
9
+ /** Include result in audit (success/failure from return or throw) */
10
+ includeResult?: boolean;
11
+ }
12
+ export declare function Audit(options: AuditDecoratorOptions | string): MethodDecorator;
13
+ export declare function getAuditMetadata(target: object, propertyKey: string | symbol): AuditDecoratorOptions | undefined;
14
+ export declare function hasAuditMetadata(target: object, propertyKey: string | symbol): boolean;
15
+ //# sourceMappingURL=audit.decorator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.decorator.d.ts","sourceRoot":"","sources":["../../src/decorators/audit.decorator.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,MAAM,WAAW,qBAAqB;IACpC,sDAAsD;IACtD,MAAM,EAAE,MAAM,CAAC;IACf,mDAAmD;IACnD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,qEAAqE;IACrE,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,wBAAgB,KAAK,CAAC,OAAO,EAAE,qBAAqB,GAAG,MAAM,GAAG,eAAe,CAS9E;AAED,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,GAAG,MAAM,GAC3B,qBAAqB,GAAG,SAAS,CAEnC;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAEtF"}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /**
3
+ * @Audit - Mark a handler or method as audited with custom action/resource
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Audit = Audit;
7
+ exports.getAuditMetadata = getAuditMetadata;
8
+ exports.hasAuditMetadata = hasAuditMetadata;
9
+ const AUDIT_METADATA_KEY = 'hazel:audit';
10
+ function Audit(options) {
11
+ const opts = typeof options === 'string' ? { action: options } : options;
12
+ return function (target, propertyKey, _descriptor) {
13
+ Reflect.defineMetadata(AUDIT_METADATA_KEY, opts, target, propertyKey);
14
+ };
15
+ }
16
+ function getAuditMetadata(target, propertyKey) {
17
+ return Reflect.getMetadata(AUDIT_METADATA_KEY, target, propertyKey);
18
+ }
19
+ function hasAuditMetadata(target, propertyKey) {
20
+ return Reflect.hasMetadata(AUDIT_METADATA_KEY, target, propertyKey);
21
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @hazeljs/audit - Audit logging and event trail for HazelJS
3
+ */
4
+ export { AuditModule, AUDIT_SERVICE_TOKEN } from './audit.module';
5
+ export { AuditService } from './audit.service';
6
+ export { AuditInterceptor } from './interceptors/audit.interceptor';
7
+ export { ConsoleAuditTransport } from './transports/console.transport';
8
+ export { FileAuditTransport } from './transports/file.transport';
9
+ export { KafkaAuditTransport } from './transports/kafka.transport';
10
+ export { Audit, getAuditMetadata, hasAuditMetadata } from './decorators/audit.decorator';
11
+ export type { AuditEvent, AuditActor, AuditTransport, AuditModuleOptions } from './audit.types';
12
+ export type { AuditDecoratorOptions } from './decorators/audit.decorator';
13
+ export type { AuditInterceptorOptions } from './interceptors/audit.interceptor';
14
+ export type { FileAuditTransportOptions } from './transports/file.transport';
15
+ export type { KafkaAuditTransportOptions, KafkaAuditSender, KafkaAuditSerializer, } from './transports/kafka.transport';
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAEzF,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAChG,YAAY,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAC1E,YAAY,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAChF,YAAY,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAC7E,YAAY,EACV,0BAA0B,EAC1B,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,8BAA8B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ /**
3
+ * @hazeljs/audit - Audit logging and event trail for HazelJS
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.hasAuditMetadata = exports.getAuditMetadata = exports.Audit = exports.KafkaAuditTransport = exports.FileAuditTransport = exports.ConsoleAuditTransport = exports.AuditInterceptor = exports.AuditService = exports.AUDIT_SERVICE_TOKEN = exports.AuditModule = void 0;
7
+ var audit_module_1 = require("./audit.module");
8
+ Object.defineProperty(exports, "AuditModule", { enumerable: true, get: function () { return audit_module_1.AuditModule; } });
9
+ Object.defineProperty(exports, "AUDIT_SERVICE_TOKEN", { enumerable: true, get: function () { return audit_module_1.AUDIT_SERVICE_TOKEN; } });
10
+ var audit_service_1 = require("./audit.service");
11
+ Object.defineProperty(exports, "AuditService", { enumerable: true, get: function () { return audit_service_1.AuditService; } });
12
+ var audit_interceptor_1 = require("./interceptors/audit.interceptor");
13
+ Object.defineProperty(exports, "AuditInterceptor", { enumerable: true, get: function () { return audit_interceptor_1.AuditInterceptor; } });
14
+ var console_transport_1 = require("./transports/console.transport");
15
+ Object.defineProperty(exports, "ConsoleAuditTransport", { enumerable: true, get: function () { return console_transport_1.ConsoleAuditTransport; } });
16
+ var file_transport_1 = require("./transports/file.transport");
17
+ Object.defineProperty(exports, "FileAuditTransport", { enumerable: true, get: function () { return file_transport_1.FileAuditTransport; } });
18
+ var kafka_transport_1 = require("./transports/kafka.transport");
19
+ Object.defineProperty(exports, "KafkaAuditTransport", { enumerable: true, get: function () { return kafka_transport_1.KafkaAuditTransport; } });
20
+ var audit_decorator_1 = require("./decorators/audit.decorator");
21
+ Object.defineProperty(exports, "Audit", { enumerable: true, get: function () { return audit_decorator_1.Audit; } });
22
+ Object.defineProperty(exports, "getAuditMetadata", { enumerable: true, get: function () { return audit_decorator_1.getAuditMetadata; } });
23
+ Object.defineProperty(exports, "hasAuditMetadata", { enumerable: true, get: function () { return audit_decorator_1.hasAuditMetadata; } });
@@ -0,0 +1,18 @@
1
+ /**
2
+ * AuditInterceptor - Log HTTP requests as audit events
3
+ */
4
+ import type { Interceptor } from '@hazeljs/core';
5
+ import type { RequestContext } from '@hazeljs/core';
6
+ import { AuditService } from '../audit.service';
7
+ export interface AuditInterceptorOptions {
8
+ /** Only audit these HTTP methods (default: all) */
9
+ methods?: string[];
10
+ /** Path patterns to skip (e.g. ['/health', '/metrics']) */
11
+ excludePaths?: string[];
12
+ }
13
+ export declare class AuditInterceptor implements Interceptor {
14
+ private readonly auditService;
15
+ constructor(auditService: AuditService);
16
+ intercept(context: RequestContext, next: () => Promise<unknown>): Promise<unknown>;
17
+ }
18
+ //# sourceMappingURL=audit.interceptor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.interceptor.d.ts","sourceRoot":"","sources":["../../src/interceptors/audit.interceptor.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEhD,MAAM,WAAW,uBAAuB;IACtC,mDAAmD;IACnD,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,2DAA2D;IAC3D,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB;AAED,qBACa,gBAAiB,YAAW,WAAW;IACtC,OAAO,CAAC,QAAQ,CAAC,YAAY;gBAAZ,YAAY,EAAE,YAAY;IAEjD,SAAS,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;CAYzF"}
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ /**
3
+ * AuditInterceptor - Log HTTP requests as audit events
4
+ */
5
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
6
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
7
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
8
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
9
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
10
+ };
11
+ var __metadata = (this && this.__metadata) || function (k, v) {
12
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.AuditInterceptor = void 0;
16
+ const core_1 = require("@hazeljs/core");
17
+ const audit_service_1 = require("../audit.service");
18
+ let AuditInterceptor = class AuditInterceptor {
19
+ constructor(auditService) {
20
+ this.auditService = auditService;
21
+ }
22
+ async intercept(context, next) {
23
+ let result = 'success';
24
+ try {
25
+ return await next();
26
+ }
27
+ catch (_err) {
28
+ result = 'failure';
29
+ throw _err;
30
+ }
31
+ finally {
32
+ const action = context.method ? `http.${context.method.toLowerCase()}` : 'http.request';
33
+ this.auditService.log(this.auditService.eventFromContext(context, result, action));
34
+ }
35
+ }
36
+ };
37
+ exports.AuditInterceptor = AuditInterceptor;
38
+ exports.AuditInterceptor = AuditInterceptor = __decorate([
39
+ (0, core_1.Injectable)(),
40
+ __metadata("design:paramtypes", [audit_service_1.AuditService])
41
+ ], AuditInterceptor);
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Console audit transport - logs events to stdout as JSON
3
+ */
4
+ import type { AuditTransport, AuditEvent } from '../audit.types';
5
+ export declare class ConsoleAuditTransport implements AuditTransport {
6
+ log(event: AuditEvent): void;
7
+ }
8
+ //# sourceMappingURL=console.transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console.transport.d.ts","sourceRoot":"","sources":["../../src/transports/console.transport.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEjE,qBAAa,qBAAsB,YAAW,cAAc;IAC1D,GAAG,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI;CAO7B"}
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ /**
3
+ * Console audit transport - logs events to stdout as JSON
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ConsoleAuditTransport = void 0;
7
+ class ConsoleAuditTransport {
8
+ log(event) {
9
+ const line = JSON.stringify({
10
+ ...event,
11
+ _type: 'audit',
12
+ });
13
+ process.stdout.write(line + '\n');
14
+ }
15
+ }
16
+ exports.ConsoleAuditTransport = ConsoleAuditTransport;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * File audit transport — appends one JSON line per event. Supports rotation by size or by day.
3
+ * Parent directory is created at startup (when ensureDir is true); the file itself is created on first audit event.
4
+ */
5
+ import type { AuditTransport, AuditEvent } from '../audit.types';
6
+ export interface FileAuditTransportOptions {
7
+ /** Base path, e.g. logs/audit.jsonl. With rollDaily, becomes logs/audit.2025-03-01.jsonl */
8
+ filePath: string;
9
+ /** Create parent directory if missing (default: true) */
10
+ ensureDir?: boolean;
11
+ /** Rotate when file exceeds this size (bytes). Default: no rotation. Example: 10 * 1024 * 1024 = 10MB */
12
+ maxSizeBytes?: number;
13
+ /** Use one file per day (filename gets .YYYY-MM-DD before extension). Default: false */
14
+ rollDaily?: boolean;
15
+ }
16
+ export declare class FileAuditTransport implements AuditTransport {
17
+ private readonly basePath;
18
+ private readonly ensureDir;
19
+ private readonly maxSizeBytes;
20
+ private readonly rollDaily;
21
+ /** Current write path (can change when rolling) */
22
+ private currentPath;
23
+ constructor(options: FileAuditTransportOptions);
24
+ private resolveCurrentPath;
25
+ private ensureCurrentPath;
26
+ private shouldRollBySize;
27
+ log(event: AuditEvent): void;
28
+ }
29
+ //# sourceMappingURL=file.transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file.transport.d.ts","sourceRoot":"","sources":["../../src/transports/file.transport.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEjE,MAAM,WAAW,yBAAyB;IACxC,4FAA4F;IAC5F,QAAQ,EAAE,MAAM,CAAC;IACjB,yDAAyD;IACzD,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,yGAAyG;IACzG,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,wFAAwF;IACxF,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAUD,qBAAa,kBAAmB,YAAW,cAAc;IACvD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAU;IACpC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAqB;IAClD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAU;IAEpC,mDAAmD;IACnD,OAAO,CAAC,WAAW,CAAS;gBAEhB,OAAO,EAAE,yBAAyB;IAyB9C,OAAO,CAAC,kBAAkB;IAO1B,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,gBAAgB;IAWxB,GAAG,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI;CAe7B"}
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ /**
3
+ * File audit transport — appends one JSON line per event. Supports rotation by size or by day.
4
+ * Parent directory is created at startup (when ensureDir is true); the file itself is created on first audit event.
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.FileAuditTransport = void 0;
41
+ const fs = __importStar(require("fs"));
42
+ const path = __importStar(require("path"));
43
+ function getDateSuffix() {
44
+ const now = new Date();
45
+ const y = now.getFullYear();
46
+ const m = String(now.getMonth() + 1).padStart(2, '0');
47
+ const d = String(now.getDate()).padStart(2, '0');
48
+ return `${y}-${m}-${d}`;
49
+ }
50
+ class FileAuditTransport {
51
+ constructor(options) {
52
+ this.basePath = path.isAbsolute(options.filePath)
53
+ ? options.filePath
54
+ : path.resolve(process.cwd(), options.filePath);
55
+ this.ensureDir = options.ensureDir !== false;
56
+ this.maxSizeBytes = options.maxSizeBytes;
57
+ this.rollDaily = options.rollDaily ?? false;
58
+ this.currentPath = this.resolveCurrentPath();
59
+ // Create directory and touch file at startup so the path is visible and writable before first event
60
+ if (this.ensureDir) {
61
+ const dir = path.dirname(this.currentPath);
62
+ if (!fs.existsSync(dir)) {
63
+ fs.mkdirSync(dir, { recursive: true });
64
+ }
65
+ }
66
+ // Ensure file exists so consumers see it immediately and first append succeeds
67
+ try {
68
+ if (!fs.existsSync(this.currentPath)) {
69
+ fs.writeFileSync(this.currentPath, '', 'utf8');
70
+ }
71
+ }
72
+ catch {
73
+ // ignore (e.g. permission); appendFileSync in log() will create on first write
74
+ }
75
+ }
76
+ resolveCurrentPath() {
77
+ if (!this.rollDaily)
78
+ return this.basePath;
79
+ const ext = path.extname(this.basePath);
80
+ const base = this.basePath.slice(0, -ext.length);
81
+ return `${base}.${getDateSuffix()}${ext}`;
82
+ }
83
+ ensureCurrentPath() {
84
+ if (this.ensureDir) {
85
+ const dir = path.dirname(this.currentPath);
86
+ if (!fs.existsSync(dir)) {
87
+ fs.mkdirSync(dir, { recursive: true });
88
+ }
89
+ }
90
+ }
91
+ shouldRollBySize() {
92
+ if (this.maxSizeBytes == null)
93
+ return false;
94
+ if (!fs.existsSync(this.currentPath))
95
+ return false;
96
+ try {
97
+ const stat = fs.statSync(this.currentPath);
98
+ return stat.size >= this.maxSizeBytes;
99
+ }
100
+ catch {
101
+ return false;
102
+ }
103
+ }
104
+ log(event) {
105
+ if (this.rollDaily) {
106
+ const next = this.resolveCurrentPath();
107
+ if (next !== this.currentPath)
108
+ this.currentPath = next;
109
+ }
110
+ if (this.shouldRollBySize()) {
111
+ const ext = path.extname(this.basePath);
112
+ const base = this.basePath.slice(0, -ext.length);
113
+ this.currentPath = `${base}.${Date.now()}${ext}`;
114
+ }
115
+ this.ensureCurrentPath();
116
+ const line = JSON.stringify({ ...event, _type: 'audit' }) + '\n';
117
+ fs.appendFileSync(this.currentPath, line, 'utf8');
118
+ }
119
+ }
120
+ exports.FileAuditTransport = FileAuditTransport;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Kafka audit transport — sends each audit event to a Kafka topic.
3
+ * Use with @hazeljs/kafka: pass KafkaProducerService as the sender.
4
+ * Supports JSON (default) or custom serialization (e.g. Avro via a serialize function).
5
+ */
6
+ import type { AuditEvent, AuditTransport } from '../audit.types';
7
+ /**
8
+ * Minimal sender interface so this package does not depend on @hazeljs/kafka.
9
+ * KafkaProducerService from @hazeljs/kafka implements this.
10
+ * Value can be string (JSON) or Buffer (e.g. Avro-encoded).
11
+ */
12
+ export interface KafkaAuditSender {
13
+ send(topic: string, messages: {
14
+ key?: string;
15
+ value: string | Buffer;
16
+ } | Array<{
17
+ key?: string;
18
+ value: string | Buffer;
19
+ }>): Promise<void>;
20
+ }
21
+ /**
22
+ * Serialize an audit event for Kafka. Return string (JSON) or Buffer (e.g. Avro).
23
+ * For Avro: use `avsc` or Confluent Schema Registry and return the encoded Buffer.
24
+ */
25
+ export type KafkaAuditSerializer = (event: AuditEvent) => string | Buffer | Promise<string | Buffer>;
26
+ export interface KafkaAuditTransportOptions {
27
+ /** Sender that can send messages to Kafka (e.g. KafkaProducerService from @hazeljs/kafka) */
28
+ sender: KafkaAuditSender;
29
+ /** Topic to publish audit events to */
30
+ topic: string;
31
+ /** Optional key for partitioning (e.g. by actor id or resource) */
32
+ key?: (event: AuditEvent) => string | undefined;
33
+ /**
34
+ * Serialize event before sending. Default: JSON.stringify.
35
+ * For Avro: pass a function that encodes the event to Buffer (e.g. using avsc or @kafkajs/confluent-schema-registry).
36
+ */
37
+ serialize?: KafkaAuditSerializer;
38
+ }
39
+ export declare class KafkaAuditTransport implements AuditTransport {
40
+ private readonly sender;
41
+ private readonly topic;
42
+ private readonly keyFn;
43
+ private readonly serialize;
44
+ constructor(options: KafkaAuditTransportOptions);
45
+ log(event: AuditEvent): Promise<void>;
46
+ }
47
+ //# sourceMappingURL=kafka.transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kafka.transport.d.ts","sourceRoot":"","sources":["../../src/transports/kafka.transport.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEjE;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,IAAI,CACF,KAAK,EAAE,MAAM,EACb,QAAQ,EACJ;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,GACxC,KAAK,CAAC;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAC,GAClD,OAAO,CAAC,IAAI,CAAC,CAAC;CAClB;AAED;;;GAGG;AACH,MAAM,MAAM,oBAAoB,GAAG,CACjC,KAAK,EAAE,UAAU,KACd,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;AAEhD,MAAM,WAAW,0BAA0B;IACzC,6FAA6F;IAC7F,MAAM,EAAE,gBAAgB,CAAC;IACzB,uCAAuC;IACvC,KAAK,EAAE,MAAM,CAAC;IACd,mEAAmE;IACnE,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,MAAM,GAAG,SAAS,CAAC;IAChD;;;OAGG;IACH,SAAS,CAAC,EAAE,oBAAoB,CAAC;CAClC;AAMD,qBAAa,mBAAoB,YAAW,cAAc;IACxD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmB;IAC1C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA0D;IAChF,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAuB;gBAErC,OAAO,EAAE,0BAA0B;IAOzC,GAAG,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;CAK5C"}
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ /**
3
+ * Kafka audit transport — sends each audit event to a Kafka topic.
4
+ * Use with @hazeljs/kafka: pass KafkaProducerService as the sender.
5
+ * Supports JSON (default) or custom serialization (e.g. Avro via a serialize function).
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.KafkaAuditTransport = void 0;
9
+ function defaultSerialize(event) {
10
+ return JSON.stringify(event);
11
+ }
12
+ class KafkaAuditTransport {
13
+ constructor(options) {
14
+ this.sender = options.sender;
15
+ this.topic = options.topic;
16
+ this.keyFn = options.key;
17
+ this.serialize = options.serialize ?? defaultSerialize;
18
+ }
19
+ async log(event) {
20
+ const value = await Promise.resolve(this.serialize(event));
21
+ const key = this.keyFn?.(event);
22
+ return this.sender.send(this.topic, key != null ? { key, value } : { value });
23
+ }
24
+ }
25
+ exports.KafkaAuditTransport = KafkaAuditTransport;
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@hazeljs/audit",
3
+ "version": "0.2.0-beta.52",
4
+ "description": "Audit logging and event trail for HazelJS applications",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsc",
12
+ "test": "jest --coverage --passWithNoTests",
13
+ "lint": "eslint \"src/**/*.ts\"",
14
+ "lint:fix": "eslint \"src/**/*.ts\" --fix",
15
+ "clean": "rm -rf dist"
16
+ },
17
+ "devDependencies": {
18
+ "@types/jest": "^29.5.11",
19
+ "@types/node": "^20.17.50",
20
+ "@typescript-eslint/eslint-plugin": "^8.18.2",
21
+ "@typescript-eslint/parser": "^8.18.2",
22
+ "eslint": "^8.56.0",
23
+ "jest": "^29.7.0",
24
+ "ts-jest": "^29.1.2",
25
+ "typescript": "^5.3.3"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/hazel-js/hazeljs.git",
33
+ "directory": "packages/audit"
34
+ },
35
+ "keywords": [
36
+ "hazeljs",
37
+ "audit",
38
+ "audit-log",
39
+ "audit-trail",
40
+ "compliance",
41
+ "logging"
42
+ ],
43
+ "author": "Muhammad Arslan <muhammad.arslan@hazeljs.com>",
44
+ "license": "Apache-2.0",
45
+ "bugs": {
46
+ "url": "https://github.com/hazeljs/hazel-js/issues"
47
+ },
48
+ "homepage": "https://hazeljs.com",
49
+ "peerDependencies": {
50
+ "@hazeljs/core": ">=0.2.0-beta.0"
51
+ },
52
+ "gitHead": "416ae971cf8fc45ab53df8cd6f43ad40439ef2f2"
53
+ }