tryaii-mcp-server
Version:
TryAII MCP Server - 15+ AI models with comparison, cost tracking, and collective intelligence
69 lines • 2.68 kB
JavaScript
import { UserApiKey } from '../models/UserApiKey.js';
import { verifyApiKey, isValidApiKeyFormat, sanitizeApiKeyForLog } from '../utils/apiKeyUtils.js';
import { logger } from '../utils/logger.js';
export class UserApiKeyService {
/**
* Authenticate API key and return user info
*/
async authenticateApiKey(apiKey) {
if (!isValidApiKeyFormat(apiKey)) {
logger.warn('Invalid API key format attempted', { keyPrefix: sanitizeApiKeyForLog(apiKey) });
return null;
}
try {
// Find all active API keys and check against hashes
const activeKeys = await UserApiKey.find({
isActive: true,
$or: [
{ expiresAt: { $exists: false } },
{ expiresAt: { $gt: new Date() } }
]
});
for (const keyDoc of activeKeys) {
if (verifyApiKey(apiKey, keyDoc.keyHash)) {
// Update last used timestamp
await UserApiKey.findByIdAndUpdate(keyDoc._id, { lastUsed: new Date() });
logger.debug('API key authenticated successfully', { keyId: keyDoc.keyId, userId: keyDoc.userId });
return {
keyId: keyDoc.keyId,
userId: keyDoc.userId,
permissions: keyDoc.permissions,
keyDocument: keyDoc
};
}
}
logger.warn('API key authentication failed', { keyPrefix: sanitizeApiKeyForLog(apiKey) });
return null;
}
catch (error) {
logger.error('Error authenticating API key', { error, keyPrefix: sanitizeApiKeyForLog(apiKey) });
return null;
}
}
/**
* Record API key usage
*/
async recordUsage(keyId, cost) {
try {
await UserApiKey.findOneAndUpdate({ keyId, isActive: true }, {
$inc: {
'usageStats.totalRequests': 1,
'usageStats.totalCost': cost
}
});
logger.debug('Usage recorded', { keyId, cost });
}
catch (error) {
logger.error('Error recording API key usage', { error, keyId, cost });
}
}
/**
* Check if user has permission for specific action
*/
hasPermission(authenticatedKey, requiredPermission) {
return authenticatedKey.permissions.includes(requiredPermission);
}
}
// Create a singleton instance
export const userApiKeyService = new UserApiKeyService();
//# sourceMappingURL=userApiKeyService.js.map