forked from GravityKit/MCP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
370 lines (327 loc) · 11.1 KB
/
Copy pathauth.js
File metadata and controls
370 lines (327 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/**
* Gravity Forms Authentication Module
* Supports Basic Authentication (primary) and OAuth 1.0a (secondary)
*
* Basic Authentication is prioritized per Gravity Forms v2 recommendations
* OAuth 1.0a included for advanced security requirements
*/
import crypto from 'crypto';
import logger from '../utils/logger.js';
/**
* Basic Authentication Handler (PRIMARY METHOD)
* Simple and secure authentication using Consumer Key/Secret over HTTPS
* Recommended for Gravity Forms v2 REST API
*/
export class BasicAuthHandler {
constructor(consumerKey, consumerSecret, baseUrl) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
this.baseUrl = baseUrl;
// Validate HTTPS for Basic Auth security
if (!this.baseUrl.startsWith('https://')) {
throw new Error('Basic Authentication requires HTTPS connection for security');
}
}
/**
* Generate Basic Auth headers for Gravity Forms v2
* Uses standard HTTP Basic Authentication with Consumer Key/Secret
*/
getAuthHeaders() {
const credentials = `${this.consumerKey}:${this.consumerSecret}`;
const encodedCredentials = Buffer.from(credentials).toString('base64');
return {
'Authorization': `Basic ${encodedCredentials}`,
'Content-Type': 'application/json',
'User-Agent': 'Gravity MCP v1.0.0'
};
}
/**
* Test authentication by making a simple API call
* Validates both credentials and REST API availability
*/
async testConnection(httpClient) {
try {
const response = await httpClient.get('/forms', {
headers: this.getAuthHeaders(),
params: { per_page: 1 }
});
return {
success: true,
method: 'Basic Authentication',
message: 'Successfully connected to Gravity Forms REST API v2',
version: response.data.version || 'Unknown'
};
} catch (error) {
return {
success: false,
method: 'Basic Authentication',
error: error.response?.status === 401 ? 'Invalid credentials' : error.message,
details: error.response?.data || error.message
};
}
}
}
/**
* OAuth 1.0a Authentication Handler (SECONDARY METHOD)
* More complex but provides additional security features
* Included for environments requiring OAuth workflow
*/
export class OAuth1Handler {
constructor(consumerKey, consumerSecret, baseUrl) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
this.baseUrl = baseUrl;
}
/**
* Generate OAuth 1.0a signature for Gravity Forms API
* Implements RFC 5849 OAuth 1.0a specification
*/
generateOAuthSignature(method, url, params, timestamp, nonce) {
// Validate required parameters
if (!method || !url || !timestamp || !nonce) {
throw new Error('Invalid OAuth parameters: method, url, timestamp, and nonce are required');
}
// Combine all parameters
const allParams = {
...params,
oauth_consumer_key: this.consumerKey,
oauth_timestamp: timestamp,
oauth_nonce: nonce,
oauth_signature_method: 'HMAC-SHA1',
oauth_version: '1.0'
};
// Create parameter string
const paramString = Object.keys(allParams)
.sort()
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(allParams[key])}`)
.join('&');
// Create signature base string
const baseString = [
method.toUpperCase(),
encodeURIComponent(url),
encodeURIComponent(paramString)
].join('&');
// Create signing key
const signingKey = `${encodeURIComponent(this.consumerSecret)}&`;
// Generate signature
const signature = crypto
.createHmac('sha1', signingKey)
.update(baseString)
.digest('base64');
return signature;
}
/**
* Generate OAuth 1.0a headers for API request
*/
getAuthHeaders(method = 'GET', url, params = {}) {
const timestamp = Math.floor(Date.now() / 1000).toString();
const nonce = crypto.randomBytes(16).toString('hex');
const signature = this.generateOAuthSignature(method, url, params, timestamp, nonce);
const authHeader = [
`oauth_consumer_key="${encodeURIComponent(this.consumerKey)}"`,
`oauth_timestamp="${timestamp}"`,
`oauth_nonce="${nonce}"`,
`oauth_signature_method="HMAC-SHA1"`,
`oauth_version="1.0"`,
`oauth_signature="${encodeURIComponent(signature)}"`
].join(', ');
return {
'Authorization': `OAuth ${authHeader}`,
'Content-Type': 'application/json',
'User-Agent': 'Gravity MCP v1.0.0'
};
}
/**
* Test OAuth authentication
*/
async testConnection(httpClient) {
try {
const fullUrl = `${this.baseUrl}/wp-json/gf/v2/forms`;
const headers = this.getAuthHeaders('GET', fullUrl, { per_page: 1 });
const response = await httpClient.get('/forms', {
headers,
params: { per_page: 1 }
});
return {
success: true,
method: 'OAuth 1.0a',
message: 'Successfully connected to Gravity Forms REST API v2',
version: response.data.version || 'Unknown'
};
} catch (error) {
return {
success: false,
method: 'OAuth 1.0a',
error: error.response?.status === 401 ? 'Invalid OAuth signature or credentials' : error.message,
details: error.response?.data || error.message
};
}
}
}
/**
* Authentication Manager
* Handles authentication method selection and validation
* Prioritizes Basic Auth as recommended for Gravity Forms v2
*/
export class AuthManager {
constructor(config) {
this.config = config;
this.authHandler = null;
this.validateConfig();
this.initializeAuthHandler();
}
/**
* Validate authentication configuration
*/
validateConfig() {
const required = ['GRAVITY_FORMS_CONSUMER_KEY', 'GRAVITY_FORMS_CONSUMER_SECRET', 'GRAVITY_FORMS_BASE_URL'];
const missing = required.filter(key => !this.config[key]);
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
// Validate base URL format
const baseUrl = this.config.GRAVITY_FORMS_BASE_URL;
if (!baseUrl.startsWith('http://') && !baseUrl.startsWith('https://')) {
throw new Error('GRAVITY_FORMS_BASE_URL must start with http:// or https://');
}
// Remove trailing slash
this.config.GRAVITY_FORMS_BASE_URL = baseUrl.replace(/\/$/, '');
}
/**
* Initialize authentication handler
* Prioritizes Basic Authentication as primary method
*/
initializeAuthHandler() {
const { GRAVITY_FORMS_CONSUMER_KEY, GRAVITY_FORMS_CONSUMER_SECRET, GRAVITY_FORMS_BASE_URL } = this.config;
// Default to Basic Authentication (RECOMMENDED for Gravity Forms v2)
const authMethod = this.config.GRAVITY_FORMS_AUTH_METHOD || 'basic';
try {
if (authMethod.toLowerCase() === 'oauth' || authMethod.toLowerCase() === 'oauth1') {
if (this.config.GRAVITY_FORMS_DEBUG === 'true') {
logger.info('🔐 Using OAuth 1.0a Authentication');
}
this.authHandler = new OAuth1Handler(
GRAVITY_FORMS_CONSUMER_KEY,
GRAVITY_FORMS_CONSUMER_SECRET,
GRAVITY_FORMS_BASE_URL
);
} else {
if (this.config.GRAVITY_FORMS_DEBUG === 'true') {
logger.info('🔐 Using Basic Authentication (Recommended for Gravity Forms v2)');
}
this.authHandler = new BasicAuthHandler(
GRAVITY_FORMS_CONSUMER_KEY,
GRAVITY_FORMS_CONSUMER_SECRET,
GRAVITY_FORMS_BASE_URL
);
}
} catch (error) {
// Fallback to OAuth if Basic Auth fails (e.g., HTTP instead of HTTPS)
if (authMethod.toLowerCase() === 'basic' && error.message.includes('HTTPS')) {
// Only warn if not in test mode - check multiple ways tests might be run
const isTest = process.env.NODE_ENV === 'test' ||
process.env.GRAVITY_FORMS_TEST_MODE === 'true' ||
process.argv.some(arg => arg.includes('test'));
if (!isTest) {
console.warn('⚠️ Basic Authentication requires HTTPS. Falling back to OAuth 1.0a');
}
this.authHandler = new OAuth1Handler(
GRAVITY_FORMS_CONSUMER_KEY,
GRAVITY_FORMS_CONSUMER_SECRET,
GRAVITY_FORMS_BASE_URL
);
} else {
throw error;
}
}
}
/**
* Get authentication headers for HTTP requests
*/
getAuthHeaders(method = 'GET', url, params = {}) {
return this.authHandler.getAuthHeaders(method, url, params);
}
/**
* Test authentication connection
*/
async testConnection(httpClient) {
return await this.authHandler.testConnection(httpClient);
}
/**
* Get authentication method info
*/
getAuthInfo() {
return {
method: this.authHandler instanceof BasicAuthHandler ? 'Basic Authentication' : 'OAuth 1.0a',
baseUrl: this.config.GRAVITY_FORMS_BASE_URL,
secure: this.config.GRAVITY_FORMS_BASE_URL.startsWith('https://'),
recommended: this.authHandler instanceof BasicAuthHandler
};
}
}
/**
* Validate REST API availability and capabilities
* Ensures Gravity Forms REST API v2 is properly configured
*/
export async function validateRestApiAccess(httpClient, authManager) {
try {
// Test basic connectivity
const connectionResult = await authManager.testConnection(httpClient);
if (!connectionResult.success) {
return {
available: false,
error: 'Authentication failed',
details: connectionResult
};
}
// Test specific endpoints to verify full API access
const endpoints = [
{ path: '/forms', name: 'Forms' },
{ path: '/entries', name: 'Entries' },
{ path: '/feeds', name: 'Feeds' }
];
// Get baseURL from httpClient for OAuth signature generation
const baseURL = httpClient?.defaults?.baseURL;
if (!baseURL) {
throw new Error('httpClient baseURL is not configured');
}
const results = [];
for (const endpoint of endpoints) {
try {
// Generate proper OAuth headers with full URL for signature
const fullUrl = `${baseURL}${endpoint.path}`;
const headers = authManager.getAuthHeaders('GET', fullUrl, { per_page: 1 });
await httpClient.get(endpoint.path, {
headers,
params: { per_page: 1 }
});
results.push({ ...endpoint, available: true });
} catch (error) {
results.push({
...endpoint,
available: false,
error: error.response?.status || 'Unknown error'
});
}
}
const availableEndpoints = results.filter(r => r.available).length;
const totalEndpoints = results.length;
return {
available: availableEndpoints > 0,
authMethod: authManager.getAuthInfo().method,
endpoints: results,
coverage: `${availableEndpoints}/${totalEndpoints}`,
fullAccess: availableEndpoints === totalEndpoints,
message: availableEndpoints === totalEndpoints
? 'Full REST API access confirmed'
: `Partial access: ${availableEndpoints}/${totalEndpoints} endpoints available`
};
} catch (error) {
return {
available: false,
error: 'REST API validation failed',
details: error.message
};
}
}
export default AuthManager;