tryaii-mcp-server
Version:
TryAII MCP Server - 15+ AI models with comparison, cost tracking, and collective intelligence
81 lines • 2.25 kB
JavaScript
import crypto from 'crypto';
import bcrypt from 'bcryptjs';
import { v4 as uuidv4 } from 'uuid';
// API Key format: tai_ + 32-character random string
export const API_KEY_PREFIX = 'tai_';
export const API_KEY_LENGTH = 32;
export const HASH_ROUNDS = 12;
/**
* Generate a secure API key with proper format
* Format: tai_1234567890abcdef1234567890abcdef
*/
export function generateApiKey() {
// Generate unique key ID
const keyId = uuidv4();
// Generate secure random string
const randomBytes = crypto.randomBytes(16);
const randomString = randomBytes.toString('hex');
// Create full API key
const apiKey = `${API_KEY_PREFIX}${randomString}`;
// Create hash for storage
const keyHash = bcrypt.hashSync(apiKey, HASH_ROUNDS);
// Create prefix for display (first 8 characters)
const keyPrefix = apiKey.substring(0, 8);
return {
keyId,
apiKey,
keyHash,
keyPrefix
};
}
/**
* Validate API key format
*/
export function isValidApiKeyFormat(apiKey) {
if (!apiKey || typeof apiKey !== 'string') {
return false;
}
// Check prefix and length
if (!apiKey.startsWith(API_KEY_PREFIX)) {
return false;
}
// Check total length
if (apiKey.length !== API_KEY_PREFIX.length + API_KEY_LENGTH) {
return false;
}
// Check if the remaining part is valid hex
const keyPart = apiKey.substring(API_KEY_PREFIX.length);
const hexRegex = /^[a-f0-9]+$/i;
return hexRegex.test(keyPart);
}
/**
* Verify API key against stored hash
*/
export function verifyApiKey(apiKey, hash) {
try {
return bcrypt.compareSync(apiKey, hash);
}
catch (error) {
console.error('Error verifying API key:', error);
return false;
}
}
/**
* Extract key ID from API key for rate limiting
*/
export function extractKeyPrefix(apiKey) {
if (!isValidApiKeyFormat(apiKey)) {
return '';
}
return apiKey.substring(0, 8);
}
/**
* Sanitize API key for logging (show only prefix)
*/
export function sanitizeApiKeyForLog(apiKey) {
if (!apiKey || apiKey.length < 8) {
return '[INVALID_KEY]';
}
return `${apiKey.substring(0, 8)}...`;
}
//# sourceMappingURL=apiKeyUtils.js.map