win-portal-auth-sdk 1.3.1 → 1.4.0

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.
Files changed (35) hide show
  1. package/README.md +6 -7
  2. package/dist/index.d.ts +6 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +11 -2
  5. package/dist/nestjs/decorators/current-token.decorator.d.ts +29 -0
  6. package/dist/nestjs/decorators/current-token.decorator.d.ts.map +1 -0
  7. package/dist/nestjs/decorators/current-token.decorator.js +36 -0
  8. package/dist/nestjs/decorators/current-user.decorator.d.ts +26 -0
  9. package/dist/nestjs/decorators/current-user.decorator.d.ts.map +1 -0
  10. package/dist/nestjs/decorators/current-user.decorator.js +33 -0
  11. package/dist/nestjs/decorators/index.d.ts +9 -0
  12. package/dist/nestjs/decorators/index.d.ts.map +1 -0
  13. package/dist/nestjs/decorators/index.js +15 -0
  14. package/dist/nestjs/decorators/public.decorator.d.ts +31 -0
  15. package/dist/nestjs/decorators/public.decorator.d.ts.map +1 -0
  16. package/dist/nestjs/decorators/public.decorator.js +36 -0
  17. package/dist/nestjs/guards/index.d.ts +7 -0
  18. package/dist/nestjs/guards/index.d.ts.map +1 -0
  19. package/dist/nestjs/guards/index.js +11 -0
  20. package/dist/nestjs/guards/oauth-auth.guard.d.ts +139 -0
  21. package/dist/nestjs/guards/oauth-auth.guard.d.ts.map +1 -0
  22. package/dist/nestjs/guards/oauth-auth.guard.js +257 -0
  23. package/dist/nestjs/index.d.ts +28 -0
  24. package/dist/nestjs/index.d.ts.map +1 -0
  25. package/dist/nestjs/index.js +47 -0
  26. package/dist/nestjs/middleware/index.d.ts +7 -0
  27. package/dist/nestjs/middleware/index.d.ts.map +1 -0
  28. package/dist/nestjs/middleware/index.js +11 -0
  29. package/dist/nestjs/middleware/request-context.middleware.d.ts +62 -0
  30. package/dist/nestjs/middleware/request-context.middleware.d.ts.map +1 -0
  31. package/dist/nestjs/middleware/request-context.middleware.js +122 -0
  32. package/dist/nestjs/types/request-context.types.d.ts +69 -0
  33. package/dist/nestjs/types/request-context.types.d.ts.map +1 -0
  34. package/dist/nestjs/types/request-context.types.js +33 -0
  35. package/package.json +41 -3
package/README.md CHANGED
@@ -554,15 +554,14 @@ try {
554
554
 
555
555
  📚 **[Complete Documentation →](./docs/README.md)**
556
556
 
557
- - [API Functions Reference](./docs/api/functions.md) - สรุปฟังก์ชันทั้งหมดที่ SDK รองรับ 🆕
558
- - [Frontend Examples](./docs/guides/frontend-examples.md) - Next.js, React usage
559
- - [Middleware Guide](./docs/middleware/usage.md) - Express & NestJS
560
- - [Type Safety Guide](./docs/middleware/type-safety.md) - Express type augmentation 🆕
561
- - [Type Names Guide](./docs/guides/type-names.md) - SDK-friendly type names 🆕
562
- - [Next.js Guide](./docs/guides/nextjs.md) - คู่มือ Next.js ภาษาไทย
557
+ - [Next.js Guide](./docs/guides/nextjs.md) - คู่มือ Next.js ภาษาไทย (ครบถ้วน) ⭐
563
558
  - [OAuth Next.js Guide](./docs/guides/oauth-nextjs.md) - คู่มือ OAuth กับ Next.js
564
559
  - [NestJS Guide](./docs/guides/nestjs.md) - คู่มือ NestJS
565
- - [Thai Documentation](./docs/guides/getting-started.md) - คู่มือภาษาไทย
560
+ - [Middleware Guide](./docs/middleware/usage.md) - Express & NestJS (English & ไทย)
561
+ - [Middleware Examples](./docs/middleware/examples.md) - Complete backend examples
562
+ - [Type Safety Guide](./docs/middleware/type-safety.md) - Express type augmentation
563
+ - [API Functions Reference](./docs/api/functions.md) - สรุปฟังก์ชันทั้งหมดที่ SDK รองรับ
564
+ - [Type Names Guide](./docs/guides/type-names.md) - SDK-friendly type names
566
565
  - [Publishing Guide](./docs/development/publish.md) - How to publish updates
567
566
 
568
567
  ## License
package/dist/index.d.ts CHANGED
@@ -3,10 +3,15 @@
3
3
  *
4
4
  * Authentication SDK for Win Portal applications
5
5
  * Provides HTTP client with automatic API key injection
6
+ *
7
+ * Core exports - ใช้ได้ทุกที่ (Frontend & Backend)
8
+ *
9
+ * สำหรับ Backend-specific features:
10
+ * - Express Middleware: import from 'win-portal-auth-sdk/middleware'
11
+ * - NestJS Components: import from 'win-portal-auth-sdk/nestjs'
6
12
  */
7
13
  export * from './types';
8
14
  export * from './client';
9
- export * from './middleware';
10
15
  export * from './utils/token-utils';
11
16
  export { logger } from './utils/logger';
12
17
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,cAAc,SAAS,CAAC;AAGxB,cAAc,UAAU,CAAC;AAGzB,cAAc,cAAc,CAAC;AAG7B,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,cAAc,SAAS,CAAC;AAGxB,cAAc,UAAU,CAAC;AAGzB,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC"}
package/dist/index.js CHANGED
@@ -4,6 +4,12 @@
4
4
  *
5
5
  * Authentication SDK for Win Portal applications
6
6
  * Provides HTTP client with automatic API key injection
7
+ *
8
+ * Core exports - ใช้ได้ทุกที่ (Frontend & Backend)
9
+ *
10
+ * สำหรับ Backend-specific features:
11
+ * - Express Middleware: import from 'win-portal-auth-sdk/middleware'
12
+ * - NestJS Components: import from 'win-portal-auth-sdk/nestjs'
7
13
  */
8
14
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
15
  if (k2 === undefined) k2 = k;
@@ -25,9 +31,12 @@ exports.logger = void 0;
25
31
  __exportStar(require("./types"), exports);
26
32
  // Client (Frontend & Backend)
27
33
  __exportStar(require("./client"), exports);
28
- // Middleware (Backend only - Express & NestJS)
29
- __exportStar(require("./middleware"), exports);
30
34
  // Utils
31
35
  __exportStar(require("./utils/token-utils"), exports);
32
36
  var logger_1 = require("./utils/logger");
33
37
  Object.defineProperty(exports, "logger", { enumerable: true, get: function () { return logger_1.logger; } });
38
+ // Note: Middleware และ NestJS components ไม่ได้ export จาก root
39
+ // เพื่อป้องกันการ bundle backend code ใน frontend applications
40
+ // ใช้ subpath exports แทน:
41
+ // - 'win-portal-auth-sdk/middleware' สำหรับ Express middleware
42
+ // - 'win-portal-auth-sdk/nestjs' สำหรับ NestJS components
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Current Token Decorator
3
+ *
4
+ * Parameter decorator to extract the current authentication token from the request.
5
+ * Requires that a guard has set request.token (e.g., OAuthAuthGuard).
6
+ */
7
+ /**
8
+ * Current Token Decorator
9
+ *
10
+ * Extracts the authentication token from request.token.
11
+ * Returns null if no token is available.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * @Controller('api')
16
+ * @UseGuards(OAuthAuthGuard)
17
+ * export class ApiController {
18
+ * @Get('token-info')
19
+ * getTokenInfo(@CurrentToken() token: string) {
20
+ * return {
21
+ * token: token.substring(0, 20) + '...',
22
+ * length: token.length,
23
+ * };
24
+ * }
25
+ * }
26
+ * ```
27
+ */
28
+ export declare const CurrentToken: any;
29
+ //# sourceMappingURL=current-token.decorator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"current-token.decorator.d.ts","sourceRoot":"","sources":["../../../src/nestjs/decorators/current-token.decorator.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,YAAY,KAGvB,CAAC"}
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ /**
3
+ * Current Token Decorator
4
+ *
5
+ * Parameter decorator to extract the current authentication token from the request.
6
+ * Requires that a guard has set request.token (e.g., OAuthAuthGuard).
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.CurrentToken = void 0;
10
+ // @ts-expect-error - @nestjs/common is a peer dependency, will be available at runtime in NestJS apps
11
+ const common_1 = require("@nestjs/common");
12
+ /**
13
+ * Current Token Decorator
14
+ *
15
+ * Extracts the authentication token from request.token.
16
+ * Returns null if no token is available.
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * @Controller('api')
21
+ * @UseGuards(OAuthAuthGuard)
22
+ * export class ApiController {
23
+ * @Get('token-info')
24
+ * getTokenInfo(@CurrentToken() token: string) {
25
+ * return {
26
+ * token: token.substring(0, 20) + '...',
27
+ * length: token.length,
28
+ * };
29
+ * }
30
+ * }
31
+ * ```
32
+ */
33
+ exports.CurrentToken = (0, common_1.createParamDecorator)((data, ctx) => {
34
+ const request = ctx.switchToHttp().getRequest();
35
+ return request.token || null;
36
+ });
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Current User Decorator
3
+ *
4
+ * Parameter decorator to extract the current authenticated user from the request.
5
+ * Requires that a guard has set request.user (e.g., OAuthAuthGuard).
6
+ */
7
+ /**
8
+ * Current User Decorator
9
+ *
10
+ * Extracts the authenticated user from request.user.
11
+ * Returns null if no user is authenticated.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * @Controller('users')
16
+ * @UseGuards(OAuthAuthGuard)
17
+ * export class UsersController {
18
+ * @Get('profile')
19
+ * getProfile(@CurrentUser() user: User) {
20
+ * return user;
21
+ * }
22
+ * }
23
+ * ```
24
+ */
25
+ export declare const CurrentUser: any;
26
+ //# sourceMappingURL=current-user.decorator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"current-user.decorator.d.ts","sourceRoot":"","sources":["../../../src/nestjs/decorators/current-user.decorator.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,WAAW,KAKvB,CAAC"}
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ /**
3
+ * Current User Decorator
4
+ *
5
+ * Parameter decorator to extract the current authenticated user from the request.
6
+ * Requires that a guard has set request.user (e.g., OAuthAuthGuard).
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.CurrentUser = void 0;
10
+ // @ts-expect-error - @nestjs/common is a peer dependency, will be available at runtime in NestJS apps
11
+ const common_1 = require("@nestjs/common");
12
+ /**
13
+ * Current User Decorator
14
+ *
15
+ * Extracts the authenticated user from request.user.
16
+ * Returns null if no user is authenticated.
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * @Controller('users')
21
+ * @UseGuards(OAuthAuthGuard)
22
+ * export class UsersController {
23
+ * @Get('profile')
24
+ * getProfile(@CurrentUser() user: User) {
25
+ * return user;
26
+ * }
27
+ * }
28
+ * ```
29
+ */
30
+ exports.CurrentUser = (0, common_1.createParamDecorator)((data, ctx) => {
31
+ const request = ctx.switchToHttp().getRequest();
32
+ return request.user || null;
33
+ });
@@ -0,0 +1,9 @@
1
+ /**
2
+ * NestJS Decorators
3
+ *
4
+ * Decorators for NestJS applications using win-portal-auth-sdk
5
+ */
6
+ export { CurrentUser } from './current-user.decorator';
7
+ export { CurrentToken } from './current-token.decorator';
8
+ export { Public, IS_PUBLIC_KEY } from './public.decorator';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/nestjs/decorators/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ /**
3
+ * NestJS Decorators
4
+ *
5
+ * Decorators for NestJS applications using win-portal-auth-sdk
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.IS_PUBLIC_KEY = exports.Public = exports.CurrentToken = exports.CurrentUser = void 0;
9
+ var current_user_decorator_1 = require("./current-user.decorator");
10
+ Object.defineProperty(exports, "CurrentUser", { enumerable: true, get: function () { return current_user_decorator_1.CurrentUser; } });
11
+ var current_token_decorator_1 = require("./current-token.decorator");
12
+ Object.defineProperty(exports, "CurrentToken", { enumerable: true, get: function () { return current_token_decorator_1.CurrentToken; } });
13
+ var public_decorator_1 = require("./public.decorator");
14
+ Object.defineProperty(exports, "Public", { enumerable: true, get: function () { return public_decorator_1.Public; } });
15
+ Object.defineProperty(exports, "IS_PUBLIC_KEY", { enumerable: true, get: function () { return public_decorator_1.IS_PUBLIC_KEY; } });
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Public Decorator
3
+ *
4
+ * Decorator to mark endpoints as public (skip authentication)
5
+ * Used with guards that support the IS_PUBLIC_KEY metadata.
6
+ */
7
+ /**
8
+ * Metadata key for public endpoints
9
+ */
10
+ export declare const IS_PUBLIC_KEY = "isPublic";
11
+ /**
12
+ * Public decorator factory
13
+ *
14
+ * Marks an endpoint or controller as public, allowing access without authentication.
15
+ * Guards that support this decorator will skip authentication checks.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * @Controller('api')
20
+ * @UseGuards(OAuthAuthGuard)
21
+ * export class ApiController {
22
+ * @Public()
23
+ * @Get('health')
24
+ * healthCheck() {
25
+ * return { status: 'ok' };
26
+ * }
27
+ * }
28
+ * ```
29
+ */
30
+ export declare const Public: () => any;
31
+ //# sourceMappingURL=public.decorator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"public.decorator.d.ts","sourceRoot":"","sources":["../../../src/nestjs/decorators/public.decorator.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;GAEG;AACH,eAAO,MAAM,aAAa,aAAa,CAAC;AAKxC;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,MAAM,WAAyC,CAAC"}
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ /**
3
+ * Public Decorator
4
+ *
5
+ * Decorator to mark endpoints as public (skip authentication)
6
+ * Used with guards that support the IS_PUBLIC_KEY metadata.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.Public = exports.IS_PUBLIC_KEY = void 0;
10
+ /**
11
+ * Metadata key for public endpoints
12
+ */
13
+ exports.IS_PUBLIC_KEY = 'isPublic';
14
+ // @ts-expect-error - @nestjs/common is a peer dependency, will be available at runtime in NestJS apps
15
+ const common_1 = require("@nestjs/common");
16
+ /**
17
+ * Public decorator factory
18
+ *
19
+ * Marks an endpoint or controller as public, allowing access without authentication.
20
+ * Guards that support this decorator will skip authentication checks.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * @Controller('api')
25
+ * @UseGuards(OAuthAuthGuard)
26
+ * export class ApiController {
27
+ * @Public()
28
+ * @Get('health')
29
+ * healthCheck() {
30
+ * return { status: 'ok' };
31
+ * }
32
+ * }
33
+ * ```
34
+ */
35
+ const Public = () => (0, common_1.SetMetadata)(exports.IS_PUBLIC_KEY, true);
36
+ exports.Public = Public;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * NestJS Guards
3
+ *
4
+ * Guards for NestJS applications using win-portal-auth-sdk
5
+ */
6
+ export { OAuthAuthGuard, createOAuthAuthGuard, OAuthAuthGuardConfig } from './oauth-auth.guard';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/nestjs/guards/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ /**
3
+ * NestJS Guards
4
+ *
5
+ * Guards for NestJS applications using win-portal-auth-sdk
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.createOAuthAuthGuard = exports.OAuthAuthGuard = void 0;
9
+ var oauth_auth_guard_1 = require("./oauth-auth.guard");
10
+ Object.defineProperty(exports, "OAuthAuthGuard", { enumerable: true, get: function () { return oauth_auth_guard_1.OAuthAuthGuard; } });
11
+ Object.defineProperty(exports, "createOAuthAuthGuard", { enumerable: true, get: function () { return oauth_auth_guard_1.createOAuthAuthGuard; } });
@@ -0,0 +1,139 @@
1
+ /**
2
+ * OAuth Auth Guard
3
+ *
4
+ * Extended guard with OAuth-first validation, Public decorator support,
5
+ * and optional RequestContextService integration.
6
+ *
7
+ * Features:
8
+ * - OAuth-first validation: Tries OAuth token validation first, falls back to JWT
9
+ * - Public decorator support: Skips authentication for endpoints marked with @Public()
10
+ * - Optional RequestContextService integration: Sets user context if service is available
11
+ *
12
+ * @note This guard requires @nestjs/common and @nestjs/core as peer dependencies.
13
+ * The guard uses dynamic imports to avoid requiring NestJS as a direct dependency.
14
+ */
15
+ import { AuthClient } from '../../client';
16
+ import { User } from '../../types';
17
+ import { MiddlewareConfig } from '../../middleware/types';
18
+ /**
19
+ * Configuration for OAuthAuthGuard
20
+ */
21
+ export interface OAuthAuthGuardConfig extends Omit<MiddlewareConfig, 'optional'> {
22
+ /**
23
+ * AuthClient instance (injected via DI)
24
+ * If not provided, guard will create its own instance
25
+ */
26
+ authClient?: AuthClient;
27
+ }
28
+ /**
29
+ * OAuth Auth Guard Class
30
+ *
31
+ * This guard extends the base SDK guard and adds:
32
+ * - Public decorator support
33
+ * - OAuth-first token validation
34
+ * - Optional RequestContextService integration
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * // In your module
39
+ * @Module({
40
+ * providers: [
41
+ * {
42
+ * provide: 'AUTH_CLIENT',
43
+ * useFactory: () => new AuthClient({
44
+ * baseURL: process.env.AUTH_API_URL,
45
+ * apiKey: process.env.AUTH_API_KEY,
46
+ * }),
47
+ * },
48
+ * ],
49
+ * })
50
+ * export class AuthModule {}
51
+ *
52
+ * // In your controller
53
+ * @Controller('api')
54
+ * @UseGuards(OAuthAuthGuard)
55
+ * export class ApiController {
56
+ * @Get('profile')
57
+ * getProfile(@CurrentUser() user: User) {
58
+ * return user;
59
+ * }
60
+ *
61
+ * @Public()
62
+ * @Get('health')
63
+ * healthCheck() {
64
+ * return { status: 'ok' };
65
+ * }
66
+ * }
67
+ * ```
68
+ */
69
+ export declare class OAuthAuthGuard {
70
+ readonly baseGuard: any;
71
+ readonly authClient?: AuthClient;
72
+ readonly reflector: any;
73
+ readonly logger: any;
74
+ constructor(config: OAuthAuthGuardConfig, reflector: any, authClient?: AuthClient);
75
+ canActivate(context: any): Promise<boolean>;
76
+ /**
77
+ * Set user info in RequestContextService if available
78
+ * @internal
79
+ */
80
+ setRequestContext(user: User, token: string): void;
81
+ /**
82
+ * Handle successful authentication
83
+ * @internal
84
+ */
85
+ handleSuccess(request: any, token: string | null): boolean;
86
+ }
87
+ /**
88
+ * Factory function to create OAuthAuthGuard
89
+ *
90
+ * This factory creates a guard class that can be used with NestJS dependency injection.
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * // In your module
95
+ * @Module({
96
+ * providers: [
97
+ * {
98
+ * provide: 'AUTH_CLIENT',
99
+ * useFactory: () => new AuthClient({
100
+ * baseURL: process.env.AUTH_API_URL,
101
+ * apiKey: process.env.AUTH_API_KEY,
102
+ * }),
103
+ * },
104
+ * ],
105
+ * })
106
+ * export class AuthModule {}
107
+ *
108
+ * // Create guard instance
109
+ * const guard = createOAuthAuthGuard({
110
+ * baseURL: process.env.AUTH_API_URL || '',
111
+ * apiKey: process.env.AUTH_API_KEY || '',
112
+ * });
113
+ *
114
+ * // Use in controller
115
+ * @Controller('api')
116
+ * @UseGuards(guard)
117
+ * export class ApiController {}
118
+ * ```
119
+ */
120
+ export declare function createOAuthAuthGuard(config: OAuthAuthGuardConfig): {
121
+ new (reflector: any, authClient?: AuthClient): {
122
+ readonly baseGuard: any;
123
+ readonly authClient?: AuthClient | undefined;
124
+ readonly reflector: any;
125
+ readonly logger: any;
126
+ canActivate(context: any): Promise<boolean>;
127
+ /**
128
+ * Set user info in RequestContextService if available
129
+ * @internal
130
+ */
131
+ setRequestContext(user: User, token: string): void;
132
+ /**
133
+ * Handle successful authentication
134
+ * @internal
135
+ */
136
+ handleSuccess(request: any, token: string | null): boolean;
137
+ };
138
+ };
139
+ //# sourceMappingURL=oauth-auth.guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth-auth.guard.d.ts","sourceRoot":"","sources":["../../../src/nestjs/guards/oauth-auth.guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAEnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D;;GAEG;AACH,MAAM,WAAW,oBAAqB,SAAQ,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC;IAC9E;;;OAGG;IACH,UAAU,CAAC,EAAE,UAAU,CAAC;CACzB;AAUD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,qBAAa,cAAc;IAGzB,QAAQ,CAAC,SAAS,EAAE,GAAG,CAAC;IACxB,QAAQ,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC;IACjC,QAAQ,CAAC,SAAS,EAAE,GAAG,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,GAAG,CAAC;gBAGnB,MAAM,EAAE,oBAAoB,EAC5B,SAAS,EAAE,GAAG,EACd,UAAU,CAAC,EAAE,UAAU;IAgCnB,WAAW,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC;IAyGjD;;;OAGG;IACH,iBAAiB,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAmBlD;;;OAGG;IACH,aAAa,CAAC,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO;CAM3D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,oBAAoB;oBAEtC,GAAG,eAAe,UAAU;;;;;;QAtErD;;;WAGG;;QAoBH;;;WAGG;;;EAiDJ"}
@@ -0,0 +1,257 @@
1
+ "use strict";
2
+ /**
3
+ * OAuth Auth Guard
4
+ *
5
+ * Extended guard with OAuth-first validation, Public decorator support,
6
+ * and optional RequestContextService integration.
7
+ *
8
+ * Features:
9
+ * - OAuth-first validation: Tries OAuth token validation first, falls back to JWT
10
+ * - Public decorator support: Skips authentication for endpoints marked with @Public()
11
+ * - Optional RequestContextService integration: Sets user context if service is available
12
+ *
13
+ * @note This guard requires @nestjs/common and @nestjs/core as peer dependencies.
14
+ * The guard uses dynamic imports to avoid requiring NestJS as a direct dependency.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.createOAuthAuthGuard = exports.OAuthAuthGuard = void 0;
18
+ const decorators_1 = require("../decorators");
19
+ const middleware_1 = require("../../middleware");
20
+ const request_context_types_1 = require("../types/request-context.types");
21
+ /**
22
+ * Base Auth Guard from SDK
23
+ * This is the foundation guard that handles JWT validation
24
+ */
25
+ function createBaseAuthGuard(config) {
26
+ return (0, middleware_1.createAuthGuard)(config);
27
+ }
28
+ /**
29
+ * OAuth Auth Guard Class
30
+ *
31
+ * This guard extends the base SDK guard and adds:
32
+ * - Public decorator support
33
+ * - OAuth-first token validation
34
+ * - Optional RequestContextService integration
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * // In your module
39
+ * @Module({
40
+ * providers: [
41
+ * {
42
+ * provide: 'AUTH_CLIENT',
43
+ * useFactory: () => new AuthClient({
44
+ * baseURL: process.env.AUTH_API_URL,
45
+ * apiKey: process.env.AUTH_API_KEY,
46
+ * }),
47
+ * },
48
+ * ],
49
+ * })
50
+ * export class AuthModule {}
51
+ *
52
+ * // In your controller
53
+ * @Controller('api')
54
+ * @UseGuards(OAuthAuthGuard)
55
+ * export class ApiController {
56
+ * @Get('profile')
57
+ * getProfile(@CurrentUser() user: User) {
58
+ * return user;
59
+ * }
60
+ *
61
+ * @Public()
62
+ * @Get('health')
63
+ * healthCheck() {
64
+ * return { status: 'ok' };
65
+ * }
66
+ * }
67
+ * ```
68
+ */
69
+ class OAuthAuthGuard {
70
+ constructor(config, reflector, authClient) {
71
+ // Create base guard for fallback JWT validation
72
+ this.baseGuard = createBaseAuthGuard({
73
+ baseURL: config.baseURL,
74
+ apiKey: config.apiKey,
75
+ apiKeyHeader: config.apiKeyHeader || 'X-API-Key',
76
+ tokenStrategy: config.tokenStrategy || 'bearer',
77
+ cacheTimeout: config.cacheTimeout || 300,
78
+ });
79
+ this.authClient = authClient || config.authClient;
80
+ this.reflector = reflector;
81
+ // Try to get Logger from @nestjs/common
82
+ // Use dynamic require to avoid requiring @nestjs/common as direct dependency
83
+ try {
84
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
85
+ const { Logger } = require('@nestjs/common');
86
+ this.logger = new Logger('OAuthAuthGuard');
87
+ }
88
+ catch {
89
+ // Fallback logger if @nestjs/common is not available
90
+ // This should not happen in normal NestJS usage
91
+ this.logger = {
92
+ debug: () => { },
93
+ log: () => { },
94
+ warn: () => { },
95
+ error: () => { },
96
+ };
97
+ }
98
+ }
99
+ async canActivate(context) {
100
+ // Check if endpoint is marked as public
101
+ const isPublic = this.reflector?.getAllAndOverride
102
+ ? this.reflector.getAllAndOverride(decorators_1.IS_PUBLIC_KEY, [context.getHandler(), context.getClass()])
103
+ : undefined;
104
+ if (isPublic) {
105
+ this.logger.debug('Public endpoint - skipping authentication');
106
+ return true;
107
+ }
108
+ const request = context.switchToHttp().getRequest();
109
+ const authHeader = request.headers?.authorization;
110
+ if (!authHeader) {
111
+ // Try base guard (might handle missing token differently)
112
+ const result = await this.baseGuard.canActivate(context);
113
+ if (!result) {
114
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
115
+ const { UnauthorizedException } = require('@nestjs/common');
116
+ throw new UnauthorizedException('Missing authorization token');
117
+ }
118
+ return this.handleSuccess(request, request.token);
119
+ }
120
+ // Extract token from Authorization header
121
+ const token = authHeader.replace(/^Bearer\s+/i, '');
122
+ if (!token) {
123
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
124
+ const { UnauthorizedException } = require('@nestjs/common');
125
+ throw new UnauthorizedException('Missing authorization token');
126
+ }
127
+ // Check environment variables
128
+ const authApiUrl = process.env.AUTH_API_URL;
129
+ const authApiKey = process.env.AUTH_API_KEY;
130
+ if (!authApiUrl || !authApiKey) {
131
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
132
+ const { UnauthorizedException } = require('@nestjs/common');
133
+ throw new UnauthorizedException('Authentication service not configured');
134
+ }
135
+ try {
136
+ // Try OAuth validation first if AuthClient is available
137
+ if (this.authClient) {
138
+ try {
139
+ this.authClient.setToken(token, 'oauth');
140
+ const user = await this.authClient.auth.profile();
141
+ // Set user and token in request
142
+ request.user = user;
143
+ request.token = token;
144
+ // Set user info in RequestContextService (if available)
145
+ this.setRequestContext(user, token);
146
+ this.logger.debug(`OAuth authentication successful for user: ${user.id}`);
147
+ return true;
148
+ }
149
+ catch (oauthError) {
150
+ // OAuth validation failed, try base guard (JWT fallback)
151
+ this.logger.debug('OAuth validation failed, trying JWT fallback');
152
+ }
153
+ }
154
+ // Fallback to base guard (JWT validation)
155
+ const result = await this.baseGuard.canActivate(context);
156
+ if (result === false) {
157
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
158
+ const { UnauthorizedException } = require('@nestjs/common');
159
+ throw new UnauthorizedException('Invalid or expired token');
160
+ }
161
+ // Set user info in RequestContextService (if available)
162
+ if (request.user) {
163
+ this.setRequestContext(request.user, token);
164
+ }
165
+ return true;
166
+ }
167
+ catch (error) {
168
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
169
+ const { UnauthorizedException, HttpException } = require('@nestjs/common');
170
+ if (error instanceof UnauthorizedException) {
171
+ throw error;
172
+ }
173
+ if (error instanceof HttpException) {
174
+ const httpError = error;
175
+ const status = httpError.getStatus();
176
+ if (status === 401 || status === 403) {
177
+ throw new UnauthorizedException('Invalid or expired token');
178
+ }
179
+ throw error;
180
+ }
181
+ throw new UnauthorizedException('Invalid or expired token');
182
+ }
183
+ }
184
+ /**
185
+ * Set user info in RequestContextService if available
186
+ * @internal
187
+ */
188
+ setRequestContext(user, token) {
189
+ const requestContextService = (0, request_context_types_1.getRequestContextService)();
190
+ if (requestContextService) {
191
+ try {
192
+ requestContextService.setUserInfo(user.id, user.email, undefined, token);
193
+ if (user.permissions) {
194
+ requestContextService.setUserPermissions(user.permissions, user.roles || []);
195
+ }
196
+ }
197
+ catch (error) {
198
+ // RequestContextService not available or error setting context
199
+ // This is fine - guard will work without it
200
+ this.logger.debug('RequestContextService not available or error setting context');
201
+ }
202
+ }
203
+ }
204
+ /**
205
+ * Handle successful authentication
206
+ * @internal
207
+ */
208
+ handleSuccess(request, token) {
209
+ if (request.user && token) {
210
+ this.setRequestContext(request.user, token);
211
+ }
212
+ return true;
213
+ }
214
+ }
215
+ exports.OAuthAuthGuard = OAuthAuthGuard;
216
+ /**
217
+ * Factory function to create OAuthAuthGuard
218
+ *
219
+ * This factory creates a guard class that can be used with NestJS dependency injection.
220
+ *
221
+ * @example
222
+ * ```typescript
223
+ * // In your module
224
+ * @Module({
225
+ * providers: [
226
+ * {
227
+ * provide: 'AUTH_CLIENT',
228
+ * useFactory: () => new AuthClient({
229
+ * baseURL: process.env.AUTH_API_URL,
230
+ * apiKey: process.env.AUTH_API_KEY,
231
+ * }),
232
+ * },
233
+ * ],
234
+ * })
235
+ * export class AuthModule {}
236
+ *
237
+ * // Create guard instance
238
+ * const guard = createOAuthAuthGuard({
239
+ * baseURL: process.env.AUTH_API_URL || '',
240
+ * apiKey: process.env.AUTH_API_KEY || '',
241
+ * });
242
+ *
243
+ * // Use in controller
244
+ * @Controller('api')
245
+ * @UseGuards(guard)
246
+ * export class ApiController {}
247
+ * ```
248
+ */
249
+ function createOAuthAuthGuard(config) {
250
+ class OAuthAuthGuardInstance extends OAuthAuthGuard {
251
+ constructor(reflector, authClient) {
252
+ super(config, reflector, authClient);
253
+ }
254
+ }
255
+ return OAuthAuthGuardInstance;
256
+ }
257
+ exports.createOAuthAuthGuard = createOAuthAuthGuard;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * NestJS Integration Module
3
+ *
4
+ * Complete NestJS integration for win-portal-auth-sdk
5
+ * Includes guards, decorators, and middleware for easy setup.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * // Import everything you need
10
+ * import {
11
+ * OAuthAuthGuard,
12
+ * createOAuthAuthGuard,
13
+ * CurrentUser,
14
+ * CurrentToken,
15
+ * Public,
16
+ * RequestContextMiddleware,
17
+ * } from 'win-portal-auth-sdk/nestjs';
18
+ *
19
+ * // Or import from specific modules
20
+ * import { OAuthAuthGuard } from 'win-portal-auth-sdk/nestjs/guards';
21
+ * import { CurrentUser, Public } from 'win-portal-auth-sdk/nestjs/decorators';
22
+ * ```
23
+ */
24
+ export * from './guards';
25
+ export * from './decorators';
26
+ export * from './middleware';
27
+ export * from './types/request-context.types';
28
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/nestjs/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAGH,cAAc,UAAU,CAAC;AAGzB,cAAc,cAAc,CAAC;AAG7B,cAAc,cAAc,CAAC;AAG7B,cAAc,+BAA+B,CAAC"}
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ /**
3
+ * NestJS Integration Module
4
+ *
5
+ * Complete NestJS integration for win-portal-auth-sdk
6
+ * Includes guards, decorators, and middleware for easy setup.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * // Import everything you need
11
+ * import {
12
+ * OAuthAuthGuard,
13
+ * createOAuthAuthGuard,
14
+ * CurrentUser,
15
+ * CurrentToken,
16
+ * Public,
17
+ * RequestContextMiddleware,
18
+ * } from 'win-portal-auth-sdk/nestjs';
19
+ *
20
+ * // Or import from specific modules
21
+ * import { OAuthAuthGuard } from 'win-portal-auth-sdk/nestjs/guards';
22
+ * import { CurrentUser, Public } from 'win-portal-auth-sdk/nestjs/decorators';
23
+ * ```
24
+ */
25
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
26
+ if (k2 === undefined) k2 = k;
27
+ var desc = Object.getOwnPropertyDescriptor(m, k);
28
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
29
+ desc = { enumerable: true, get: function() { return m[k]; } };
30
+ }
31
+ Object.defineProperty(o, k2, desc);
32
+ }) : (function(o, m, k, k2) {
33
+ if (k2 === undefined) k2 = k;
34
+ o[k2] = m[k];
35
+ }));
36
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
37
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
38
+ };
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ // Guards
41
+ __exportStar(require("./guards"), exports);
42
+ // Decorators
43
+ __exportStar(require("./decorators"), exports);
44
+ // Middleware
45
+ __exportStar(require("./middleware"), exports);
46
+ // Types
47
+ __exportStar(require("./types/request-context.types"), exports);
@@ -0,0 +1,7 @@
1
+ /**
2
+ * NestJS Middleware
3
+ *
4
+ * Middleware for NestJS applications using win-portal-auth-sdk
5
+ */
6
+ export { RequestContextMiddleware, createRequestContextMiddleware, } from './request-context.middleware';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/nestjs/middleware/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,8BAA8B,CAAC"}
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ /**
3
+ * NestJS Middleware
4
+ *
5
+ * Middleware for NestJS applications using win-portal-auth-sdk
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.createRequestContextMiddleware = exports.RequestContextMiddleware = void 0;
9
+ var request_context_middleware_1 = require("./request-context.middleware");
10
+ Object.defineProperty(exports, "RequestContextMiddleware", { enumerable: true, get: function () { return request_context_middleware_1.RequestContextMiddleware; } });
11
+ Object.defineProperty(exports, "createRequestContextMiddleware", { enumerable: true, get: function () { return request_context_middleware_1.createRequestContextMiddleware; } });
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Request Context Middleware
3
+ *
4
+ * Optional middleware for managing request context with RequestContextService.
5
+ * This middleware creates a request context with requestId, ipAddress, userAgent,
6
+ * and runs the request within AsyncLocalStorage context.
7
+ *
8
+ * Note: This middleware requires RequestContextService to be available in the application.
9
+ * If RequestContextService is not available, the middleware will still work but
10
+ * won't set up the context.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * // In your AppModule
15
+ * import { RequestContextMiddleware } from 'win-portal-auth-sdk/nestjs';
16
+ *
17
+ * @Module({})
18
+ * export class AppModule implements NestModule {
19
+ * configure(consumer: MiddlewareConsumer) {
20
+ * consumer.apply(RequestContextMiddleware).forRoutes('*');
21
+ * }
22
+ * }
23
+ * ```
24
+ */
25
+ /**
26
+ * Request Context Middleware Class
27
+ *
28
+ * Creates request context and runs request within AsyncLocalStorage context.
29
+ */
30
+ export declare class RequestContextMiddleware {
31
+ /**
32
+ * Generate request ID
33
+ * Uses uuid v4 if available, otherwise generates a simple ID
34
+ */
35
+ private generateRequestId;
36
+ /**
37
+ * Get client IP address from request
38
+ */
39
+ private getClientIP;
40
+ /**
41
+ * Middleware handler
42
+ */
43
+ use(req: any, res: any, next: () => void): void;
44
+ }
45
+ /**
46
+ * Factory function to create RequestContextMiddleware
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * // In your AppModule
51
+ * import { createRequestContextMiddleware } from 'win-portal-auth-sdk/nestjs';
52
+ *
53
+ * @Module({})
54
+ * export class AppModule implements NestModule {
55
+ * configure(consumer: MiddlewareConsumer) {
56
+ * consumer.apply(createRequestContextMiddleware()).forRoutes('*');
57
+ * }
58
+ * }
59
+ * ```
60
+ */
61
+ export declare function createRequestContextMiddleware(): RequestContextMiddleware;
62
+ //# sourceMappingURL=request-context.middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-context.middleware.d.ts","sourceRoot":"","sources":["../../../src/nestjs/middleware/request-context.middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAIH;;;;GAIG;AACH,qBAAa,wBAAwB;IACnC;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAUzB;;OAEG;IACH,OAAO,CAAC,WAAW;IAUnB;;OAEG;IACH,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,IAAI,GAAG,IAAI;CA2ChD;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,8BAA8B,6BAE7C"}
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ /**
3
+ * Request Context Middleware
4
+ *
5
+ * Optional middleware for managing request context with RequestContextService.
6
+ * This middleware creates a request context with requestId, ipAddress, userAgent,
7
+ * and runs the request within AsyncLocalStorage context.
8
+ *
9
+ * Note: This middleware requires RequestContextService to be available in the application.
10
+ * If RequestContextService is not available, the middleware will still work but
11
+ * won't set up the context.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * // In your AppModule
16
+ * import { RequestContextMiddleware } from 'win-portal-auth-sdk/nestjs';
17
+ *
18
+ * @Module({})
19
+ * export class AppModule implements NestModule {
20
+ * configure(consumer: MiddlewareConsumer) {
21
+ * consumer.apply(RequestContextMiddleware).forRoutes('*');
22
+ * }
23
+ * }
24
+ * ```
25
+ */
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.createRequestContextMiddleware = exports.RequestContextMiddleware = void 0;
28
+ const request_context_types_1 = require("../types/request-context.types");
29
+ /**
30
+ * Request Context Middleware Class
31
+ *
32
+ * Creates request context and runs request within AsyncLocalStorage context.
33
+ */
34
+ class RequestContextMiddleware {
35
+ /**
36
+ * Generate request ID
37
+ * Uses uuid v4 if available, otherwise generates a simple ID
38
+ */
39
+ generateRequestId() {
40
+ try {
41
+ const { v4: uuidv4 } = require('uuid');
42
+ return uuidv4();
43
+ }
44
+ catch {
45
+ // Fallback if uuid is not available
46
+ return `req-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
47
+ }
48
+ }
49
+ /**
50
+ * Get client IP address from request
51
+ */
52
+ getClientIP(req) {
53
+ return (req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
54
+ req.headers['x-real-ip'] ||
55
+ req.connection?.remoteAddress ||
56
+ req.socket?.remoteAddress ||
57
+ '127.0.0.1');
58
+ }
59
+ /**
60
+ * Middleware handler
61
+ */
62
+ use(req, res, next) {
63
+ const requestId = this.generateRequestId();
64
+ const ipAddress = this.getClientIP(req);
65
+ const userAgent = req.get('user-agent') || req.headers['user-agent'] || 'Unknown';
66
+ const origin = req.get('origin') || req.get('referer');
67
+ // Set request ID in response headers for debugging
68
+ if (res && typeof res.setHeader === 'function') {
69
+ res.setHeader('X-Request-ID', requestId);
70
+ }
71
+ // Store context in request object
72
+ const requestContext = {
73
+ requestId,
74
+ ipAddress,
75
+ userAgent,
76
+ origin,
77
+ method: req.method,
78
+ url: req.url,
79
+ timestamp: new Date(),
80
+ };
81
+ // Attach to request object
82
+ req.requestContext = requestContext;
83
+ // Try to use RequestContextService if available
84
+ const requestContextService = (0, request_context_types_1.getRequestContextService)();
85
+ if (requestContextService) {
86
+ try {
87
+ // Run the entire request pipeline within AsyncLocalStorage context
88
+ requestContextService.runWithContext(req, () => {
89
+ next();
90
+ });
91
+ return;
92
+ }
93
+ catch (error) {
94
+ // RequestContextService not available or error
95
+ // Continue without it
96
+ }
97
+ }
98
+ // If RequestContextService is not available, just continue
99
+ next();
100
+ }
101
+ }
102
+ exports.RequestContextMiddleware = RequestContextMiddleware;
103
+ /**
104
+ * Factory function to create RequestContextMiddleware
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * // In your AppModule
109
+ * import { createRequestContextMiddleware } from 'win-portal-auth-sdk/nestjs';
110
+ *
111
+ * @Module({})
112
+ * export class AppModule implements NestModule {
113
+ * configure(consumer: MiddlewareConsumer) {
114
+ * consumer.apply(createRequestContextMiddleware()).forRoutes('*');
115
+ * }
116
+ * }
117
+ * ```
118
+ */
119
+ function createRequestContextMiddleware() {
120
+ return new RequestContextMiddleware();
121
+ }
122
+ exports.createRequestContextMiddleware = createRequestContextMiddleware;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Request Context Types
3
+ *
4
+ * Type definitions for optional RequestContextService integration
5
+ * These types allow SDK components to work with RequestContextService
6
+ * if it's available in the application, without requiring it as a dependency.
7
+ */
8
+ /**
9
+ * Request Context Data Interface
10
+ *
11
+ * Matches the structure used by RequestContextService in applications
12
+ */
13
+ export interface RequestContextData {
14
+ requestId: string;
15
+ ipAddress: string;
16
+ userAgent: string;
17
+ origin?: string;
18
+ userId?: string;
19
+ userEmail?: string;
20
+ sessionId?: string;
21
+ method: string;
22
+ url: string;
23
+ timestamp: Date;
24
+ authToken?: string;
25
+ permissions?: string[];
26
+ roles?: Array<{
27
+ id: string;
28
+ name: string;
29
+ }>;
30
+ roleCodes?: string[];
31
+ applicationId?: string;
32
+ applicationName?: string;
33
+ apiKeyId?: string;
34
+ }
35
+ /**
36
+ * Optional RequestContextService Interface
37
+ *
38
+ * This interface represents the static methods available on RequestContextService
39
+ * that SDK components can use if the service is available.
40
+ */
41
+ export interface RequestContextServiceInterface {
42
+ /**
43
+ * Get current request context
44
+ */
45
+ getContext(): RequestContextData | undefined;
46
+ /**
47
+ * Run function with request context
48
+ */
49
+ runWithContext<T>(req: any, fn: () => T): T;
50
+ /**
51
+ * Set user info in current context
52
+ */
53
+ setUserInfo(userId: string, userEmail: string, sessionId?: string, authToken?: string): void;
54
+ /**
55
+ * Set user permissions and roles in context
56
+ */
57
+ setUserPermissions(permissions: string[], roles: string[] | Array<{
58
+ id: string;
59
+ name: string;
60
+ }>): void;
61
+ }
62
+ /**
63
+ * Helper function to safely access RequestContextService
64
+ *
65
+ * This function checks if RequestContextService is available and returns
66
+ * a typed interface if it exists, or undefined if not.
67
+ */
68
+ export declare function getRequestContextService(): RequestContextServiceInterface | undefined;
69
+ //# sourceMappingURL=request-context.types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-context.types.d.ts","sourceRoot":"","sources":["../../../src/nestjs/types/request-context.types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,IAAI,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB,KAAK,CAAC,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC5C,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;;GAKG;AACH,MAAM,WAAW,8BAA8B;IAC7C;;OAEG;IACH,UAAU,IAAI,kBAAkB,GAAG,SAAS,CAAC;IAE7C;;OAEG;IACH,cAAc,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;IAE5C;;OAEG;IACH,WAAW,CACT,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,SAAS,CAAC,EAAE,MAAM,EAClB,SAAS,CAAC,EAAE,MAAM,GACjB,IAAI,CAAC;IAER;;OAEG;IACH,kBAAkB,CAChB,WAAW,EAAE,MAAM,EAAE,EACrB,KAAK,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,GACpD,IAAI,CAAC;CACT;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,IAAI,8BAA8B,GAAG,SAAS,CAcrF"}
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ /**
3
+ * Request Context Types
4
+ *
5
+ * Type definitions for optional RequestContextService integration
6
+ * These types allow SDK components to work with RequestContextService
7
+ * if it's available in the application, without requiring it as a dependency.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.getRequestContextService = void 0;
11
+ /**
12
+ * Helper function to safely access RequestContextService
13
+ *
14
+ * This function checks if RequestContextService is available and returns
15
+ * a typed interface if it exists, or undefined if not.
16
+ */
17
+ function getRequestContextService() {
18
+ // Try to access RequestContextService from global scope or module
19
+ // This is a safe way to check if the service exists without requiring it
20
+ try {
21
+ // Check if RequestContextService exists in the runtime
22
+ // Applications that use RequestContextService will have it available
23
+ const RequestContextService = global.RequestContextService;
24
+ if (RequestContextService && typeof RequestContextService.setUserInfo === 'function') {
25
+ return RequestContextService;
26
+ }
27
+ }
28
+ catch {
29
+ // RequestContextService not available
30
+ }
31
+ return undefined;
32
+ }
33
+ exports.getRequestContextService = getRequestContextService;
package/package.json CHANGED
@@ -1,9 +1,31 @@
1
1
  {
2
2
  "name": "win-portal-auth-sdk",
3
- "version": "1.3.1",
3
+ "version": "1.4.0",
4
4
  "description": "Shared authentication SDK for Win Portal applications with JWT and OAuth support",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./middleware": {
13
+ "types": "./dist/middleware/index.d.ts",
14
+ "default": "./dist/middleware/index.js"
15
+ },
16
+ "./nestjs": {
17
+ "types": "./dist/nestjs/index.d.ts",
18
+ "default": "./dist/nestjs/index.js"
19
+ },
20
+ "./client": {
21
+ "types": "./dist/client/index.d.ts",
22
+ "default": "./dist/client/index.js"
23
+ },
24
+ "./types": {
25
+ "types": "./dist/types/index.d.ts",
26
+ "default": "./dist/types/index.js"
27
+ }
28
+ },
7
29
  "files": [
8
30
  "dist",
9
31
  "README.md",
@@ -47,6 +69,22 @@
47
69
  "dependencies": {
48
70
  "axios": "^1.6.0"
49
71
  },
72
+ "peerDependencies": {
73
+ "@nestjs/common": "^10.0.0 || ^11.0.0",
74
+ "@nestjs/core": "^10.0.0 || ^11.0.0",
75
+ "uuid": "^9.0.0 || ^10.0.0"
76
+ },
77
+ "peerDependenciesMeta": {
78
+ "@nestjs/common": {
79
+ "optional": true
80
+ },
81
+ "@nestjs/core": {
82
+ "optional": true
83
+ },
84
+ "uuid": {
85
+ "optional": true
86
+ }
87
+ },
50
88
  "devDependencies": {
51
89
  "@types/node": "^20.0.0",
52
90
  "typescript": "^5.3.0"