Repository navigation
Expand file tree
/
Copy pathauth.ts
More file actions
446 lines (380 loc) · 11.3 KB
/
Copy pathauth.ts
File metadata and controls
446 lines (380 loc) · 11.3 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/**
* Authentication and authorization for MCP
*/
import type { MCPAuthConfig, MCPSession } from '../utils/types.js';
import type { ILogger } from '../core/logger.js';
import type { MCPError } from '../utils/errors.js';
import { createHash, timingSafeEqual } from 'node:crypto';
export interface IAuthManager {
authenticate(credentials: unknown): Promise<AuthResult>;
authorize(session: MCPSession, permission: string): boolean;
validateToken(token: string): Promise<TokenValidation>;
generateToken(userId: string, permissions: string[]): Promise<string>;
revokeToken(token: string): Promise<void>;
}
export interface AuthResult {
success: boolean;
user?: string;
permissions?: string[];
token?: string;
error?: string;
}
export interface TokenValidation {
valid: boolean;
user?: string;
permissions?: string[];
expiresAt?: Date;
error?: string;
}
/**
* Authentication manager implementation
*/
export class AuthManager implements IAuthManager {
private revokedTokens = new Set<string>();
private tokenStore = new Map<
string,
{
user: string;
permissions: string[];
createdAt: Date;
expiresAt: Date;
}
>();
constructor(
private config: MCPAuthConfig,
private logger: ILogger,
) {
// Start token cleanup timer
if (config.enabled) {
setInterval(() => {
this.cleanupExpiredTokens();
}, 300000); // Clean up every 5 minutes
}
}
async authenticate(credentials: unknown): Promise<AuthResult> {
if (!this.config.enabled) {
return {
success: true,
user: 'anonymous',
permissions: ['*'],
};
}
this.logger.debug('Authenticating credentials', {
method: this.config.method,
hasCredentials: !!credentials,
});
try {
switch (this.config.method) {
case 'token':
return await this.authenticateToken(credentials);
case 'basic':
return await this.authenticateBasic(credentials);
case 'oauth':
return await this.authenticateOAuth(credentials);
default:
return {
success: false,
error: `Unsupported authentication method: ${this.config.method}`,
};
}
} catch (error) {
this.logger.error('Authentication error', error);
return {
success: false,
error:
error instanceof Error
? error instanceof Error
? error.message
: String(error)
: 'Authentication failed',
};
}
}
authorize(session: MCPSession, permission: string): boolean {
if (!this.config.enabled || !session.authenticated) {
return !this.config.enabled; // If auth disabled, allow all
}
const permissions = session.authData?.permissions || [];
// Check for wildcard permission
if (permissions.includes('*')) {
return true;
}
// Check for exact permission match
if (permissions.includes(permission)) {
return true;
}
// Check for prefix-based permissions (e.g., "tools.*" matches "tools.list")
for (const perm of permissions) {
if (perm.endsWith('*') && permission.startsWith(perm.slice(0, -1))) {
return true;
}
}
this.logger.warn('Authorization denied', {
sessionId: session.id,
user: session.authData?.user,
permission,
userPermissions: permissions,
});
return false;
}
async validateToken(token: string): Promise<TokenValidation> {
if (this.revokedTokens.has(token)) {
return {
valid: false,
error: 'Token has been revoked',
};
}
const tokenData = this.tokenStore.get(token);
if (!tokenData) {
return {
valid: false,
error: 'Invalid token',
};
}
if (tokenData.expiresAt < new Date()) {
this.tokenStore.delete(token);
return {
valid: false,
error: 'Token has expired',
};
}
return {
valid: true,
user: tokenData.user,
permissions: tokenData.permissions,
expiresAt: tokenData.expiresAt,
};
}
async generateToken(userId: string, permissions: string[]): Promise<string> {
const token = this.createSecureToken();
const now = new Date();
const expiresAt = new Date(now.getTime() + (this.config.sessionTimeout || 3600000));
this.tokenStore.set(token, {
user: userId,
permissions,
createdAt: now,
expiresAt,
});
this.logger.info('Token generated', {
userId,
permissions,
expiresAt,
});
return token;
}
async revokeToken(token: string): Promise<void> {
this.revokedTokens.add(token);
this.tokenStore.delete(token);
this.logger.info('Token revoked', { token: token.substring(0, 8) + '...' });
}
private async authenticateToken(credentials: unknown): Promise<AuthResult> {
const token = this.extractToken(credentials);
if (!token) {
return {
success: false,
error: 'Token not provided',
};
}
// Check if it's a stored token (generated by us)
const validation = await this.validateToken(token);
if (validation.valid) {
return {
success: true,
user: validation.user!,
permissions: validation.permissions!,
token,
};
}
// Check against configured static tokens
if (this.config.tokens && this.config.tokens.length > 0) {
const isValid = this.config.tokens.some((validToken) => {
return this.timingSafeEqual(token, validToken);
});
if (isValid) {
return {
success: true,
user: 'token-user',
permissions: ['*'], // Static tokens get all permissions
token,
};
}
}
return {
success: false,
error: 'Invalid token',
};
}
private async authenticateBasic(credentials: unknown): Promise<AuthResult> {
const { username, password } = this.extractBasicAuth(credentials);
if (!username || !password) {
return {
success: false,
error: 'Username and password required',
};
}
if (!this.config.users || this.config.users.length === 0) {
return {
success: false,
error: 'No users configured',
};
}
const user = this.config.users.find((u) => u.username === username);
if (!user) {
return {
success: false,
error: 'Invalid username or password',
};
}
// Verify password
const isValidPassword = this.verifyPassword(password, user.password);
if (!isValidPassword) {
return {
success: false,
error: 'Invalid username or password',
};
}
// Generate a session token
const token = await this.generateToken(username, user.permissions);
return {
success: true,
user: username,
permissions: user.permissions,
token,
};
}
private async authenticateOAuth(credentials: unknown): Promise<AuthResult> {
// TODO: Implement OAuth authentication
// This would typically involve:
// 1. Validating JWT tokens
// 2. Checking token expiration
// 3. Extracting user info and permissions from token claims
this.logger.warn('OAuth authentication not yet implemented');
return {
success: false,
error: 'OAuth authentication not implemented',
};
}
private extractToken(credentials: unknown): string | null {
if (typeof credentials === 'string') {
return credentials;
}
if (typeof credentials === 'object' && credentials !== null) {
const creds = credentials as Record<string, unknown>;
if (typeof creds.token === 'string') {
return creds.token;
}
if (typeof creds.authorization === 'string') {
const match = creds.authorization.match(/^Bearer\s+(.+)$/i);
return match ? match[1] : null;
}
}
return null;
}
private extractBasicAuth(credentials: unknown): { username?: string; password?: string } {
if (typeof credentials === 'object' && credentials !== null) {
const creds = credentials as Record<string, unknown>;
if (typeof creds.username === 'string' && typeof creds.password === 'string') {
return {
username: creds.username,
password: creds.password,
};
}
if (typeof creds.authorization === 'string') {
const match = creds.authorization.match(/^Basic\s+(.+)$/i);
if (match) {
try {
const decoded = atob(match[1]);
const colonIndex = decoded.indexOf(':');
if (colonIndex >= 0) {
return {
username: decoded.substring(0, colonIndex),
password: decoded.substring(colonIndex + 1),
};
}
} catch {
// Invalid base64
}
}
}
}
return {};
}
private verifyPassword(providedPassword: string, storedPassword: string): boolean {
// For now, using simple hash comparison
// In production, use proper password hashing like bcrypt
const hashedProvided = this.hashPassword(providedPassword);
const hashedStored = this.hashPassword(storedPassword);
return this.timingSafeEqual(hashedProvided, hashedStored);
}
private hashPassword(password: string): string {
return createHash('sha256').update(password).digest('hex');
}
private timingSafeEqual(a: string, b: string): boolean {
const encoder = new TextEncoder();
const bufferA = encoder.encode(a);
const bufferB = encoder.encode(b);
if (bufferA.length !== bufferB.length) {
return false;
}
return timingSafeEqual(bufferA, bufferB);
}
private createSecureToken(): string {
// Generate a secure random token
const timestamp = Date.now().toString(36);
const random1 = Math.random().toString(36).substring(2, 15);
const random2 = Math.random().toString(36).substring(2, 15);
const hash = createHash('sha256')
.update(`${timestamp}${random1}${random2}`)
.digest('hex')
.substring(0, 32);
return `mcp_${timestamp}_${hash}`;
}
private cleanupExpiredTokens(): void {
const now = new Date();
let cleaned = 0;
for (const [token, data] of this.tokenStore.entries()) {
if (data.expiresAt < now) {
this.tokenStore.delete(token);
cleaned++;
}
}
if (cleaned > 0) {
this.logger.debug('Cleaned up expired tokens', { count: cleaned });
}
}
}
/**
* Permission constants for common operations
*/
export const Permissions = {
// System operations
SYSTEM_INFO: 'system.info',
SYSTEM_HEALTH: 'system.health',
SYSTEM_METRICS: 'system.metrics',
// Tool operations
TOOLS_LIST: 'tools.list',
TOOLS_INVOKE: 'tools.invoke',
TOOLS_DESCRIBE: 'tools.describe',
// Agent operations
AGENTS_LIST: 'agents.list',
AGENTS_SPAWN: 'agents.spawn',
AGENTS_TERMINATE: 'agents.terminate',
AGENTS_INFO: 'agents.info',
// Task operations
TASKS_LIST: 'tasks.list',
TASKS_CREATE: 'tasks.create',
TASKS_CANCEL: 'tasks.cancel',
TASKS_STATUS: 'tasks.status',
// Memory operations
MEMORY_READ: 'memory.read',
MEMORY_WRITE: 'memory.write',
MEMORY_QUERY: 'memory.query',
MEMORY_DELETE: 'memory.delete',
// Administrative operations
ADMIN_CONFIG: 'admin.config',
ADMIN_LOGS: 'admin.logs',
ADMIN_SESSIONS: 'admin.sessions',
// Wildcard permission
ALL: '*',
} as const;
export type Permission = (typeof Permissions)[keyof typeof Permissions];