@nathapp/nestjs-audit 4.0.0 → 4.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/package.json +6 -6
- package/.eslintrc.js +0 -8
- package/.turbo/turbo-build.log +0 -4
- package/CHANGELOG.md +0 -35
- package/lib/constant/audit.constants.ts +0 -14
- package/lib/constant/index.ts +0 -1
- package/lib/decorator/audit.decorator.ts +0 -13
- package/lib/decorator/index.ts +0 -1
- package/lib/index.ts +0 -6
- package/lib/interceptor/audit.interceptor.ts +0 -84
- package/lib/interceptor/index.ts +0 -1
- package/lib/interface/audit-actor-resolver.interface.ts +0 -6
- package/lib/interface/audit-entry.interface.ts +0 -24
- package/lib/interface/audit-module-options.interface.ts +0 -25
- package/lib/interface/audit-storage.interface.ts +0 -6
- package/lib/interface/index.ts +0 -4
- package/lib/module/audit.module.ts +0 -45
- package/lib/module/index.ts +0 -1
- package/lib/provider/default-actor-resolver.ts +0 -11
- package/lib/provider/in-memory-audit-storage.ts +0 -31
- package/lib/provider/index.ts +0 -3
- package/lib/provider/logger-audit-storage.ts +0 -29
- package/test/constant/audit.constants.spec.ts +0 -20
- package/test/decorator/audit.decorator.spec.ts +0 -50
- package/test/interceptor/audit.interceptor.spec.ts +0 -241
- package/test/jest-nax.json +0 -27
- package/test/jest-test.json +0 -28
- package/test/module/audit.module.spec.ts +0 -89
- package/test/provider/default-actor-resolver.spec.ts +0 -33
- package/test/provider/in-memory-audit-storage.spec.ts +0 -77
- package/test/provider/logger-audit-storage.spec.ts +0 -55
- package/tsconfig.json +0 -9
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nathapp/nestjs-audit",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.1",
|
|
4
4
|
"description": "Decorator-driven, storage-agnostic audit logging for NestJS applications",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -28,18 +28,18 @@
|
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"@nathapp/eslint-config": "1.0.1",
|
|
31
|
-
"@nathapp/nestjs-common": "^4.0.
|
|
32
|
-
"@nathapp/nestjs-logging": "^4.0.
|
|
31
|
+
"@nathapp/nestjs-common": "^4.0.1",
|
|
32
|
+
"@nathapp/nestjs-logging": "^4.0.1",
|
|
33
33
|
"@nathapp/typescript-config": "1.0.1",
|
|
34
34
|
"@nestjs/common": "^11.0.0",
|
|
35
35
|
"@nestjs/core": "^11.0.0",
|
|
36
36
|
"@nestjs/testing": "^11.0.0",
|
|
37
|
-
"@types/jest": "^
|
|
37
|
+
"@types/jest": "^30.0.0",
|
|
38
38
|
"eslint": "^8.57.0",
|
|
39
|
-
"jest": "^
|
|
39
|
+
"jest": "^30.5.2",
|
|
40
40
|
"reflect-metadata": "^0.1.13",
|
|
41
41
|
"rxjs": "^7.8.0",
|
|
42
|
-
"ts-jest": "^29.
|
|
42
|
+
"ts-jest": "^29.4.14",
|
|
43
43
|
"typescript": "^5"
|
|
44
44
|
},
|
|
45
45
|
"directories": {
|
package/.eslintrc.js
DELETED
package/.turbo/turbo-build.log
DELETED
package/CHANGELOG.md
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
# @nathapp/nestjs-audit
|
|
2
|
-
|
|
3
|
-
## 4.0.0
|
|
4
|
-
|
|
5
|
-
### Major Changes
|
|
6
|
-
|
|
7
|
-
- 2319e9d: BREAKING: drop NestJS 8/9 peer ranges and require Node ^20.19.0 || >=22.12.0. Support NestJS 12. Peer ranges now cover NestJS 10, 11 and 12 (Node ^20.19.0 || >=22.12.0 is required because NestJS 12 is ESM-only). The configurable module builder no longer deep-imports a directory that is unresolvable on NestJS 12, and TwoFactorGuard / TwoFactorForceGuard redeclare their constructor DI metadata because NestJS 12 no longer inherits @Optional() from base classes.
|
|
8
|
-
|
|
9
|
-
Other consumer-facing changes:
|
|
10
|
-
|
|
11
|
-
- `@nathapp/nestjs-health`: `@nestjs/terminus` moved from `dependencies` to `peerDependencies` (`^11.0.0 || ^12.0.0`) so NestJS 12 apps can use terminus 12. Install `@nestjs/terminus` in your app.
|
|
12
|
-
- Optional-package loading (`loadPackage`) now throws a descriptive `Error` (original error on `cause`) instead of logging and calling `process.exit(1)` when an optional package is missing.
|
|
13
|
-
|
|
14
|
-
## 4.0.0-rc.0
|
|
15
|
-
|
|
16
|
-
### Major Changes
|
|
17
|
-
|
|
18
|
-
- c3aeb46: BREAKING: drop NestJS 8/9 peer ranges and require Node ^20.19.0 || >=22.12.0. Support NestJS 12. Peer ranges now cover NestJS 10, 11 and 12 (Node ^20.19.0 || >=22.12.0 is required because NestJS 12 is ESM-only). The configurable module builder no longer deep-imports a directory that is unresolvable on NestJS 12, and TwoFactorGuard / TwoFactorForceGuard redeclare their constructor DI metadata because NestJS 12 no longer inherits @Optional() from base classes.
|
|
19
|
-
|
|
20
|
-
Other consumer-facing changes:
|
|
21
|
-
|
|
22
|
-
- `@nathapp/nestjs-health`: `@nestjs/terminus` moved from `dependencies` to `peerDependencies` (`^11.0.0 || ^12.0.0`) so NestJS 12 apps can use terminus 12. Install `@nestjs/terminus` in your app.
|
|
23
|
-
- Optional-package loading (`loadPackage`) now throws a descriptive `Error` (original error on `cause`) instead of logging and calling `process.exit(1)` when an optional package is missing.
|
|
24
|
-
|
|
25
|
-
### Patch Changes
|
|
26
|
-
|
|
27
|
-
- Updated dependencies [c3aeb46]
|
|
28
|
-
- @nathapp/nestjs-common@4.0.0-rc.0
|
|
29
|
-
- @nathapp/nestjs-logging@4.0.0-rc.0
|
|
30
|
-
|
|
31
|
-
## 3.3.0
|
|
32
|
-
|
|
33
|
-
### Minor Changes
|
|
34
|
-
|
|
35
|
-
- 1f2614b: Add @nathapp/nestjs-audit: decorator-driven, storage-agnostic audit logging (@Audit() decorator, AuditInterceptor, pluggable IAuditStorage/IAuditActorResolver seams, InMemoryAuditStorage + LoggerAuditStorage + DefaultActorResolver, AuditModule).
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* DI token for the pluggable audit storage seam.
|
|
3
|
-
* Uses Symbol.for so the token is identical across realms / duplicate installs.
|
|
4
|
-
*/
|
|
5
|
-
export const AUDIT_STORAGE = Symbol.for('AUDIT_STORAGE');
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* DI token for the pluggable actor-resolution seam.
|
|
9
|
-
* Uses Symbol.for so the token is identical across realms / duplicate installs.
|
|
10
|
-
*/
|
|
11
|
-
export const AUDIT_ACTOR_RESOLVER = Symbol.for('AUDIT_ACTOR_RESOLVER');
|
|
12
|
-
|
|
13
|
-
/** Options token consumed by AuditModule (ConfigurableModuleClass). */
|
|
14
|
-
export const AUDIT_MODULE_OPTIONS = 'AUDIT_MODULE_OPTIONS';
|
package/lib/constant/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './audit.constants';
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { SetMetadata } from '@nestjs/common';
|
|
2
|
-
|
|
3
|
-
export const AUDIT_METADATA_KEY = 'AUDIT_METADATA_KEY';
|
|
4
|
-
|
|
5
|
-
export interface AuditDecoratorOptions {
|
|
6
|
-
action: string;
|
|
7
|
-
resource?: string;
|
|
8
|
-
/** Route param name to read resourceId from, e.g. 'id'. */
|
|
9
|
-
resourceIdParam?: string;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export const Audit = (options: AuditDecoratorOptions) =>
|
|
13
|
-
SetMetadata(AUDIT_METADATA_KEY, options);
|
package/lib/decorator/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './audit.decorator';
|
package/lib/index.ts
DELETED
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
CallHandler,
|
|
3
|
-
ExecutionContext,
|
|
4
|
-
Inject,
|
|
5
|
-
Injectable,
|
|
6
|
-
Logger,
|
|
7
|
-
NestInterceptor,
|
|
8
|
-
} from '@nestjs/common';
|
|
9
|
-
import { Reflector } from '@nestjs/core';
|
|
10
|
-
import { Observable } from 'rxjs';
|
|
11
|
-
import { tap } from 'rxjs/operators';
|
|
12
|
-
import { CLOCK, IClock } from '@nathapp/nestjs-common';
|
|
13
|
-
import { RequestContextService } from '@nathapp/nestjs-logging';
|
|
14
|
-
import { AUDIT_METADATA_KEY, AuditDecoratorOptions } from '../decorator';
|
|
15
|
-
import { AUDIT_ACTOR_RESOLVER, AUDIT_STORAGE } from '../constant';
|
|
16
|
-
import { AuditEntry, IAuditActorResolver, IAuditStorage } from '../interface';
|
|
17
|
-
|
|
18
|
-
@Injectable()
|
|
19
|
-
export class AuditInterceptor implements NestInterceptor {
|
|
20
|
-
private readonly logger = new Logger(AuditInterceptor.name);
|
|
21
|
-
|
|
22
|
-
constructor(
|
|
23
|
-
private readonly reflector: Reflector,
|
|
24
|
-
@Inject(AUDIT_STORAGE) private readonly storage: IAuditStorage,
|
|
25
|
-
@Inject(AUDIT_ACTOR_RESOLVER) private readonly actorResolver: IAuditActorResolver,
|
|
26
|
-
@Inject(CLOCK) private readonly clock: IClock,
|
|
27
|
-
private readonly requestContext: RequestContextService,
|
|
28
|
-
) {}
|
|
29
|
-
|
|
30
|
-
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
|
31
|
-
const options = this.reflector.get<AuditDecoratorOptions | undefined>(
|
|
32
|
-
AUDIT_METADATA_KEY,
|
|
33
|
-
context.getHandler(),
|
|
34
|
-
);
|
|
35
|
-
|
|
36
|
-
if (!options) {
|
|
37
|
-
return next.handle();
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// Audit entries are built from `request.user` / `request.params` via
|
|
41
|
-
// switchToHttp(). Non-http transports (rpc, ws) do not populate those, so
|
|
42
|
-
// resolving here would silently produce a misleading `actor: 'anonymous'`
|
|
43
|
-
// entry instead of the real principal. Skip cleanly rather than record a
|
|
44
|
-
// wrong audit trail; non-http actor resolution is out of scope for now.
|
|
45
|
-
if (context.getType() !== 'http') {
|
|
46
|
-
// A decorated @Audit() handler produced zero audit entries. This is intentional
|
|
47
|
-
// for hybrid apps that reuse an audited handler over rpc/ws, but it is also
|
|
48
|
-
// indistinguishable from a developer mistakenly decorating a non-http handler.
|
|
49
|
-
// Warn so the audit-coverage gap is discoverable in logs rather than silent.
|
|
50
|
-
this.logger.warn(
|
|
51
|
-
`@Audit() handler skipped: non-http transport (${context.getType()}) is not supported, ` +
|
|
52
|
-
`no audit entry was recorded for action "${options.action}".`,
|
|
53
|
-
);
|
|
54
|
-
return next.handle();
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
return next.handle().pipe(
|
|
58
|
-
tap(() => {
|
|
59
|
-
const entry = this.buildEntry(context, options);
|
|
60
|
-
this.storage.record(entry).catch((err) => {
|
|
61
|
-
this.logger.error('Audit write failed', err?.stack, JSON.stringify({ entry }));
|
|
62
|
-
});
|
|
63
|
-
}),
|
|
64
|
-
);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
private buildEntry(context: ExecutionContext, options: AuditDecoratorOptions): AuditEntry {
|
|
68
|
-
const actor = this.actorResolver.resolve(context);
|
|
69
|
-
const request = context.switchToHttp().getRequest();
|
|
70
|
-
const resourceId = options.resourceIdParam
|
|
71
|
-
? request?.params?.[options.resourceIdParam]
|
|
72
|
-
: undefined;
|
|
73
|
-
|
|
74
|
-
return {
|
|
75
|
-
action: options.action,
|
|
76
|
-
actor,
|
|
77
|
-
resource: options.resource,
|
|
78
|
-
resourceId,
|
|
79
|
-
correlationId: this.requestContext.get('requestId'),
|
|
80
|
-
timestamp: this.clock.now(),
|
|
81
|
-
metadata: undefined,
|
|
82
|
-
};
|
|
83
|
-
}
|
|
84
|
-
}
|
package/lib/interceptor/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './audit.interceptor';
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
export interface AuditActor {
|
|
2
|
-
id: string;
|
|
3
|
-
type?: string;
|
|
4
|
-
metadata?: Record<string, unknown>;
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export interface AuditEntry {
|
|
8
|
-
action: string;
|
|
9
|
-
actor?: AuditActor;
|
|
10
|
-
resource?: string;
|
|
11
|
-
resourceId?: string;
|
|
12
|
-
correlationId?: string;
|
|
13
|
-
timestamp: Date;
|
|
14
|
-
metadata?: Record<string, unknown>;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export interface AuditQueryFilter {
|
|
18
|
-
action?: string;
|
|
19
|
-
actorId?: string;
|
|
20
|
-
resource?: string;
|
|
21
|
-
resourceId?: string;
|
|
22
|
-
from?: Date;
|
|
23
|
-
to?: Date;
|
|
24
|
-
}
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import type { ModuleMetadata, Type } from '@nestjs/common';
|
|
2
|
-
import { IAuditStorage } from './audit-storage.interface';
|
|
3
|
-
import { IAuditActorResolver } from './audit-actor-resolver.interface';
|
|
4
|
-
|
|
5
|
-
/** Override options for AuditModule. Omit fields to get the default provider for that seam. */
|
|
6
|
-
export interface AuditModuleOptions {
|
|
7
|
-
storage?: IAuditStorage;
|
|
8
|
-
actorResolver?: IAuditActorResolver;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
/** Factory contract for the `useClass` async path; method name matches the
|
|
12
|
-
* in-repo ConfigurableModuleBuilder default ('createOptions'). */
|
|
13
|
-
export interface AuditModuleOptionsFactory {
|
|
14
|
-
createOptions(): Promise<AuditModuleOptions> | AuditModuleOptions;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/** Async registration options for AuditModule. */
|
|
18
|
-
export interface AuditAsyncModuleOptions extends Pick<ModuleMetadata, 'imports'> {
|
|
19
|
-
useExisting?: Type<AuditModuleOptionsFactory>;
|
|
20
|
-
useClass?: Type<AuditModuleOptionsFactory>;
|
|
21
|
-
useFactory?: (
|
|
22
|
-
...args: any[]
|
|
23
|
-
) => Promise<AuditModuleOptions> | AuditModuleOptions;
|
|
24
|
-
inject?: any[];
|
|
25
|
-
}
|
package/lib/interface/index.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import { DynamicModule, Module } from '@nestjs/common';
|
|
2
|
-
import { ConfigurableModuleClass } from '@nathapp/nestjs-common';
|
|
3
|
-
import { RequestContextService } from '@nathapp/nestjs-logging';
|
|
4
|
-
import { AUDIT_ACTOR_RESOLVER, AUDIT_MODULE_OPTIONS, AUDIT_STORAGE } from '../constant';
|
|
5
|
-
import { AuditAsyncModuleOptions, AuditModuleOptions } from '../interface';
|
|
6
|
-
import { AuditInterceptor } from '../interceptor';
|
|
7
|
-
import { DefaultActorResolver, InMemoryAuditStorage } from '../provider';
|
|
8
|
-
|
|
9
|
-
@Module({
|
|
10
|
-
providers: [
|
|
11
|
-
RequestContextService,
|
|
12
|
-
{
|
|
13
|
-
provide: AUDIT_STORAGE,
|
|
14
|
-
useFactory: (options?: AuditModuleOptions) => options?.storage ?? new InMemoryAuditStorage(),
|
|
15
|
-
inject: [AUDIT_MODULE_OPTIONS],
|
|
16
|
-
},
|
|
17
|
-
{
|
|
18
|
-
provide: AUDIT_ACTOR_RESOLVER,
|
|
19
|
-
useFactory: (options?: AuditModuleOptions) =>
|
|
20
|
-
options?.actorResolver ?? new DefaultActorResolver(),
|
|
21
|
-
inject: [AUDIT_MODULE_OPTIONS],
|
|
22
|
-
},
|
|
23
|
-
AuditInterceptor,
|
|
24
|
-
],
|
|
25
|
-
exports: [AUDIT_STORAGE, AUDIT_ACTOR_RESOLVER, AuditInterceptor, RequestContextService],
|
|
26
|
-
})
|
|
27
|
-
export class AuditModule extends ConfigurableModuleClass<AuditModuleOptions>(
|
|
28
|
-
AUDIT_MODULE_OPTIONS,
|
|
29
|
-
) {
|
|
30
|
-
static register(options?: AuditModuleOptions): DynamicModule {
|
|
31
|
-
return {
|
|
32
|
-
...super.register(options ?? {}),
|
|
33
|
-
module: AuditModule,
|
|
34
|
-
global: true,
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
static registerAsync(options: AuditAsyncModuleOptions): DynamicModule {
|
|
39
|
-
return {
|
|
40
|
-
...super.registerAsync(options),
|
|
41
|
-
module: AuditModule,
|
|
42
|
-
global: true,
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
}
|
package/lib/module/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './audit.module';
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { ExecutionContext, Injectable } from '@nestjs/common';
|
|
2
|
-
import { AuditActor, IAuditActorResolver } from '../interface';
|
|
3
|
-
|
|
4
|
-
/** Default actor resolver: falls back to `req.user?.id ?? 'anonymous'`. */
|
|
5
|
-
@Injectable()
|
|
6
|
-
export class DefaultActorResolver implements IAuditActorResolver {
|
|
7
|
-
resolve(context: ExecutionContext): AuditActor | undefined {
|
|
8
|
-
const request = context.switchToHttp().getRequest();
|
|
9
|
-
return { id: request?.user?.id ?? 'anonymous' };
|
|
10
|
-
}
|
|
11
|
-
}
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { Injectable } from '@nestjs/common';
|
|
2
|
-
import { AuditEntry, AuditQueryFilter, IAuditStorage } from '../interface';
|
|
3
|
-
|
|
4
|
-
const DEFAULT_MAX_ENTRIES = 1000;
|
|
5
|
-
|
|
6
|
-
/** Bounded ring-buffer audit storage. Default AuditModule storage; suitable for tests/dev. */
|
|
7
|
-
@Injectable()
|
|
8
|
-
export class InMemoryAuditStorage implements IAuditStorage {
|
|
9
|
-
private readonly entries: AuditEntry[] = [];
|
|
10
|
-
|
|
11
|
-
constructor(private readonly maxEntries: number = DEFAULT_MAX_ENTRIES) {}
|
|
12
|
-
|
|
13
|
-
async record(entry: AuditEntry): Promise<void> {
|
|
14
|
-
this.entries.push(entry);
|
|
15
|
-
if (this.entries.length > this.maxEntries) {
|
|
16
|
-
this.entries.shift();
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
async query(filter: AuditQueryFilter = {}): Promise<AuditEntry[]> {
|
|
21
|
-
return this.entries.filter((entry) => {
|
|
22
|
-
if (filter.action && entry.action !== filter.action) return false;
|
|
23
|
-
if (filter.actorId && entry.actor?.id !== filter.actorId) return false;
|
|
24
|
-
if (filter.resource && entry.resource !== filter.resource) return false;
|
|
25
|
-
if (filter.resourceId && entry.resourceId !== filter.resourceId) return false;
|
|
26
|
-
if (filter.from && entry.timestamp < filter.from) return false;
|
|
27
|
-
if (filter.to && entry.timestamp > filter.to) return false;
|
|
28
|
-
return true;
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
}
|
package/lib/provider/index.ts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { Inject, Injectable } from '@nestjs/common';
|
|
2
|
-
import { InternalAppException } from '@nathapp/nestjs-common';
|
|
3
|
-
import { Logger, LOGGER_SERVICE } from '@nathapp/nestjs-logging';
|
|
4
|
-
import { AuditEntry, IAuditStorage } from '../interface';
|
|
5
|
-
|
|
6
|
-
/** Writes audit entries as structured log lines. Opt-in; relies on external log
|
|
7
|
-
* aggregation for querying, so query() always rejects. */
|
|
8
|
-
@Injectable()
|
|
9
|
-
export class LoggerAuditStorage implements IAuditStorage {
|
|
10
|
-
constructor(@Inject(LOGGER_SERVICE) private readonly logger: Logger) {}
|
|
11
|
-
|
|
12
|
-
async record(entry: AuditEntry): Promise<void> {
|
|
13
|
-
this.logger.log('AUDIT', {
|
|
14
|
-
action: entry.action,
|
|
15
|
-
actor: entry.actor,
|
|
16
|
-
resource: entry.resource,
|
|
17
|
-
resourceId: entry.resourceId,
|
|
18
|
-
correlationId: entry.correlationId,
|
|
19
|
-
timestamp: entry.timestamp.toISOString(),
|
|
20
|
-
metadata: entry.metadata,
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
async query(): Promise<AuditEntry[]> {
|
|
25
|
-
throw new InternalAppException({
|
|
26
|
-
message: 'LoggerAuditStorage does not support query()',
|
|
27
|
-
});
|
|
28
|
-
}
|
|
29
|
-
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from '@jest/globals';
|
|
2
|
-
import {
|
|
3
|
-
AUDIT_ACTOR_RESOLVER,
|
|
4
|
-
AUDIT_MODULE_OPTIONS,
|
|
5
|
-
AUDIT_STORAGE,
|
|
6
|
-
} from '../../lib/constant/audit.constants';
|
|
7
|
-
|
|
8
|
-
describe('audit constants', () => {
|
|
9
|
-
it('AUDIT_STORAGE is a realm-safe Symbol.for token', () => {
|
|
10
|
-
expect(AUDIT_STORAGE).toBe(Symbol.for('AUDIT_STORAGE'));
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
it('AUDIT_ACTOR_RESOLVER is a realm-safe Symbol.for token', () => {
|
|
14
|
-
expect(AUDIT_ACTOR_RESOLVER).toBe(Symbol.for('AUDIT_ACTOR_RESOLVER'));
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
it('AUDIT_MODULE_OPTIONS is a string token', () => {
|
|
18
|
-
expect(AUDIT_MODULE_OPTIONS).toBe('AUDIT_MODULE_OPTIONS');
|
|
19
|
-
});
|
|
20
|
-
});
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from '@jest/globals';
|
|
2
|
-
import { Reflector } from '@nestjs/core';
|
|
3
|
-
import { AUDIT_METADATA_KEY, Audit } from '../../lib/decorator/audit.decorator';
|
|
4
|
-
|
|
5
|
-
describe('@Audit()', () => {
|
|
6
|
-
it('attaches AuditDecoratorOptions as reflect-metadata on the handler', () => {
|
|
7
|
-
class Controller {
|
|
8
|
-
@Audit({ action: 'USER_UPDATED', resource: 'user', resourceIdParam: 'id' })
|
|
9
|
-
updateUser() {
|
|
10
|
-
return undefined;
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
const reflector = new Reflector();
|
|
15
|
-
const options = reflector.get(AUDIT_METADATA_KEY, Controller.prototype.updateUser);
|
|
16
|
-
|
|
17
|
-
expect(options).toEqual({
|
|
18
|
-
action: 'USER_UPDATED',
|
|
19
|
-
resource: 'user',
|
|
20
|
-
resourceIdParam: 'id',
|
|
21
|
-
});
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
it('supports options with only the required action field', () => {
|
|
25
|
-
class Controller {
|
|
26
|
-
@Audit({ action: 'USER_DELETED' })
|
|
27
|
-
deleteUser() {
|
|
28
|
-
return undefined;
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const reflector = new Reflector();
|
|
33
|
-
const options = reflector.get(AUDIT_METADATA_KEY, Controller.prototype.deleteUser);
|
|
34
|
-
|
|
35
|
-
expect(options).toEqual({ action: 'USER_DELETED' });
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
it('a method without @Audit() has no metadata under AUDIT_METADATA_KEY', () => {
|
|
39
|
-
class Controller {
|
|
40
|
-
untouched() {
|
|
41
|
-
return undefined;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
const reflector = new Reflector();
|
|
46
|
-
const options = reflector.get(AUDIT_METADATA_KEY, Controller.prototype.untouched);
|
|
47
|
-
|
|
48
|
-
expect(options).toBeUndefined();
|
|
49
|
-
});
|
|
50
|
-
});
|
|
@@ -1,241 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, jest } from '@jest/globals';
|
|
2
|
-
import { CallHandler, ExecutionContext } from '@nestjs/common';
|
|
3
|
-
import { Reflector } from '@nestjs/core';
|
|
4
|
-
import { of, throwError } from 'rxjs';
|
|
5
|
-
import { IClock } from '@nathapp/nestjs-common';
|
|
6
|
-
import { RequestContextService } from '@nathapp/nestjs-logging';
|
|
7
|
-
import { IAuditActorResolver, IAuditStorage } from '../../lib/interface';
|
|
8
|
-
import { AuditInterceptor } from '../../lib/interceptor/audit.interceptor';
|
|
9
|
-
|
|
10
|
-
const FIXED = new Date('2026-01-01T00:00:00.000Z');
|
|
11
|
-
|
|
12
|
-
const makeContext = (request: any = {}): ExecutionContext =>
|
|
13
|
-
({
|
|
14
|
-
getHandler: () => ({}),
|
|
15
|
-
getType: () => 'http',
|
|
16
|
-
switchToHttp: () => ({ getRequest: () => request }),
|
|
17
|
-
}) as unknown as ExecutionContext;
|
|
18
|
-
|
|
19
|
-
const makeReflector = (metadata: any): Reflector =>
|
|
20
|
-
({ get: jest.fn().mockReturnValue(metadata) }) as unknown as Reflector;
|
|
21
|
-
|
|
22
|
-
const makeCallHandler = (result: any, isError = false): CallHandler => ({
|
|
23
|
-
handle: () => (isError ? throwError(() => result) : of(result)),
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
const makeClock = (): IClock => ({ now: () => FIXED });
|
|
27
|
-
|
|
28
|
-
const makeRequestContext = (requestId?: string): RequestContextService =>
|
|
29
|
-
({ get: jest.fn().mockReturnValue(requestId) }) as unknown as RequestContextService;
|
|
30
|
-
|
|
31
|
-
describe('AuditInterceptor', () => {
|
|
32
|
-
it('passes through untouched when no @Audit() metadata is present', (done) => {
|
|
33
|
-
const storage: IAuditStorage = { record: jest.fn<IAuditStorage['record']>() };
|
|
34
|
-
const actorResolver: IAuditActorResolver = {
|
|
35
|
-
resolve: jest.fn<IAuditActorResolver['resolve']>(),
|
|
36
|
-
};
|
|
37
|
-
const interceptor = new AuditInterceptor(
|
|
38
|
-
makeReflector(undefined),
|
|
39
|
-
storage,
|
|
40
|
-
actorResolver,
|
|
41
|
-
makeClock(),
|
|
42
|
-
makeRequestContext(),
|
|
43
|
-
);
|
|
44
|
-
|
|
45
|
-
interceptor
|
|
46
|
-
.intercept(makeContext(), makeCallHandler('result'))
|
|
47
|
-
.subscribe((value) => {
|
|
48
|
-
expect(value).toBe('result');
|
|
49
|
-
expect(storage.record).not.toHaveBeenCalled();
|
|
50
|
-
done();
|
|
51
|
-
});
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
it('skips recording and does not touch switchToHttp for non-http transports (rpc)', (done) => {
|
|
55
|
-
const storage: IAuditStorage = { record: jest.fn<IAuditStorage['record']>() };
|
|
56
|
-
const actorResolver: IAuditActorResolver = {
|
|
57
|
-
resolve: jest.fn<IAuditActorResolver['resolve']>(),
|
|
58
|
-
};
|
|
59
|
-
const interceptor = new AuditInterceptor(
|
|
60
|
-
makeReflector({ action: 'USER_UPDATED' }),
|
|
61
|
-
storage,
|
|
62
|
-
actorResolver,
|
|
63
|
-
makeClock(),
|
|
64
|
-
makeRequestContext(),
|
|
65
|
-
);
|
|
66
|
-
const context = {
|
|
67
|
-
getHandler: () => ({}),
|
|
68
|
-
getType: () => 'rpc',
|
|
69
|
-
switchToHttp: () => {
|
|
70
|
-
throw new Error('should not be called for a non-http context');
|
|
71
|
-
},
|
|
72
|
-
} as unknown as ExecutionContext;
|
|
73
|
-
|
|
74
|
-
interceptor.intercept(context, makeCallHandler('result')).subscribe((value) => {
|
|
75
|
-
expect(value).toBe('result');
|
|
76
|
-
expect(storage.record).not.toHaveBeenCalled();
|
|
77
|
-
expect(actorResolver.resolve).not.toHaveBeenCalled();
|
|
78
|
-
done();
|
|
79
|
-
});
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
it('records an entry after the handler succeeds, using the actor resolver, clock, and correlation id', (done) => {
|
|
83
|
-
const storage: IAuditStorage = {
|
|
84
|
-
record: jest.fn<IAuditStorage['record']>().mockResolvedValue(undefined),
|
|
85
|
-
};
|
|
86
|
-
const actorResolver: IAuditActorResolver = {
|
|
87
|
-
resolve: jest.fn<IAuditActorResolver['resolve']>().mockReturnValue({ id: 'user-1' }),
|
|
88
|
-
};
|
|
89
|
-
const interceptor = new AuditInterceptor(
|
|
90
|
-
makeReflector({ action: 'USER_UPDATED', resource: 'user', resourceIdParam: 'id' }),
|
|
91
|
-
storage,
|
|
92
|
-
actorResolver,
|
|
93
|
-
makeClock(),
|
|
94
|
-
makeRequestContext('req-1'),
|
|
95
|
-
);
|
|
96
|
-
const context = makeContext({ params: { id: '42' } });
|
|
97
|
-
|
|
98
|
-
interceptor.intercept(context, makeCallHandler('result')).subscribe((value) => {
|
|
99
|
-
expect(value).toBe('result');
|
|
100
|
-
setImmediate(() => {
|
|
101
|
-
expect(storage.record).toHaveBeenCalledWith({
|
|
102
|
-
action: 'USER_UPDATED',
|
|
103
|
-
actor: { id: 'user-1' },
|
|
104
|
-
resource: 'user',
|
|
105
|
-
resourceId: '42',
|
|
106
|
-
correlationId: 'req-1',
|
|
107
|
-
timestamp: FIXED,
|
|
108
|
-
metadata: undefined,
|
|
109
|
-
});
|
|
110
|
-
done();
|
|
111
|
-
});
|
|
112
|
-
});
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
it('does not record an entry when the handler itself errors', (done) => {
|
|
116
|
-
const storage: IAuditStorage = { record: jest.fn<IAuditStorage['record']>() };
|
|
117
|
-
const actorResolver: IAuditActorResolver = {
|
|
118
|
-
resolve: jest.fn<IAuditActorResolver['resolve']>(),
|
|
119
|
-
};
|
|
120
|
-
const interceptor = new AuditInterceptor(
|
|
121
|
-
makeReflector({ action: 'USER_UPDATED' }),
|
|
122
|
-
storage,
|
|
123
|
-
actorResolver,
|
|
124
|
-
makeClock(),
|
|
125
|
-
makeRequestContext(),
|
|
126
|
-
);
|
|
127
|
-
|
|
128
|
-
interceptor
|
|
129
|
-
.intercept(makeContext(), makeCallHandler(new Error('boom'), true))
|
|
130
|
-
.subscribe({
|
|
131
|
-
error: (err) => {
|
|
132
|
-
expect(err.message).toBe('boom');
|
|
133
|
-
expect(storage.record).not.toHaveBeenCalled();
|
|
134
|
-
done();
|
|
135
|
-
},
|
|
136
|
-
});
|
|
137
|
-
});
|
|
138
|
-
|
|
139
|
-
it('never fails the request when storage.record() rejects', (done) => {
|
|
140
|
-
const storage: IAuditStorage = {
|
|
141
|
-
record: jest.fn<IAuditStorage['record']>().mockRejectedValue(new Error('storage down')),
|
|
142
|
-
};
|
|
143
|
-
const actorResolver: IAuditActorResolver = {
|
|
144
|
-
resolve: jest.fn<IAuditActorResolver['resolve']>().mockReturnValue({ id: 'user-1' }),
|
|
145
|
-
};
|
|
146
|
-
const interceptor = new AuditInterceptor(
|
|
147
|
-
makeReflector({ action: 'USER_UPDATED' }),
|
|
148
|
-
storage,
|
|
149
|
-
actorResolver,
|
|
150
|
-
makeClock(),
|
|
151
|
-
makeRequestContext(),
|
|
152
|
-
);
|
|
153
|
-
|
|
154
|
-
interceptor
|
|
155
|
-
.intercept(makeContext(), makeCallHandler('result'))
|
|
156
|
-
.subscribe((value) => {
|
|
157
|
-
expect(value).toBe('result');
|
|
158
|
-
done();
|
|
159
|
-
});
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
it('never fails the request when storage.record() rejects with a non-Error value (no stack)', (done) => {
|
|
163
|
-
const storage: IAuditStorage = {
|
|
164
|
-
record: jest.fn<IAuditStorage['record']>().mockRejectedValue(undefined),
|
|
165
|
-
};
|
|
166
|
-
const actorResolver: IAuditActorResolver = {
|
|
167
|
-
resolve: jest.fn<IAuditActorResolver['resolve']>().mockReturnValue({ id: 'user-1' }),
|
|
168
|
-
};
|
|
169
|
-
const interceptor = new AuditInterceptor(
|
|
170
|
-
makeReflector({ action: 'USER_UPDATED' }),
|
|
171
|
-
storage,
|
|
172
|
-
actorResolver,
|
|
173
|
-
makeClock(),
|
|
174
|
-
makeRequestContext(),
|
|
175
|
-
);
|
|
176
|
-
|
|
177
|
-
interceptor
|
|
178
|
-
.intercept(makeContext(), makeCallHandler('result'))
|
|
179
|
-
.subscribe((value) => {
|
|
180
|
-
expect(value).toBe('result');
|
|
181
|
-
done();
|
|
182
|
-
});
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
it('leaves resourceId undefined when resourceIdParam is set but the request has no params', (done) => {
|
|
186
|
-
const storage: IAuditStorage = {
|
|
187
|
-
record: jest.fn<IAuditStorage['record']>().mockResolvedValue(undefined),
|
|
188
|
-
};
|
|
189
|
-
const actorResolver: IAuditActorResolver = {
|
|
190
|
-
resolve: jest.fn<IAuditActorResolver['resolve']>().mockReturnValue({ id: 'user-1' }),
|
|
191
|
-
};
|
|
192
|
-
const interceptor = new AuditInterceptor(
|
|
193
|
-
makeReflector({ action: 'USER_UPDATED', resourceIdParam: 'id' }),
|
|
194
|
-
storage,
|
|
195
|
-
actorResolver,
|
|
196
|
-
makeClock(),
|
|
197
|
-
makeRequestContext(),
|
|
198
|
-
);
|
|
199
|
-
|
|
200
|
-
interceptor.intercept(makeContext({}), makeCallHandler('result')).subscribe((value) => {
|
|
201
|
-
expect(value).toBe('result');
|
|
202
|
-
setImmediate(() => {
|
|
203
|
-
expect(storage.record).toHaveBeenCalledWith(
|
|
204
|
-
expect.objectContaining({ resourceId: undefined }),
|
|
205
|
-
);
|
|
206
|
-
done();
|
|
207
|
-
});
|
|
208
|
-
});
|
|
209
|
-
});
|
|
210
|
-
|
|
211
|
-
it('leaves resourceId undefined when resourceIdParam is set but the request itself is missing', (done) => {
|
|
212
|
-
const storage: IAuditStorage = {
|
|
213
|
-
record: jest.fn<IAuditStorage['record']>().mockResolvedValue(undefined),
|
|
214
|
-
};
|
|
215
|
-
const actorResolver: IAuditActorResolver = {
|
|
216
|
-
resolve: jest.fn<IAuditActorResolver['resolve']>().mockReturnValue({ id: 'user-1' }),
|
|
217
|
-
};
|
|
218
|
-
const interceptor = new AuditInterceptor(
|
|
219
|
-
makeReflector({ action: 'USER_UPDATED', resourceIdParam: 'id' }),
|
|
220
|
-
storage,
|
|
221
|
-
actorResolver,
|
|
222
|
-
makeClock(),
|
|
223
|
-
makeRequestContext(),
|
|
224
|
-
);
|
|
225
|
-
const context = {
|
|
226
|
-
getHandler: () => ({}),
|
|
227
|
-
getType: () => 'http',
|
|
228
|
-
switchToHttp: () => ({ getRequest: () => undefined }),
|
|
229
|
-
} as unknown as ExecutionContext;
|
|
230
|
-
|
|
231
|
-
interceptor.intercept(context, makeCallHandler('result')).subscribe((value) => {
|
|
232
|
-
expect(value).toBe('result');
|
|
233
|
-
setImmediate(() => {
|
|
234
|
-
expect(storage.record).toHaveBeenCalledWith(
|
|
235
|
-
expect.objectContaining({ resourceId: undefined }),
|
|
236
|
-
);
|
|
237
|
-
done();
|
|
238
|
-
});
|
|
239
|
-
});
|
|
240
|
-
});
|
|
241
|
-
});
|
package/test/jest-nax.json
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"moduleFileExtensions": ["js", "json", "ts", "d.ts"],
|
|
3
|
-
"rootDir": "../",
|
|
4
|
-
"testEnvironment": "node",
|
|
5
|
-
"testMatch": ["**/.nax/**/*.test.ts"],
|
|
6
|
-
"transform": {
|
|
7
|
-
"^.+\\.(t)s$": [
|
|
8
|
-
"ts-jest",
|
|
9
|
-
{
|
|
10
|
-
"diagnostics": true,
|
|
11
|
-
"tsconfig": {
|
|
12
|
-
"esModuleInterop": true,
|
|
13
|
-
"emitDecoratorMetadata": true,
|
|
14
|
-
"experimentalDecorators": true
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
]
|
|
18
|
-
},
|
|
19
|
-
"collectCoverageFrom": [
|
|
20
|
-
"lib/**/*.ts",
|
|
21
|
-
"!lib/**/*.spec.ts",
|
|
22
|
-
"!lib/**/*.d.ts",
|
|
23
|
-
"!**/node_modules/**"
|
|
24
|
-
],
|
|
25
|
-
"forceExit": true,
|
|
26
|
-
"maxWorkers": 1
|
|
27
|
-
}
|
package/test/jest-test.json
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"moduleFileExtensions": [
|
|
3
|
-
"js",
|
|
4
|
-
"json",
|
|
5
|
-
"ts",
|
|
6
|
-
"d.ts"
|
|
7
|
-
],
|
|
8
|
-
"rootDir": "../",
|
|
9
|
-
"testEnvironment": "node",
|
|
10
|
-
"testRegex": ".spec.ts$",
|
|
11
|
-
"transform": {
|
|
12
|
-
"^.+\\.(t)s$": [
|
|
13
|
-
"ts-jest",
|
|
14
|
-
{
|
|
15
|
-
"diagnostics": true
|
|
16
|
-
}
|
|
17
|
-
]
|
|
18
|
-
},
|
|
19
|
-
"collectCoverageFrom": [
|
|
20
|
-
"lib/**/*.ts",
|
|
21
|
-
"!lib/**/*.spec.ts",
|
|
22
|
-
"!lib/**/*.d.ts",
|
|
23
|
-
"!lib/**/index.ts",
|
|
24
|
-
"!lib/**/*.interface.ts",
|
|
25
|
-
"!**/node_modules/**"
|
|
26
|
-
],
|
|
27
|
-
"coverageProvider": "v8"
|
|
28
|
-
}
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from '@jest/globals';
|
|
2
|
-
import { Inject, Injectable, Module } from '@nestjs/common';
|
|
3
|
-
import { Test } from '@nestjs/testing';
|
|
4
|
-
import { ClockModule } from '@nathapp/nestjs-common';
|
|
5
|
-
import { AUDIT_ACTOR_RESOLVER, AUDIT_STORAGE } from '../../lib/constant';
|
|
6
|
-
import { IAuditActorResolver, IAuditStorage } from '../../lib/interface';
|
|
7
|
-
import { AuditModule } from '../../lib/module/audit.module';
|
|
8
|
-
import { DefaultActorResolver } from '../../lib/provider/default-actor-resolver';
|
|
9
|
-
import { InMemoryAuditStorage } from '../../lib/provider/in-memory-audit-storage';
|
|
10
|
-
|
|
11
|
-
describe('AuditModule', () => {
|
|
12
|
-
it('register() binds InMemoryAuditStorage and DefaultActorResolver by default', async () => {
|
|
13
|
-
const moduleRef = await Test.createTestingModule({
|
|
14
|
-
imports: [ClockModule.register(), AuditModule.register()],
|
|
15
|
-
}).compile();
|
|
16
|
-
|
|
17
|
-
expect(moduleRef.get<IAuditStorage>(AUDIT_STORAGE)).toBeInstanceOf(InMemoryAuditStorage);
|
|
18
|
-
expect(moduleRef.get<IAuditActorResolver>(AUDIT_ACTOR_RESOLVER)).toBeInstanceOf(
|
|
19
|
-
DefaultActorResolver,
|
|
20
|
-
);
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
it('register({ storage, actorResolver }) overrides the defaults with custom instances', async () => {
|
|
24
|
-
const customStorage: IAuditStorage = { record: async () => undefined };
|
|
25
|
-
const customResolver: IAuditActorResolver = { resolve: () => ({ id: 'custom' }) };
|
|
26
|
-
|
|
27
|
-
const moduleRef = await Test.createTestingModule({
|
|
28
|
-
imports: [
|
|
29
|
-
ClockModule.register(),
|
|
30
|
-
AuditModule.register({ storage: customStorage, actorResolver: customResolver }),
|
|
31
|
-
],
|
|
32
|
-
}).compile();
|
|
33
|
-
|
|
34
|
-
expect(moduleRef.get<IAuditStorage>(AUDIT_STORAGE)).toBe(customStorage);
|
|
35
|
-
expect(moduleRef.get<IAuditActorResolver>(AUDIT_ACTOR_RESOLVER)).toBe(customResolver);
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
it('register({ storage }) overrides only the storage, leaving the default actor resolver', async () => {
|
|
39
|
-
const customStorage: IAuditStorage = { record: async () => undefined };
|
|
40
|
-
|
|
41
|
-
const moduleRef = await Test.createTestingModule({
|
|
42
|
-
imports: [ClockModule.register(), AuditModule.register({ storage: customStorage })],
|
|
43
|
-
}).compile();
|
|
44
|
-
|
|
45
|
-
expect(moduleRef.get<IAuditStorage>(AUDIT_STORAGE)).toBe(customStorage);
|
|
46
|
-
expect(moduleRef.get<IAuditActorResolver>(AUDIT_ACTOR_RESOLVER)).toBeInstanceOf(
|
|
47
|
-
DefaultActorResolver,
|
|
48
|
-
);
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
it('register({ actorResolver }) overrides only the actor resolver, leaving the default storage', async () => {
|
|
52
|
-
const customResolver: IAuditActorResolver = { resolve: () => ({ id: 'custom' }) };
|
|
53
|
-
|
|
54
|
-
const moduleRef = await Test.createTestingModule({
|
|
55
|
-
imports: [ClockModule.register(), AuditModule.register({ actorResolver: customResolver })],
|
|
56
|
-
}).compile();
|
|
57
|
-
|
|
58
|
-
expect(moduleRef.get<IAuditStorage>(AUDIT_STORAGE)).toBeInstanceOf(InMemoryAuditStorage);
|
|
59
|
-
expect(moduleRef.get<IAuditActorResolver>(AUDIT_ACTOR_RESOLVER)).toBe(customResolver);
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
it('registerAsync({ useFactory }) supplies options asynchronously', async () => {
|
|
63
|
-
const customStorage: IAuditStorage = { record: async () => undefined };
|
|
64
|
-
|
|
65
|
-
const moduleRef = await Test.createTestingModule({
|
|
66
|
-
imports: [
|
|
67
|
-
ClockModule.register(),
|
|
68
|
-
AuditModule.registerAsync({ useFactory: () => ({ storage: customStorage }) }),
|
|
69
|
-
],
|
|
70
|
-
}).compile();
|
|
71
|
-
|
|
72
|
-
expect(moduleRef.get<IAuditStorage>(AUDIT_STORAGE)).toBe(customStorage);
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
it('is global — a feature module can inject AUDIT_STORAGE without importing AuditModule', async () => {
|
|
76
|
-
@Injectable()
|
|
77
|
-
class Consumer {
|
|
78
|
-
constructor(@Inject(AUDIT_STORAGE) readonly storage: IAuditStorage) {}
|
|
79
|
-
}
|
|
80
|
-
@Module({ providers: [Consumer], exports: [Consumer] })
|
|
81
|
-
class FeatureModule {}
|
|
82
|
-
|
|
83
|
-
const moduleRef = await Test.createTestingModule({
|
|
84
|
-
imports: [ClockModule.register(), AuditModule.register(), FeatureModule],
|
|
85
|
-
}).compile();
|
|
86
|
-
|
|
87
|
-
expect(moduleRef.get(Consumer).storage).toBeInstanceOf(InMemoryAuditStorage);
|
|
88
|
-
});
|
|
89
|
-
});
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from '@jest/globals';
|
|
2
|
-
import { ExecutionContext } from '@nestjs/common';
|
|
3
|
-
import { DefaultActorResolver } from '../../lib/provider/default-actor-resolver';
|
|
4
|
-
|
|
5
|
-
const makeContext = (request: any): ExecutionContext =>
|
|
6
|
-
({
|
|
7
|
-
switchToHttp: () => ({
|
|
8
|
-
getRequest: () => request,
|
|
9
|
-
}),
|
|
10
|
-
}) as unknown as ExecutionContext;
|
|
11
|
-
|
|
12
|
-
describe('DefaultActorResolver', () => {
|
|
13
|
-
it('resolves the actor id from request.user.id', () => {
|
|
14
|
-
const resolver = new DefaultActorResolver();
|
|
15
|
-
const context = makeContext({ user: { id: 'user-1' } });
|
|
16
|
-
|
|
17
|
-
expect(resolver.resolve(context)).toEqual({ id: 'user-1' });
|
|
18
|
-
});
|
|
19
|
-
|
|
20
|
-
it('falls back to "anonymous" when request.user is absent', () => {
|
|
21
|
-
const resolver = new DefaultActorResolver();
|
|
22
|
-
const context = makeContext({});
|
|
23
|
-
|
|
24
|
-
expect(resolver.resolve(context)).toEqual({ id: 'anonymous' });
|
|
25
|
-
});
|
|
26
|
-
|
|
27
|
-
it('falls back to "anonymous" when request itself is absent', () => {
|
|
28
|
-
const resolver = new DefaultActorResolver();
|
|
29
|
-
const context = makeContext(undefined);
|
|
30
|
-
|
|
31
|
-
expect(resolver.resolve(context)).toEqual({ id: 'anonymous' });
|
|
32
|
-
});
|
|
33
|
-
});
|
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from '@jest/globals';
|
|
2
|
-
import { AuditEntry } from '../../lib/interface';
|
|
3
|
-
import { InMemoryAuditStorage } from '../../lib/provider/in-memory-audit-storage';
|
|
4
|
-
|
|
5
|
-
const makeEntry = (overrides: Partial<AuditEntry> = {}): AuditEntry => ({
|
|
6
|
-
action: 'USER_UPDATED',
|
|
7
|
-
resource: 'user',
|
|
8
|
-
resourceId: '1',
|
|
9
|
-
timestamp: new Date('2026-01-01T00:00:00.000Z'),
|
|
10
|
-
...overrides,
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
describe('InMemoryAuditStorage', () => {
|
|
14
|
-
it('record() then query() round-trips the entry', async () => {
|
|
15
|
-
const storage = new InMemoryAuditStorage();
|
|
16
|
-
const entry = makeEntry();
|
|
17
|
-
|
|
18
|
-
await storage.record(entry);
|
|
19
|
-
const results = await storage.query();
|
|
20
|
-
|
|
21
|
-
expect(results).toEqual([entry]);
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
it('query() filters by action, resource, resourceId, and actorId', async () => {
|
|
25
|
-
const storage = new InMemoryAuditStorage();
|
|
26
|
-
const match = makeEntry({ actor: { id: 'user-1' } });
|
|
27
|
-
const noMatch = makeEntry({
|
|
28
|
-
action: 'USER_DELETED',
|
|
29
|
-
resource: 'account',
|
|
30
|
-
resourceId: '2',
|
|
31
|
-
actor: { id: 'user-2' },
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
await storage.record(match);
|
|
35
|
-
await storage.record(noMatch);
|
|
36
|
-
|
|
37
|
-
expect(await storage.query({ action: 'USER_UPDATED' })).toEqual([match]);
|
|
38
|
-
expect(await storage.query({ resource: 'user' })).toEqual([match]);
|
|
39
|
-
expect(await storage.query({ resourceId: '1' })).toEqual([match]);
|
|
40
|
-
expect(await storage.query({ actorId: 'user-1' })).toEqual([match]);
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
it('query() filters out entries with no actor when actorId is requested', async () => {
|
|
44
|
-
const storage = new InMemoryAuditStorage();
|
|
45
|
-
const withoutActor = makeEntry();
|
|
46
|
-
|
|
47
|
-
await storage.record(withoutActor);
|
|
48
|
-
|
|
49
|
-
expect(await storage.query({ actorId: 'user-1' })).toEqual([]);
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
it('query() filters by from/to timestamp range', async () => {
|
|
53
|
-
const storage = new InMemoryAuditStorage();
|
|
54
|
-
const early = makeEntry({ timestamp: new Date('2026-01-01T00:00:00.000Z') });
|
|
55
|
-
const late = makeEntry({ timestamp: new Date('2026-06-01T00:00:00.000Z') });
|
|
56
|
-
|
|
57
|
-
await storage.record(early);
|
|
58
|
-
await storage.record(late);
|
|
59
|
-
|
|
60
|
-
expect(await storage.query({ from: new Date('2026-03-01T00:00:00.000Z') })).toEqual([late]);
|
|
61
|
-
expect(await storage.query({ to: new Date('2026-03-01T00:00:00.000Z') })).toEqual([early]);
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
it('evicts the oldest entry once maxEntries is exceeded', async () => {
|
|
65
|
-
const storage = new InMemoryAuditStorage(2);
|
|
66
|
-
const first = makeEntry({ resourceId: '1' });
|
|
67
|
-
const second = makeEntry({ resourceId: '2' });
|
|
68
|
-
const third = makeEntry({ resourceId: '3' });
|
|
69
|
-
|
|
70
|
-
await storage.record(first);
|
|
71
|
-
await storage.record(second);
|
|
72
|
-
await storage.record(third);
|
|
73
|
-
|
|
74
|
-
const results = await storage.query();
|
|
75
|
-
expect(results).toEqual([second, third]);
|
|
76
|
-
});
|
|
77
|
-
});
|
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, jest } from '@jest/globals';
|
|
2
|
-
import { CommonExceptionCode } from '@nathapp/nestjs-common';
|
|
3
|
-
import { Logger } from '@nathapp/nestjs-logging';
|
|
4
|
-
import { AuditEntry } from '../../lib/interface';
|
|
5
|
-
import { LoggerAuditStorage } from '../../lib/provider/logger-audit-storage';
|
|
6
|
-
|
|
7
|
-
const makeLogger = (): jest.Mocked<Logger> =>
|
|
8
|
-
({
|
|
9
|
-
log: jest.fn<Logger['log']>(),
|
|
10
|
-
error: jest.fn<Logger['error']>(),
|
|
11
|
-
warn: jest.fn<Logger['warn']>(),
|
|
12
|
-
debug: jest.fn<Logger['debug']>(),
|
|
13
|
-
verbose: jest.fn<Logger['verbose']>(),
|
|
14
|
-
fatal: jest.fn<Logger['fatal']>(),
|
|
15
|
-
logWithMeta: jest.fn<Logger['logWithMeta']>(),
|
|
16
|
-
onModuleDestroy: jest.fn<Logger['onModuleDestroy']>(),
|
|
17
|
-
}) as unknown as jest.Mocked<Logger>;
|
|
18
|
-
|
|
19
|
-
describe('LoggerAuditStorage', () => {
|
|
20
|
-
it('record() delegates to the injected logger with the entry as structured fields', async () => {
|
|
21
|
-
const logger = makeLogger();
|
|
22
|
-
const storage = new LoggerAuditStorage(logger);
|
|
23
|
-
const entry: AuditEntry = {
|
|
24
|
-
action: 'USER_UPDATED',
|
|
25
|
-
actor: { id: 'user-1' },
|
|
26
|
-
resource: 'user',
|
|
27
|
-
resourceId: '1',
|
|
28
|
-
correlationId: 'req-1',
|
|
29
|
-
timestamp: new Date('2026-01-01T00:00:00.000Z'),
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
await storage.record(entry);
|
|
33
|
-
|
|
34
|
-
expect(logger.log).toHaveBeenCalledWith(
|
|
35
|
-
'AUDIT',
|
|
36
|
-
expect.objectContaining({
|
|
37
|
-
action: 'USER_UPDATED',
|
|
38
|
-
actor: { id: 'user-1' },
|
|
39
|
-
resource: 'user',
|
|
40
|
-
resourceId: '1',
|
|
41
|
-
correlationId: 'req-1',
|
|
42
|
-
timestamp: '2026-01-01T00:00:00.000Z',
|
|
43
|
-
}),
|
|
44
|
-
);
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
it('query() rejects with InternalAppException (CommonExceptionCode.INTERNAL_ERROR)', async () => {
|
|
48
|
-
const storage = new LoggerAuditStorage(makeLogger());
|
|
49
|
-
|
|
50
|
-
await expect(storage.query()).rejects.toHaveProperty(
|
|
51
|
-
'code',
|
|
52
|
-
CommonExceptionCode.INTERNAL_ERROR,
|
|
53
|
-
);
|
|
54
|
-
});
|
|
55
|
-
});
|
package/tsconfig.json
DELETED