@payez/next-mvp 4.1.11 → 4.1.12

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 (91) hide show
  1. package/dist/api-handlers/auth/refresh.js +15 -38
  2. package/dist/auth/better-auth.js +12 -33
  3. package/dist/client/better-auth-client.d.ts +14 -2
  4. package/dist/lib/ensure-fresh-access-token.js +8 -42
  5. package/dist/lib/session-store.d.ts +0 -1
  6. package/dist/lib/session-store.js +29 -33
  7. package/dist/lib/startup-init.js +19 -19
  8. package/dist/lib/token-lifecycle.d.ts +0 -2
  9. package/dist/lib/token-lifecycle.js +3 -21
  10. package/package.json +4 -3
  11. package/scripts/check-internal-url-usage.sh +73 -73
  12. package/src/api/index.ts +17 -17
  13. package/src/api-handlers/account/masked-info.ts +45 -45
  14. package/src/api-handlers/account/profile.ts +80 -80
  15. package/src/api-handlers/account/recovery/initiate.ts +23 -23
  16. package/src/api-handlers/account/recovery/send-code.ts +25 -25
  17. package/src/api-handlers/account/recovery/verify-code.ts +25 -25
  18. package/src/api-handlers/account/reset-password.ts +23 -23
  19. package/src/api-handlers/account/send-code.ts +76 -76
  20. package/src/api-handlers/account/validate-password.ts +118 -118
  21. package/src/api-handlers/admin/stats.ts +249 -249
  22. package/src/api-handlers/anon/preferences.ts +123 -123
  23. package/src/api-handlers/auth/jwks.ts +20 -20
  24. package/src/api-handlers/auth/login.ts +240 -240
  25. package/src/api-handlers/auth/refresh.ts +15 -38
  26. package/src/api-handlers/auth/validate.ts +43 -43
  27. package/src/api-handlers/session/viability.ts +142 -142
  28. package/src/auth/better-auth.ts +450 -467
  29. package/src/auth/unauthenticated-routes.ts +2 -2
  30. package/src/client/better-auth-client.ts +70 -70
  31. package/src/client/fetchWithSession.ts +21 -21
  32. package/src/client/index.ts +13 -13
  33. package/src/client/useAnonSession.ts +131 -131
  34. package/src/components/admin/VibeAdminContext.tsx +87 -87
  35. package/src/config/logging-config.ts +82 -82
  36. package/src/config/unauthenticated-routes.ts +19 -19
  37. package/src/edge/internal-api-url.ts +65 -65
  38. package/src/edge/middleware.ts +42 -42
  39. package/src/hooks/useProfile.ts +75 -75
  40. package/src/lib/anon-session.ts +213 -213
  41. package/src/lib/auth-secret.ts +137 -137
  42. package/src/lib/demo-mode.ts +17 -17
  43. package/src/lib/ensure-fresh-access-token.ts +8 -42
  44. package/src/lib/idp-client-config.ts +559 -559
  45. package/src/lib/idp-fetch.ts +126 -126
  46. package/src/lib/internal-api.ts +171 -171
  47. package/src/lib/jwt-decode-client.ts +45 -45
  48. package/src/lib/rate-limit-service.ts +9 -9
  49. package/src/lib/redis.ts +26 -26
  50. package/src/lib/refresh-token-validator.ts +64 -64
  51. package/src/lib/secret-validation.ts +8 -8
  52. package/src/lib/session-store.ts +692 -695
  53. package/src/lib/session.ts +34 -34
  54. package/src/lib/startup-init.ts +251 -251
  55. package/src/lib/token-expiry.ts +40 -40
  56. package/src/lib/token-lifecycle.ts +470 -497
  57. package/src/lib/types/api-responses.ts +336 -336
  58. package/src/middleware/auth-decision.ts +43 -43
  59. package/src/models/DecodedAccessToken.ts +16 -16
  60. package/src/models/SessionModel.ts +264 -264
  61. package/src/pages/admin-roles/index.ts +9 -9
  62. package/src/pages/security/EnhancedSecurityPage.tsx +9 -9
  63. package/src/routes/account/index.ts +31 -31
  64. package/src/routes/account/masked-info.ts +36 -36
  65. package/src/routes/account/send-code.ts +39 -39
  66. package/src/routes/account/verify-email.ts +40 -40
  67. package/src/routes/account/verify-sms.ts +40 -40
  68. package/src/routes/auth/index.ts +22 -22
  69. package/src/routes/auth/refresh.ts +48 -48
  70. package/src/routes/auth/session.ts +166 -166
  71. package/src/routes/index.ts +17 -17
  72. package/src/routes/session/index.ts +7 -7
  73. package/src/routes/session/refresh-viability.ts +17 -17
  74. package/src/server/auth.ts +373 -373
  75. package/src/server/decode-session.ts +202 -202
  76. package/src/services/signalrActivityService.ts +258 -258
  77. package/src/theme/ThemeProvider.tsx +39 -39
  78. package/src/theme/default.ts +33 -33
  79. package/src/theme/index.ts +31 -31
  80. package/src/theme/types.ts +69 -69
  81. package/src/theme/useTheme.ts +57 -57
  82. package/src/theme/utils.ts +40 -40
  83. package/src/types/api.ts +12 -12
  84. package/src/types/auth.d.ts +23 -23
  85. package/src/types/auth.ts +22 -22
  86. package/src/types/logging.ts +11 -11
  87. package/src/types/recovery.ts +54 -54
  88. package/src/utils/api.ts +353 -353
  89. package/src/utils/circuitBreaker.ts +40 -40
  90. package/src/utils/error-message.ts +108 -108
  91. package/src/utils/layout/reservedSpace.ts +124 -124
@@ -1,31 +1,31 @@
1
- /**
2
- * Theme Module for @payez/next-mvp
3
- *
4
- * Main export for the theme system. Provides:
5
- * - ThemeProvider component
6
- * - Theme hooks (useTheme, useBranding, useColors, etc.)
7
- * - TypeScript types for theme configuration
8
- * - Default theme
9
- */
10
-
11
- export { ThemeProvider } from './ThemeProvider';
12
- export type { ThemeProviderProps } from './ThemeProvider';
13
-
14
- export {
15
- useTheme,
16
- useBranding,
17
- useColors,
18
- useTypography,
19
- useLayout,
20
- useComponentTheme,
21
- } from './useTheme';
22
-
23
- export type {
24
- ThemeConfig,
25
- LoginPageTheme,
26
- ProfilePageTheme,
27
- RecoveryPageTheme,
28
- } from './types';
29
-
30
- export { defaultTheme } from './default';
31
- export { mergeDeep } from './utils';
1
+ /**
2
+ * Theme Module for @payez/next-mvp
3
+ *
4
+ * Main export for the theme system. Provides:
5
+ * - ThemeProvider component
6
+ * - Theme hooks (useTheme, useBranding, useColors, etc.)
7
+ * - TypeScript types for theme configuration
8
+ * - Default theme
9
+ */
10
+
11
+ export { ThemeProvider } from './ThemeProvider';
12
+ export type { ThemeProviderProps } from './ThemeProvider';
13
+
14
+ export {
15
+ useTheme,
16
+ useBranding,
17
+ useColors,
18
+ useTypography,
19
+ useLayout,
20
+ useComponentTheme,
21
+ } from './useTheme';
22
+
23
+ export type {
24
+ ThemeConfig,
25
+ LoginPageTheme,
26
+ ProfilePageTheme,
27
+ RecoveryPageTheme,
28
+ } from './types';
29
+
30
+ export { defaultTheme } from './default';
31
+ export { mergeDeep } from './utils';
@@ -1,69 +1,69 @@
1
- /**
2
- * Theme Configuration Types for @payez/next-mvp
3
- *
4
- * These types define the shape of theme configurations that consumers
5
- * can provide to customize branding, colors, typography, and layout.
6
- */
7
-
8
- export interface ThemeConfig {
9
- // Branding
10
- branding: {
11
- logo: {
12
- light: string; // Path to logo for light backgrounds
13
- dark: string; // Path to logo for dark backgrounds
14
- alt: string; // Alt text
15
- height?: string; // Default: "h-10"
16
- width?: string; // Default: "w-auto"
17
- };
18
- appName: string; // "Nexus", "CryptAply", etc.
19
- tagline?: string; // Optional tagline
20
- };
21
-
22
- // Colors (Tailwind classes or hex)
23
- colors: {
24
- primary: string; // Primary brand color
25
- secondary?: string; // Secondary brand color
26
- accent?: string; // Accent color
27
- background: string; // Page background
28
- card: string; // Card background
29
- muted: string; // Muted text/elements
30
- border: string; // Border color
31
- };
32
-
33
- // Typography
34
- typography?: {
35
- fontFamily?: string; // Font family
36
- headingWeight?: string; // "font-bold", etc.
37
- bodyWeight?: string; // "font-normal", etc.
38
- };
39
-
40
- // Layout
41
- layout?: {
42
- maxWidth?: string; // "max-w-4xl", etc.
43
- padding?: string; // "p-6", etc.
44
- spacing?: string; // "space-y-6", etc.
45
- };
46
-
47
- // Component-specific overrides
48
- components?: {
49
- loginPage?: Partial<LoginPageTheme>;
50
- profilePage?: Partial<ProfilePageTheme>;
51
- recoveryPage?: Partial<RecoveryPageTheme>;
52
- };
53
- }
54
-
55
- export interface LoginPageTheme {
56
- cardBackground: string;
57
- gradient: string;
58
- buttonColor: string;
59
- showLogo: boolean;
60
- }
61
-
62
- export interface ProfilePageTheme {
63
- layout: "centered" | "full-width";
64
- showAvatar: boolean;
65
- }
66
-
67
- export interface RecoveryPageTheme {
68
- layout: "centered" | "full-width";
69
- }
1
+ /**
2
+ * Theme Configuration Types for @payez/next-mvp
3
+ *
4
+ * These types define the shape of theme configurations that consumers
5
+ * can provide to customize branding, colors, typography, and layout.
6
+ */
7
+
8
+ export interface ThemeConfig {
9
+ // Branding
10
+ branding: {
11
+ logo: {
12
+ light: string; // Path to logo for light backgrounds
13
+ dark: string; // Path to logo for dark backgrounds
14
+ alt: string; // Alt text
15
+ height?: string; // Default: "h-10"
16
+ width?: string; // Default: "w-auto"
17
+ };
18
+ appName: string; // "Nexus", "CryptAply", etc.
19
+ tagline?: string; // Optional tagline
20
+ };
21
+
22
+ // Colors (Tailwind classes or hex)
23
+ colors: {
24
+ primary: string; // Primary brand color
25
+ secondary?: string; // Secondary brand color
26
+ accent?: string; // Accent color
27
+ background: string; // Page background
28
+ card: string; // Card background
29
+ muted: string; // Muted text/elements
30
+ border: string; // Border color
31
+ };
32
+
33
+ // Typography
34
+ typography?: {
35
+ fontFamily?: string; // Font family
36
+ headingWeight?: string; // "font-bold", etc.
37
+ bodyWeight?: string; // "font-normal", etc.
38
+ };
39
+
40
+ // Layout
41
+ layout?: {
42
+ maxWidth?: string; // "max-w-4xl", etc.
43
+ padding?: string; // "p-6", etc.
44
+ spacing?: string; // "space-y-6", etc.
45
+ };
46
+
47
+ // Component-specific overrides
48
+ components?: {
49
+ loginPage?: Partial<LoginPageTheme>;
50
+ profilePage?: Partial<ProfilePageTheme>;
51
+ recoveryPage?: Partial<RecoveryPageTheme>;
52
+ };
53
+ }
54
+
55
+ export interface LoginPageTheme {
56
+ cardBackground: string;
57
+ gradient: string;
58
+ buttonColor: string;
59
+ showLogo: boolean;
60
+ }
61
+
62
+ export interface ProfilePageTheme {
63
+ layout: "centered" | "full-width";
64
+ showAvatar: boolean;
65
+ }
66
+
67
+ export interface RecoveryPageTheme {
68
+ layout: "centered" | "full-width";
69
+ }
@@ -1,57 +1,57 @@
1
- /**
2
- * Theme Hooks for @payez/next-mvp
3
- *
4
- * Convenience hooks for accessing specific parts of the theme configuration.
5
- * These hooks can only be used within components wrapped by ThemeProvider.
6
- */
7
-
8
- 'use client';
9
-
10
- import { useTheme as useThemeContext } from './ThemeProvider';
11
-
12
- /**
13
- * Access the full theme configuration
14
- */
15
- export function useTheme() {
16
- return useThemeContext();
17
- }
18
-
19
- /**
20
- * Access branding configuration (logo, app name, tagline)
21
- */
22
- export function useBranding() {
23
- const theme = useThemeContext();
24
- return theme.branding;
25
- }
26
-
27
- /**
28
- * Access color configuration
29
- */
30
- export function useColors() {
31
- const theme = useThemeContext();
32
- return theme.colors;
33
- }
34
-
35
- /**
36
- * Access typography configuration
37
- */
38
- export function useTypography() {
39
- const theme = useThemeContext();
40
- return theme.typography;
41
- }
42
-
43
- /**
44
- * Access layout configuration
45
- */
46
- export function useLayout() {
47
- const theme = useThemeContext();
48
- return theme.layout;
49
- }
50
-
51
- /**
52
- * Access component-specific theme overrides
53
- */
54
- export function useComponentTheme() {
55
- const theme = useThemeContext();
56
- return theme.components;
57
- }
1
+ /**
2
+ * Theme Hooks for @payez/next-mvp
3
+ *
4
+ * Convenience hooks for accessing specific parts of the theme configuration.
5
+ * These hooks can only be used within components wrapped by ThemeProvider.
6
+ */
7
+
8
+ 'use client';
9
+
10
+ import { useTheme as useThemeContext } from './ThemeProvider';
11
+
12
+ /**
13
+ * Access the full theme configuration
14
+ */
15
+ export function useTheme() {
16
+ return useThemeContext();
17
+ }
18
+
19
+ /**
20
+ * Access branding configuration (logo, app name, tagline)
21
+ */
22
+ export function useBranding() {
23
+ const theme = useThemeContext();
24
+ return theme.branding;
25
+ }
26
+
27
+ /**
28
+ * Access color configuration
29
+ */
30
+ export function useColors() {
31
+ const theme = useThemeContext();
32
+ return theme.colors;
33
+ }
34
+
35
+ /**
36
+ * Access typography configuration
37
+ */
38
+ export function useTypography() {
39
+ const theme = useThemeContext();
40
+ return theme.typography;
41
+ }
42
+
43
+ /**
44
+ * Access layout configuration
45
+ */
46
+ export function useLayout() {
47
+ const theme = useThemeContext();
48
+ return theme.layout;
49
+ }
50
+
51
+ /**
52
+ * Access component-specific theme overrides
53
+ */
54
+ export function useComponentTheme() {
55
+ const theme = useThemeContext();
56
+ return theme.components;
57
+ }
@@ -1,40 +1,40 @@
1
- /**
2
- * Theme Utility Functions
3
- *
4
- * Provides helper functions for theme management, including deep merging
5
- * of theme configurations.
6
- */
7
-
8
- /**
9
- * Deep merge two objects, with the second object taking precedence
10
- * @param target - Base object
11
- * @param source - Object to merge in (takes precedence)
12
- * @returns Merged object
13
- */
14
- export function mergeDeep<T extends Record<string, any>>(target: T, source: Partial<T>): T {
15
- const output: any = { ...target };
16
-
17
- if (isObject(target) && isObject(source)) {
18
- Object.keys(source).forEach((key) => {
19
- const sourceValue = (source as any)[key];
20
- const targetValue = (target as any)[key];
21
-
22
- if (isObject(sourceValue) && isObject(targetValue)) {
23
- // Recursively merge nested objects
24
- output[key] = mergeDeep(targetValue, sourceValue);
25
- } else if (sourceValue !== undefined) {
26
- // Use source value if it's defined
27
- output[key] = sourceValue;
28
- }
29
- });
30
- }
31
-
32
- return output as T;
33
- }
34
-
35
- /**
36
- * Check if a value is a plain object
37
- */
38
- function isObject(item: any): item is Record<string, any> {
39
- return item && typeof item === 'object' && !Array.isArray(item);
40
- }
1
+ /**
2
+ * Theme Utility Functions
3
+ *
4
+ * Provides helper functions for theme management, including deep merging
5
+ * of theme configurations.
6
+ */
7
+
8
+ /**
9
+ * Deep merge two objects, with the second object taking precedence
10
+ * @param target - Base object
11
+ * @param source - Object to merge in (takes precedence)
12
+ * @returns Merged object
13
+ */
14
+ export function mergeDeep<T extends Record<string, any>>(target: T, source: Partial<T>): T {
15
+ const output: any = { ...target };
16
+
17
+ if (isObject(target) && isObject(source)) {
18
+ Object.keys(source).forEach((key) => {
19
+ const sourceValue = (source as any)[key];
20
+ const targetValue = (target as any)[key];
21
+
22
+ if (isObject(sourceValue) && isObject(targetValue)) {
23
+ // Recursively merge nested objects
24
+ output[key] = mergeDeep(targetValue, sourceValue);
25
+ } else if (sourceValue !== undefined) {
26
+ // Use source value if it's defined
27
+ output[key] = sourceValue;
28
+ }
29
+ });
30
+ }
31
+
32
+ return output as T;
33
+ }
34
+
35
+ /**
36
+ * Check if a value is a plain object
37
+ */
38
+ function isObject(item: any): item is Record<string, any> {
39
+ return item && typeof item === 'object' && !Array.isArray(item);
40
+ }
package/src/types/api.ts CHANGED
@@ -1,13 +1,13 @@
1
- export interface ApiResponse<T = any> { success: boolean; data?: T; error?: ApiError; meta?: ApiMeta; timestamp: string; requestId: string; }
2
- export interface ApiError { code: string; message: string; details?: Record<string, any>; field?: string; resolution?: string; supportContact?: string; remainingAttempts?: number; }
3
- export interface ApiMeta { version: string; responseTime: number; operation?: string; rateLimit?: { limit: number; remaining: number; resetAt: string; }; pagination?: { page: number; pageSize: number; total: number; totalPages: number; }; cached?: boolean; filters?: Record<string, any>; aggregation?: Record<string, any>; resourceId?: string | number; }
4
- export interface ApiRequestContext { requestId: string; startTime: number; userAgent?: string; ipAddress?: string; userId?: string; sessionId?: string; endpoint: string; method: string; params?: Record<string, string>; headers?: Record<string, string>; }
5
- export interface ApiValidationError { field: string; message: string; code: string; value?: any; }
6
- export interface ApiAuthContext { accessToken: string | null; tokenType: string; refreshToken: string | null; userId?: string; roles?: string[]; sessionId?: string; expiresAt?: number; }
7
- export interface ApiHandlerConfig { requireAuth?: boolean; requiredRoles?: readonly string[]; rateLimit?: { windowMs: number; maxRequests: number; }; validation?: { body?: any; query?: any; params?: any; }; timeout?: number; retries?: number; cacheTtl?: number; tokenRefreshBuffer?: number; }
8
- export interface ApiMiddleware { name: string; execute: (context: ApiRequestContext, config: ApiHandlerConfig) => Promise<void>; }
9
- export enum ApiErrorCode { UNAUTHORIZED='UNAUTHORIZED', FORBIDDEN='FORBIDDEN', TOKEN_EXPIRED='TOKEN_EXPIRED', INVALID_TOKEN='INVALID_TOKEN', INVALID_SESSION='INVALID_SESSION', INVALID_2FA_TOKEN='INVALID_2FA_TOKEN', INSUFFICIENT_PERMISSIONS='INSUFFICIENT_PERMISSIONS', RATE_LIMIT_EXCEEDED='RATE_LIMIT_EXCEEDED', TOO_MANY_REQUESTS='TOO_MANY_REQUESTS', VALIDATION_ERROR='VALIDATION_ERROR', INVALID_REQUEST='INVALID_REQUEST', MISSING_REQUIRED_FIELD='MISSING_REQUIRED_FIELD', INVALID_FORMAT='INVALID_FORMAT', RESOURCE_NOT_FOUND='RESOURCE_NOT_FOUND', NOT_FOUND='NOT_FOUND', RESOURCE_CONFLICT='RESOURCE_CONFLICT', CONFLICT='CONFLICT', BUSINESS_RULE_VIOLATION='BUSINESS_RULE_VIOLATION', NOT_IMPLEMENTED='NOT_IMPLEMENTED', INTERNAL_ERROR='INTERNAL_ERROR', INTERNAL_SERVER_ERROR='INTERNAL_SERVER_ERROR', SERVICE_UNAVAILABLE='SERVICE_UNAVAILABLE', TIMEOUT='TIMEOUT', CIRCUIT_BREAKER_OPEN='CIRCUIT_BREAKER_OPEN', UPSTREAM_SERVICE_ERROR='UPSTREAM_SERVICE_ERROR', NETWORK_ERROR='NETWORK_ERROR', CONNECTION_ERROR='CONNECTION_ERROR', UNKNOWN_ERROR='UNKNOWN_ERROR' }
10
- export const ApiErrorMessages: Record<ApiErrorCode, string> = { [ApiErrorCode.UNAUTHORIZED]:'Authentication required',[ApiErrorCode.FORBIDDEN]:'Access denied',[ApiErrorCode.TOKEN_EXPIRED]:'Authentication token has expired',[ApiErrorCode.INVALID_TOKEN]:'Invalid authentication token',[ApiErrorCode.INVALID_SESSION]:'Invalid session - please log in again',[ApiErrorCode.INVALID_2FA_TOKEN]:'Invalid or expired 2FA verification token',[ApiErrorCode.INSUFFICIENT_PERMISSIONS]:'Insufficient permissions for this resource',[ApiErrorCode.RATE_LIMIT_EXCEEDED]:'Rate limit exceeded',[ApiErrorCode.TOO_MANY_REQUESTS]:'Too many requests',[ApiErrorCode.VALIDATION_ERROR]:'Request validation failed',[ApiErrorCode.INVALID_REQUEST]:'Invalid request format',[ApiErrorCode.MISSING_REQUIRED_FIELD]:'Required field is missing',[ApiErrorCode.INVALID_FORMAT]:'Invalid data format',[ApiErrorCode.RESOURCE_NOT_FOUND]:'Resource not found',[ApiErrorCode.NOT_FOUND]:'Not found',[ApiErrorCode.RESOURCE_CONFLICT]:'Resource conflict',[ApiErrorCode.CONFLICT]:'Conflict',[ApiErrorCode.BUSINESS_RULE_VIOLATION]:'Business rule violation',[ApiErrorCode.NOT_IMPLEMENTED]:'Feature not yet implemented',[ApiErrorCode.INTERNAL_ERROR]:'Internal error occurred',[ApiErrorCode.INTERNAL_SERVER_ERROR]:'Internal server error',[ApiErrorCode.SERVICE_UNAVAILABLE]:'Service temporarily unavailable',[ApiErrorCode.TIMEOUT]:'Request timeout',[ApiErrorCode.CIRCUIT_BREAKER_OPEN]:'Service circuit breaker is open',[ApiErrorCode.UPSTREAM_SERVICE_ERROR]:'Upstream service error',[ApiErrorCode.NETWORK_ERROR]:'Network error',[ApiErrorCode.CONNECTION_ERROR]:'Connection error',[ApiErrorCode.UNKNOWN_ERROR]:'An unknown error occurred' };
11
- export type ApiSuccessResponse<T> = ApiResponse<T> & { success: true; data: T; message: string; operation_code: string; };
12
- export type ApiErrorResponse = ApiResponse<never> & { success: false; error: ApiError };
1
+ export interface ApiResponse<T = any> { success: boolean; data?: T; error?: ApiError; meta?: ApiMeta; timestamp: string; requestId: string; }
2
+ export interface ApiError { code: string; message: string; details?: Record<string, any>; field?: string; resolution?: string; supportContact?: string; remainingAttempts?: number; }
3
+ export interface ApiMeta { version: string; responseTime: number; operation?: string; rateLimit?: { limit: number; remaining: number; resetAt: string; }; pagination?: { page: number; pageSize: number; total: number; totalPages: number; }; cached?: boolean; filters?: Record<string, any>; aggregation?: Record<string, any>; resourceId?: string | number; }
4
+ export interface ApiRequestContext { requestId: string; startTime: number; userAgent?: string; ipAddress?: string; userId?: string; sessionId?: string; endpoint: string; method: string; params?: Record<string, string>; headers?: Record<string, string>; }
5
+ export interface ApiValidationError { field: string; message: string; code: string; value?: any; }
6
+ export interface ApiAuthContext { accessToken: string | null; tokenType: string; refreshToken: string | null; userId?: string; roles?: string[]; sessionId?: string; expiresAt?: number; }
7
+ export interface ApiHandlerConfig { requireAuth?: boolean; requiredRoles?: readonly string[]; rateLimit?: { windowMs: number; maxRequests: number; }; validation?: { body?: any; query?: any; params?: any; }; timeout?: number; retries?: number; cacheTtl?: number; tokenRefreshBuffer?: number; }
8
+ export interface ApiMiddleware { name: string; execute: (context: ApiRequestContext, config: ApiHandlerConfig) => Promise<void>; }
9
+ export enum ApiErrorCode { UNAUTHORIZED='UNAUTHORIZED', FORBIDDEN='FORBIDDEN', TOKEN_EXPIRED='TOKEN_EXPIRED', INVALID_TOKEN='INVALID_TOKEN', INVALID_SESSION='INVALID_SESSION', INVALID_2FA_TOKEN='INVALID_2FA_TOKEN', INSUFFICIENT_PERMISSIONS='INSUFFICIENT_PERMISSIONS', RATE_LIMIT_EXCEEDED='RATE_LIMIT_EXCEEDED', TOO_MANY_REQUESTS='TOO_MANY_REQUESTS', VALIDATION_ERROR='VALIDATION_ERROR', INVALID_REQUEST='INVALID_REQUEST', MISSING_REQUIRED_FIELD='MISSING_REQUIRED_FIELD', INVALID_FORMAT='INVALID_FORMAT', RESOURCE_NOT_FOUND='RESOURCE_NOT_FOUND', NOT_FOUND='NOT_FOUND', RESOURCE_CONFLICT='RESOURCE_CONFLICT', CONFLICT='CONFLICT', BUSINESS_RULE_VIOLATION='BUSINESS_RULE_VIOLATION', NOT_IMPLEMENTED='NOT_IMPLEMENTED', INTERNAL_ERROR='INTERNAL_ERROR', INTERNAL_SERVER_ERROR='INTERNAL_SERVER_ERROR', SERVICE_UNAVAILABLE='SERVICE_UNAVAILABLE', TIMEOUT='TIMEOUT', CIRCUIT_BREAKER_OPEN='CIRCUIT_BREAKER_OPEN', UPSTREAM_SERVICE_ERROR='UPSTREAM_SERVICE_ERROR', NETWORK_ERROR='NETWORK_ERROR', CONNECTION_ERROR='CONNECTION_ERROR', UNKNOWN_ERROR='UNKNOWN_ERROR' }
10
+ export const ApiErrorMessages: Record<ApiErrorCode, string> = { [ApiErrorCode.UNAUTHORIZED]:'Authentication required',[ApiErrorCode.FORBIDDEN]:'Access denied',[ApiErrorCode.TOKEN_EXPIRED]:'Authentication token has expired',[ApiErrorCode.INVALID_TOKEN]:'Invalid authentication token',[ApiErrorCode.INVALID_SESSION]:'Invalid session - please log in again',[ApiErrorCode.INVALID_2FA_TOKEN]:'Invalid or expired 2FA verification token',[ApiErrorCode.INSUFFICIENT_PERMISSIONS]:'Insufficient permissions for this resource',[ApiErrorCode.RATE_LIMIT_EXCEEDED]:'Rate limit exceeded',[ApiErrorCode.TOO_MANY_REQUESTS]:'Too many requests',[ApiErrorCode.VALIDATION_ERROR]:'Request validation failed',[ApiErrorCode.INVALID_REQUEST]:'Invalid request format',[ApiErrorCode.MISSING_REQUIRED_FIELD]:'Required field is missing',[ApiErrorCode.INVALID_FORMAT]:'Invalid data format',[ApiErrorCode.RESOURCE_NOT_FOUND]:'Resource not found',[ApiErrorCode.NOT_FOUND]:'Not found',[ApiErrorCode.RESOURCE_CONFLICT]:'Resource conflict',[ApiErrorCode.CONFLICT]:'Conflict',[ApiErrorCode.BUSINESS_RULE_VIOLATION]:'Business rule violation',[ApiErrorCode.NOT_IMPLEMENTED]:'Feature not yet implemented',[ApiErrorCode.INTERNAL_ERROR]:'Internal error occurred',[ApiErrorCode.INTERNAL_SERVER_ERROR]:'Internal server error',[ApiErrorCode.SERVICE_UNAVAILABLE]:'Service temporarily unavailable',[ApiErrorCode.TIMEOUT]:'Request timeout',[ApiErrorCode.CIRCUIT_BREAKER_OPEN]:'Service circuit breaker is open',[ApiErrorCode.UPSTREAM_SERVICE_ERROR]:'Upstream service error',[ApiErrorCode.NETWORK_ERROR]:'Network error',[ApiErrorCode.CONNECTION_ERROR]:'Connection error',[ApiErrorCode.UNKNOWN_ERROR]:'An unknown error occurred' };
11
+ export type ApiSuccessResponse<T> = ApiResponse<T> & { success: true; data: T; message: string; operation_code: string; };
12
+ export type ApiErrorResponse = ApiResponse<never> & { success: false; error: ApiError };
13
13
  export class ApiResponseBuilder { private context: ApiRequestContext; private config: ApiHandlerConfig; constructor(context: ApiRequestContext, config: ApiHandlerConfig = {}) { this.context = context; this.config = config; } success<T>(data: T, meta?: Partial<ApiMeta>): ApiSuccessResponse<T> { return { success: true, data, message: meta?.operation ? `${meta.operation.replace(/-/g, ' ')} completed successfully` : 'Operation completed successfully', operation_code: meta?.operation || 'unknown-operation', meta: { version:'1.0', responseTime: Date.now() - this.context.startTime, ...meta }, timestamp: new Date().toISOString(), requestId: this.context.requestId }; } error(code: ApiErrorCode, message?: string, details?: Record<string, any>, field?: string): ApiErrorResponse { const errorMessage = message || ApiErrorMessages[code]; const enhancedDetails = { ...details, ...(this.context.endpoint && { endpoint: this.context.endpoint }), ...(this.context.method && { method: this.context.method }), timestamp: new Date().toISOString() }; return { success: false, error: { code, message: errorMessage, details: enhancedDetails, field, resolution: this.getResolution(code), supportContact: process.env.SUPPORT_CONTACT }, meta: { version: '1.0', responseTime: Date.now() - this.context.startTime }, timestamp: new Date().toISOString(), requestId: this.context.requestId }; } private getResolution(code: ApiErrorCode): string | undefined { const resolutions: Partial<Record<ApiErrorCode, string>> = { [ApiErrorCode.RATE_LIMIT_EXCEEDED]:'Please try again later',[ApiErrorCode.TOKEN_EXPIRED]:'Please refresh your session',[ApiErrorCode.UNAUTHORIZED]:'Please log in again',[ApiErrorCode.SERVICE_UNAVAILABLE]:'Please try again in a few minutes',[ApiErrorCode.CIRCUIT_BREAKER_OPEN]:'Service is temporarily unavailable. Please try again later.' }; return resolutions[code]; }}
@@ -1,23 +1,23 @@
1
- export interface Session {
2
- user?: { name?: string | null; email?: string | null; image?: string | null; id?: string };
3
- expires: string;
4
- }
5
- export interface JWT {
6
- [key: string]: unknown;
7
- name?: string | null;
8
- email?: string | null;
9
- sub?: string;
10
- }
11
- export type TwoFactorMethod = 'none' | 'sms' | 'authenticator' | 'passkey';
12
-
13
- export interface User {
14
- id: string; email: string; name?: string | null; roles: string[]; twoFactorMethod?: TwoFactorMethod; requiresTwoFactor: boolean; accessToken?: string; refreshToken?: string; tokenType?: string;
15
- authenticationMethods?: string[]; authenticationLevel?: string;
16
- }
17
-
18
- export interface JwtPayload { [key: string]: unknown; sub: string; email: string; name?: string; roles?: string[]; exp: number; iat: number; aud: string; iss: string; requiresTwoFactor?: boolean; twoFactorMethod?: TwoFactorMethod; amr?: string[]; acr?: string; }
19
- export interface JwtPayloadWithRoles extends JwtPayload { roles: string[]; requiresTwoFactor: boolean; twoFactorMethod?: TwoFactorMethod; amr?: string[]; acr?: string; }
20
-
21
- export interface AuthorizeCredentials { email?: string; password?: string; token?: string; twoFactorCode?: string; twoFactorMethod?: TwoFactorMethod; }
22
-
23
- export interface ApiResponse { access_token?: string; refresh_token?: string; requiresTwoFactor?: boolean; twoFactorMethod?: TwoFactorMethod; user_id?: string; email?: string; name?: string; roles?: string[]; error?: string; message?: string; result?: { access_token?: string; refresh_token?: string; name?: string; error?: string; id?: string; email?: string; roles?: string[]; user?: { email?: string; name?: string; roles?: string[]; id?: string; twoFactorMethod?: TwoFactorMethod | null; requiresTwoFactor?: boolean; accessToken?: string; refreshToken?: string; tokenType?: string; }; }; }
1
+ export interface Session {
2
+ user?: { name?: string | null; email?: string | null; image?: string | null; id?: string };
3
+ expires: string;
4
+ }
5
+ export interface JWT {
6
+ [key: string]: unknown;
7
+ name?: string | null;
8
+ email?: string | null;
9
+ sub?: string;
10
+ }
11
+ export type TwoFactorMethod = 'none' | 'sms' | 'authenticator' | 'passkey';
12
+
13
+ export interface User {
14
+ id: string; email: string; name?: string | null; roles: string[]; twoFactorMethod?: TwoFactorMethod; requiresTwoFactor: boolean; accessToken?: string; refreshToken?: string; tokenType?: string;
15
+ authenticationMethods?: string[]; authenticationLevel?: string;
16
+ }
17
+
18
+ export interface JwtPayload { [key: string]: unknown; sub: string; email: string; name?: string; roles?: string[]; exp: number; iat: number; aud: string; iss: string; requiresTwoFactor?: boolean; twoFactorMethod?: TwoFactorMethod; amr?: string[]; acr?: string; }
19
+ export interface JwtPayloadWithRoles extends JwtPayload { roles: string[]; requiresTwoFactor: boolean; twoFactorMethod?: TwoFactorMethod; amr?: string[]; acr?: string; }
20
+
21
+ export interface AuthorizeCredentials { email?: string; password?: string; token?: string; twoFactorCode?: string; twoFactorMethod?: TwoFactorMethod; }
22
+
23
+ export interface ApiResponse { access_token?: string; refresh_token?: string; requiresTwoFactor?: boolean; twoFactorMethod?: TwoFactorMethod; user_id?: string; email?: string; name?: string; roles?: string[]; error?: string; message?: string; result?: { access_token?: string; refresh_token?: string; name?: string; error?: string; id?: string; email?: string; roles?: string[]; user?: { email?: string; name?: string; roles?: string[]; id?: string; twoFactorMethod?: TwoFactorMethod | null; requiresTwoFactor?: boolean; accessToken?: string; refreshToken?: string; tokenType?: string; }; }; }
package/src/types/auth.ts CHANGED
@@ -1,22 +1,22 @@
1
- import { JwtPayload } from 'jwt-decode';
2
-
3
- export type AuthMode = 'traditional' | 'federated';
4
- export type FederatedProvider = 'google' | 'microsoft' | 'facebook' | 'github' | 'apple';
5
-
6
- export interface AuthConfig {
7
- mode: AuthMode;
8
- providers: FederatedProvider[];
9
- enableRecovery: boolean;
10
- enableEmailSignup: boolean;
11
- allowPasswordReset: boolean;
12
- }
13
-
14
- export interface JwtPayloadWithRoles extends JwtPayload {
15
- role?: string | string[];
16
- roles?: string[];
17
- amr?: string[];
18
- acr?: string;
19
- mfa_time?: number;
20
- mfa_expires?: number;
21
- mfa_validity_hours?: number;
22
- }
1
+ import { JwtPayload } from 'jwt-decode';
2
+
3
+ export type AuthMode = 'traditional' | 'federated';
4
+ export type FederatedProvider = 'google' | 'microsoft' | 'facebook' | 'github' | 'apple';
5
+
6
+ export interface AuthConfig {
7
+ mode: AuthMode;
8
+ providers: FederatedProvider[];
9
+ enableRecovery: boolean;
10
+ enableEmailSignup: boolean;
11
+ allowPasswordReset: boolean;
12
+ }
13
+
14
+ export interface JwtPayloadWithRoles extends JwtPayload {
15
+ role?: string | string[];
16
+ roles?: string[];
17
+ amr?: string[];
18
+ acr?: string;
19
+ mfa_time?: number;
20
+ mfa_expires?: number;
21
+ mfa_validity_hours?: number;
22
+ }
@@ -1,11 +1,11 @@
1
- export interface LoggingConfig {
2
- logLevel: LogLevel;
3
- console: { enabled: boolean; colors: boolean; };
4
- graylog: { enabled: boolean; host: string; port: number; facility: string; staticMeta: { service: string; application: string; version: string; [key: string]: any; }; };
5
- components: { [key: string]: { enabled: boolean; prefix: string; }; };
6
- levels: { [key: string]: number; };
7
- }
8
- export type LogLevel = 'error' | 'warn' | 'info' | 'http' | 'debug';
9
- export interface ComponentLoggerConfig { enabled: boolean; prefix: string; }
10
- export interface Logger { error: (message: string, meta?: any) => void; warn: (message: string, meta?: any) => void; info: (message: string, meta?: any) => void; http: (message: string, meta?: any) => void; debug: (message: string, meta?: any) => void; }
11
- export interface ComponentLogger extends Logger {}
1
+ export interface LoggingConfig {
2
+ logLevel: LogLevel;
3
+ console: { enabled: boolean; colors: boolean; };
4
+ graylog: { enabled: boolean; host: string; port: number; facility: string; staticMeta: { service: string; application: string; version: string; [key: string]: any; }; };
5
+ components: { [key: string]: { enabled: boolean; prefix: string; }; };
6
+ levels: { [key: string]: number; };
7
+ }
8
+ export type LogLevel = 'error' | 'warn' | 'info' | 'http' | 'debug';
9
+ export interface ComponentLoggerConfig { enabled: boolean; prefix: string; }
10
+ export interface Logger { error: (message: string, meta?: any) => void; warn: (message: string, meta?: any) => void; info: (message: string, meta?: any) => void; http: (message: string, meta?: any) => void; debug: (message: string, meta?: any) => void; }
11
+ export interface ComponentLogger extends Logger {}