UNPKG

onerios-mcp-server

Version:

OneriosMCP server providing memory, backlog management, file operations, and utility functions for enhanced AI assistant capabilities

234 lines (233 loc) 9.67 kB
"use strict"; /** * Enhanced GitHub Token Security Manager * * Provides secure token storage, rotation, and validation capabilities * for the GitHub integration development environment. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.GitHubTokenSecurityManager = void 0; const crypto = __importStar(require("crypto")); const fs = __importStar(require("fs/promises")); const path = __importStar(require("path")); /** * Enhanced Token Security Manager for Development Environment */ class GitHubTokenSecurityManager { /** * Securely store a GitHub token with encryption */ static async storeToken(token, metadata) { try { // Ensure token directory exists await fs.mkdir(this.TOKEN_DIR, { recursive: true }); // Generate unique token ID const tokenId = crypto.randomUUID(); // Create encryption components const salt = crypto.randomBytes(32); const iv = crypto.randomBytes(16); const key = crypto.pbkdf2Sync(process.env.MCP_TOKEN_KEY || 'dev-key', salt, 100000, 32, 'sha512'); // Encrypt token const cipher = crypto.createCipheriv(this.ALGORITHM, key, iv); cipher.setAAD(Buffer.from(tokenId)); let encrypted = cipher.update(token, 'utf8', 'hex'); encrypted += cipher.final('hex'); const authTag = cipher.getAuthTag(); // Create storage object const storage = { encrypted: encrypted + ':' + authTag.toString('hex'), metadata: { ...metadata, id: tokenId, createdAt: new Date().toISOString() }, salt: salt.toString('hex'), iv: iv.toString('hex') }; // Write to secure file const filePath = path.join(this.TOKEN_DIR, `${tokenId}.json`); await fs.writeFile(filePath, JSON.stringify(storage, null, 2), { mode: 0o600 }); console.log(`🔐 Token stored securely with ID: ${tokenId}`); return tokenId; } catch (error) { throw new Error(`Failed to store token securely: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Retrieve and decrypt a stored token */ static async retrieveToken(tokenId) { try { const filePath = path.join(this.TOKEN_DIR, `${tokenId}.json`); const data = await fs.readFile(filePath, 'utf8'); const storage = JSON.parse(data); // Check token age const createdAt = new Date(storage.metadata.createdAt); const ageInDays = (Date.now() - createdAt.getTime()) / (1000 * 60 * 60 * 24); if (ageInDays > this.MAX_TOKEN_AGE_DAYS) { console.warn(`⚠️ Token ${tokenId} is ${Math.round(ageInDays)} days old (max: ${this.MAX_TOKEN_AGE_DAYS})`); } // Decrypt token const salt = Buffer.from(storage.salt, 'hex'); const iv = Buffer.from(storage.iv, 'hex'); const key = crypto.pbkdf2Sync(process.env.MCP_TOKEN_KEY || 'dev-key', salt, 100000, 32, 'sha512'); const [encryptedData, authTagHex] = storage.encrypted.split(':'); const authTag = Buffer.from(authTagHex, 'hex'); const decipher = crypto.createDecipheriv(this.ALGORITHM, key, iv); decipher.setAAD(Buffer.from(tokenId)); decipher.setAuthTag(authTag); let decrypted = decipher.update(encryptedData, 'hex', 'utf8'); decrypted += decipher.final('utf8'); // Update last used timestamp storage.metadata.lastUsed = new Date().toISOString(); await fs.writeFile(filePath, JSON.stringify(storage, null, 2), { mode: 0o600 }); return { token: decrypted, metadata: storage.metadata }; } catch (error) { throw new Error(`Failed to retrieve token: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * List all stored tokens (metadata only) */ static async listTokens() { try { const files = await fs.readdir(this.TOKEN_DIR); const tokenFiles = files.filter(f => f.endsWith('.json')); const tokens = []; for (const file of tokenFiles) { try { const data = await fs.readFile(path.join(this.TOKEN_DIR, file), 'utf8'); const storage = JSON.parse(data); tokens.push(storage.metadata); } catch (error) { console.warn(`⚠️ Could not read token file ${file}: ${error}`); } } return tokens.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()); } catch (error) { if (error.code === 'ENOENT') { return []; // No tokens directory exists yet } throw error; } } /** * Delete a stored token */ static async deleteToken(tokenId) { try { const filePath = path.join(this.TOKEN_DIR, `${tokenId}.json`); await fs.unlink(filePath); console.log(`🗑️ Token ${tokenId} deleted securely`); } catch (error) { throw new Error(`Failed to delete token: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Rotate (update) an existing token */ static async rotateToken(tokenId, newToken, newMetadata) { try { // Get existing metadata const { metadata: oldMetadata } = await this.retrieveToken(tokenId); // Delete old token await this.deleteToken(tokenId); // Store new token with same ID but updated metadata const updatedMetadata = { ...oldMetadata, ...newMetadata, id: tokenId, // Preserve ID createdAt: new Date().toISOString() // Update creation time }; // Store with new token data await this.storeToken(newToken, updatedMetadata); console.log(`🔄 Token ${tokenId} rotated successfully`); } catch (error) { throw new Error(`Failed to rotate token: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Validate token security and recommend actions */ static async auditTokenSecurity() { const tokens = await this.listTokens(); const now = Date.now(); let expiredTokens = 0; let oldTokens = 0; const recommendations = []; for (const token of tokens) { const createdAt = new Date(token.createdAt).getTime(); const ageInDays = (now - createdAt) / (1000 * 60 * 60 * 24); if (token.expiresAt && new Date(token.expiresAt).getTime() < now) { expiredTokens++; } if (ageInDays > this.MAX_TOKEN_AGE_DAYS) { oldTokens++; } } if (expiredTokens > 0) { recommendations.push(`${expiredTokens} token(s) have expired and should be deleted`); } if (oldTokens > 0) { recommendations.push(`${oldTokens} token(s) are over ${this.MAX_TOKEN_AGE_DAYS} days old - consider rotation`); } if (tokens.length === 0) { recommendations.push('No tokens stored - add a GitHub token for API access'); } if (tokens.length > 5) { recommendations.push(`${tokens.length} tokens stored - consider cleanup of unused tokens`); } return { totalTokens: tokens.length, expiredTokens, oldTokens, recommendations }; } } exports.GitHubTokenSecurityManager = GitHubTokenSecurityManager; GitHubTokenSecurityManager.ALGORITHM = 'aes-256-gcm'; GitHubTokenSecurityManager.TOKEN_DIR = path.join(process.cwd(), '.github-tokens'); GitHubTokenSecurityManager.MAX_TOKEN_AGE_DAYS = 90; // 3 months