@leanmcp/auth 0.4.2 → 0.4.4-alpha.6.6dae082

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.
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Shared types for @leanmcp/auth
3
+ */
4
+ /**
5
+ * Options for the Authenticated decorator
6
+ */
7
+ interface AuthenticatedOptions {
8
+ /**
9
+ * Whether to fetch and attach user information to authUser variable
10
+ * @default true
11
+ */
12
+ getUser?: boolean;
13
+ /**
14
+ * Project ID for fetching user environment variables.
15
+ * Required when @RequireEnv is used on the method or class.
16
+ * Used to scope user secrets to a specific project.
17
+ */
18
+ projectId?: string;
19
+ }
20
+
21
+ /**
22
+ * Global authUser type declaration
23
+ * This makes authUser available in @Authenticated methods without explicit declaration
24
+ */
25
+ declare global {
26
+ /**
27
+ * Authenticated user object automatically available in @Authenticated methods
28
+ *
29
+ * Implemented as a getter that reads from AsyncLocalStorage for concurrency safety.
30
+ * Each request has its own isolated context - 100% safe for concurrent requests.
31
+ */
32
+ const authUser: any;
33
+ }
34
+ /**
35
+ * Get the current authenticated user from the async context
36
+ * This is safe for concurrent requests as each request has its own context
37
+ */
38
+ declare function getAuthUser(): any;
39
+ /**
40
+ * Authentication error class for better error handling
41
+ */
42
+ declare class AuthenticationError extends Error {
43
+ code: string;
44
+ constructor(message: string, code: string);
45
+ }
46
+ /**
47
+ * Decorator to protect MCP tools, prompts, resources, or entire services with authentication
48
+ *
49
+ * CONCURRENCY SAFE: Uses AsyncLocalStorage to ensure each request has its own isolated
50
+ * authUser context, preventing race conditions in high-concurrency scenarios.
51
+ *
52
+ * Usage:
53
+ *
54
+ * 1. Protect individual methods with automatic user info:
55
+ * ```typescript
56
+ * @Tool({ description: 'Analyze sentiment' })
57
+ * @Authenticated(authProvider, { getUser: true })
58
+ * async analyzeSentiment(args: AnalyzeSentimentInput): Promise<AnalyzeSentimentOutput> {
59
+ * // authUser is automatically available in method scope
60
+ * console.log('User:', authUser);
61
+ * console.log('User ID:', authUser.sub);
62
+ * }
63
+ * ```
64
+ *
65
+ * 2. Protect without fetching user info:
66
+ * ```typescript
67
+ * @Tool({ description: 'Public tool' })
68
+ * @Authenticated(authProvider, { getUser: false })
69
+ * async publicTool(args: PublicToolInput): Promise<PublicToolOutput> {
70
+ * // Only verifies token, doesn't fetch user info
71
+ * }
72
+ * ```
73
+ *
74
+ * 3. Protect entire service (all tools/prompts/resources):
75
+ * ```typescript
76
+ * @Authenticated(authProvider)
77
+ * export class SentimentAnalysisService {
78
+ * @Tool({ description: 'Analyze sentiment' })
79
+ * async analyzeSentiment(args: AnalyzeSentimentInput) {
80
+ * // All methods in this service require authentication
81
+ * // authUser is automatically available in all methods
82
+ * console.log('User:', authUser);
83
+ * }
84
+ * }
85
+ * ```
86
+ *
87
+ * The decorator expects authentication token in the MCP request _meta field:
88
+ * ```json
89
+ * {
90
+ * "method": "tools/call",
91
+ * "params": {
92
+ * "name": "toolName",
93
+ * "arguments": { ...businessData },
94
+ * "_meta": {
95
+ * "authorization": {
96
+ * "type": "bearer",
97
+ * "token": "your-jwt-token"
98
+ * }
99
+ * }
100
+ * }
101
+ * }
102
+ * ```
103
+ *
104
+ * @param authProvider - Instance of AuthProviderBase to use for token verification
105
+ * @param options - Optional configuration for authentication behavior
106
+ */
107
+ declare function Authenticated(authProvider: AuthProviderBase, options?: AuthenticatedOptions): (target: any, propertyKey?: string | symbol, descriptor?: PropertyDescriptor) => any;
108
+ /**
109
+ * Check if a method or class requires authentication
110
+ */
111
+ declare function isAuthenticationRequired(target: any): boolean;
112
+ /**
113
+ * Get the auth provider for a method or class
114
+ */
115
+ declare function getAuthProvider(target: any): AuthProviderBase | undefined;
116
+
117
+ /**
118
+ * @leanmcp/auth - Authentication Module
119
+ *
120
+ * This module provides a base class for implementing authentication providers for MCP tools.
121
+ * Extend AuthProviderBase to integrate with different auth providers (Clerk, Stripe, Firebase, etc.)
122
+ */
123
+ /**
124
+ * Base class for authentication providers
125
+ * Extend this class to implement integrations with different auth providers
126
+ */
127
+ declare abstract class AuthProviderBase {
128
+ /**
129
+ * Initialize the auth provider with configuration
130
+ */
131
+ abstract init(config?: any): Promise<void>;
132
+ /**
133
+ * Refresh an authentication token
134
+ */
135
+ abstract refreshToken(refreshToken: string, username?: string): Promise<any>;
136
+ /**
137
+ * Verify if a token is valid
138
+ */
139
+ abstract verifyToken(token: string): Promise<boolean>;
140
+ /**
141
+ * Get user information from a token
142
+ */
143
+ abstract getUser(token: string): Promise<any>;
144
+ }
145
+ /**
146
+ * Unified AuthProvider class that dynamically selects the appropriate auth provider
147
+ * based on the provider parameter
148
+ */
149
+ declare class AuthProvider extends AuthProviderBase {
150
+ private providerInstance;
151
+ private providerType;
152
+ private config;
153
+ constructor(provider: string, config?: any);
154
+ /**
155
+ * Initialize the selected auth provider
156
+ */
157
+ init(config?: any): Promise<void>;
158
+ /**
159
+ * Refresh an authentication token
160
+ */
161
+ refreshToken(refreshToken: string, username?: string): Promise<any>;
162
+ /**
163
+ * Verify if a token is valid
164
+ */
165
+ verifyToken(token: string): Promise<boolean>;
166
+ /**
167
+ * Get user information from a token
168
+ */
169
+ getUser(token: string): Promise<any>;
170
+ /**
171
+ * Get user secrets for a project (LeanMCP provider only)
172
+ * Other providers will return empty object
173
+ */
174
+ getUserSecrets(token: string, projectId: string): Promise<Record<string, string>>;
175
+ /**
176
+ * Get the provider type
177
+ */
178
+ getProviderType(): string;
179
+ }
180
+
181
+ export { AuthProvider, AuthProviderBase, Authenticated, type AuthenticatedOptions, AuthenticationError, getAuthProvider, getAuthUser, isAuthenticationRequired };
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Shared types for @leanmcp/auth
3
+ */
4
+ /**
5
+ * Options for the Authenticated decorator
6
+ */
7
+ interface AuthenticatedOptions {
8
+ /**
9
+ * Whether to fetch and attach user information to authUser variable
10
+ * @default true
11
+ */
12
+ getUser?: boolean;
13
+ /**
14
+ * Project ID for fetching user environment variables.
15
+ * Required when @RequireEnv is used on the method or class.
16
+ * Used to scope user secrets to a specific project.
17
+ */
18
+ projectId?: string;
19
+ }
20
+
21
+ /**
22
+ * Global authUser type declaration
23
+ * This makes authUser available in @Authenticated methods without explicit declaration
24
+ */
25
+ declare global {
26
+ /**
27
+ * Authenticated user object automatically available in @Authenticated methods
28
+ *
29
+ * Implemented as a getter that reads from AsyncLocalStorage for concurrency safety.
30
+ * Each request has its own isolated context - 100% safe for concurrent requests.
31
+ */
32
+ const authUser: any;
33
+ }
34
+ /**
35
+ * Get the current authenticated user from the async context
36
+ * This is safe for concurrent requests as each request has its own context
37
+ */
38
+ declare function getAuthUser(): any;
39
+ /**
40
+ * Authentication error class for better error handling
41
+ */
42
+ declare class AuthenticationError extends Error {
43
+ code: string;
44
+ constructor(message: string, code: string);
45
+ }
46
+ /**
47
+ * Decorator to protect MCP tools, prompts, resources, or entire services with authentication
48
+ *
49
+ * CONCURRENCY SAFE: Uses AsyncLocalStorage to ensure each request has its own isolated
50
+ * authUser context, preventing race conditions in high-concurrency scenarios.
51
+ *
52
+ * Usage:
53
+ *
54
+ * 1. Protect individual methods with automatic user info:
55
+ * ```typescript
56
+ * @Tool({ description: 'Analyze sentiment' })
57
+ * @Authenticated(authProvider, { getUser: true })
58
+ * async analyzeSentiment(args: AnalyzeSentimentInput): Promise<AnalyzeSentimentOutput> {
59
+ * // authUser is automatically available in method scope
60
+ * console.log('User:', authUser);
61
+ * console.log('User ID:', authUser.sub);
62
+ * }
63
+ * ```
64
+ *
65
+ * 2. Protect without fetching user info:
66
+ * ```typescript
67
+ * @Tool({ description: 'Public tool' })
68
+ * @Authenticated(authProvider, { getUser: false })
69
+ * async publicTool(args: PublicToolInput): Promise<PublicToolOutput> {
70
+ * // Only verifies token, doesn't fetch user info
71
+ * }
72
+ * ```
73
+ *
74
+ * 3. Protect entire service (all tools/prompts/resources):
75
+ * ```typescript
76
+ * @Authenticated(authProvider)
77
+ * export class SentimentAnalysisService {
78
+ * @Tool({ description: 'Analyze sentiment' })
79
+ * async analyzeSentiment(args: AnalyzeSentimentInput) {
80
+ * // All methods in this service require authentication
81
+ * // authUser is automatically available in all methods
82
+ * console.log('User:', authUser);
83
+ * }
84
+ * }
85
+ * ```
86
+ *
87
+ * The decorator expects authentication token in the MCP request _meta field:
88
+ * ```json
89
+ * {
90
+ * "method": "tools/call",
91
+ * "params": {
92
+ * "name": "toolName",
93
+ * "arguments": { ...businessData },
94
+ * "_meta": {
95
+ * "authorization": {
96
+ * "type": "bearer",
97
+ * "token": "your-jwt-token"
98
+ * }
99
+ * }
100
+ * }
101
+ * }
102
+ * ```
103
+ *
104
+ * @param authProvider - Instance of AuthProviderBase to use for token verification
105
+ * @param options - Optional configuration for authentication behavior
106
+ */
107
+ declare function Authenticated(authProvider: AuthProviderBase, options?: AuthenticatedOptions): (target: any, propertyKey?: string | symbol, descriptor?: PropertyDescriptor) => any;
108
+ /**
109
+ * Check if a method or class requires authentication
110
+ */
111
+ declare function isAuthenticationRequired(target: any): boolean;
112
+ /**
113
+ * Get the auth provider for a method or class
114
+ */
115
+ declare function getAuthProvider(target: any): AuthProviderBase | undefined;
116
+
117
+ /**
118
+ * @leanmcp/auth - Authentication Module
119
+ *
120
+ * This module provides a base class for implementing authentication providers for MCP tools.
121
+ * Extend AuthProviderBase to integrate with different auth providers (Clerk, Stripe, Firebase, etc.)
122
+ */
123
+ /**
124
+ * Base class for authentication providers
125
+ * Extend this class to implement integrations with different auth providers
126
+ */
127
+ declare abstract class AuthProviderBase {
128
+ /**
129
+ * Initialize the auth provider with configuration
130
+ */
131
+ abstract init(config?: any): Promise<void>;
132
+ /**
133
+ * Refresh an authentication token
134
+ */
135
+ abstract refreshToken(refreshToken: string, username?: string): Promise<any>;
136
+ /**
137
+ * Verify if a token is valid
138
+ */
139
+ abstract verifyToken(token: string): Promise<boolean>;
140
+ /**
141
+ * Get user information from a token
142
+ */
143
+ abstract getUser(token: string): Promise<any>;
144
+ }
145
+ /**
146
+ * Unified AuthProvider class that dynamically selects the appropriate auth provider
147
+ * based on the provider parameter
148
+ */
149
+ declare class AuthProvider extends AuthProviderBase {
150
+ private providerInstance;
151
+ private providerType;
152
+ private config;
153
+ constructor(provider: string, config?: any);
154
+ /**
155
+ * Initialize the selected auth provider
156
+ */
157
+ init(config?: any): Promise<void>;
158
+ /**
159
+ * Refresh an authentication token
160
+ */
161
+ refreshToken(refreshToken: string, username?: string): Promise<any>;
162
+ /**
163
+ * Verify if a token is valid
164
+ */
165
+ verifyToken(token: string): Promise<boolean>;
166
+ /**
167
+ * Get user information from a token
168
+ */
169
+ getUser(token: string): Promise<any>;
170
+ /**
171
+ * Get user secrets for a project (LeanMCP provider only)
172
+ * Other providers will return empty object
173
+ */
174
+ getUserSecrets(token: string, projectId: string): Promise<Record<string, string>>;
175
+ /**
176
+ * Get the provider type
177
+ */
178
+ getProviderType(): string;
179
+ }
180
+
181
+ export { AuthProvider, AuthProviderBase, Authenticated, type AuthenticatedOptions, AuthenticationError, getAuthProvider, getAuthUser, isAuthenticationRequired };
package/dist/index.js CHANGED
@@ -669,13 +669,13 @@ var init_leanmcp = __esm({
669
669
  };
670
670
  }
671
671
  /**
672
- * Fetch user-specific environment variables for a project
673
- * Uses the user's UID and project ID to retrieve their stored secrets
674
- *
675
- * @param token - User's auth token
676
- * @param projectId - Project ID to scope the secrets
677
- * @returns Record of environment variables
678
- */
672
+ * Fetch user-specific environment variables for a project
673
+ * Uses the user's UID and project ID to retrieve their stored secrets
674
+ *
675
+ * @param token - User's auth token
676
+ * @param projectId - Project ID to scope the secrets
677
+ * @returns Record of environment variables
678
+ */
679
679
  async getUserSecrets(token, projectId) {
680
680
  if (!this.apiKey) {
681
681
  console.warn("[LeanMCP] API key not configured - cannot fetch user secrets. Set LEANMCP_API_KEY environment variable or pass apiKey in config.");
@@ -685,7 +685,7 @@ var init_leanmcp = __esm({
685
685
  try {
686
686
  const { data } = await import_axios4.default.get(url, {
687
687
  headers: {
688
- "Authorization": `Bearer ${token}`,
688
+ Authorization: `Bearer ${token}`,
689
689
  "x-api-key": this.apiKey
690
690
  }
691
691
  });
package/dist/index.mjs CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  getAuthProvider,
7
7
  getAuthUser,
8
8
  isAuthenticationRequired
9
- } from "./chunk-P4HFKA5R.mjs";
9
+ } from "./chunk-ZJYMG6ZM.mjs";
10
10
  import "./chunk-LPEX4YW6.mjs";
11
11
  export {
12
12
  AuthProvider,
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  AuthProviderBase
3
- } from "./chunk-P4HFKA5R.mjs";
3
+ } from "./chunk-ZJYMG6ZM.mjs";
4
4
  import {
5
5
  __name
6
6
  } from "./chunk-LPEX4YW6.mjs";
@@ -108,13 +108,13 @@ var AuthLeanmcp = class extends AuthProviderBase {
108
108
  };
109
109
  }
110
110
  /**
111
- * Fetch user-specific environment variables for a project
112
- * Uses the user's UID and project ID to retrieve their stored secrets
113
- *
114
- * @param token - User's auth token
115
- * @param projectId - Project ID to scope the secrets
116
- * @returns Record of environment variables
117
- */
111
+ * Fetch user-specific environment variables for a project
112
+ * Uses the user's UID and project ID to retrieve their stored secrets
113
+ *
114
+ * @param token - User's auth token
115
+ * @param projectId - Project ID to scope the secrets
116
+ * @returns Record of environment variables
117
+ */
118
118
  async getUserSecrets(token, projectId) {
119
119
  if (!this.apiKey) {
120
120
  console.warn("[LeanMCP] API key not configured - cannot fetch user secrets. Set LEANMCP_API_KEY environment variable or pass apiKey in config.");
@@ -124,7 +124,7 @@ var AuthLeanmcp = class extends AuthProviderBase {
124
124
  try {
125
125
  const { data } = await axios.get(url, {
126
126
  headers: {
127
- "Authorization": `Bearer ${token}`,
127
+ Authorization: `Bearer ${token}`,
128
128
  "x-api-key": this.apiKey
129
129
  }
130
130
  });