@codai/romai-mcp
Version:
ROMAI Ultimate MCP Server - All-in-One Enterprise Solution with 26+ Integrated Tools
1,089 lines (1,086 loc) • 33.3 kB
JavaScript
import { randomUUID, createHash } from 'crypto';
// src/auth/authentication-manager.ts
var EnterpriseLogger = class _EnterpriseLogger {
static instance;
metrics = [];
auditTrail = [];
constructor() {
}
static getInstance() {
if (!_EnterpriseLogger.instance) {
_EnterpriseLogger.instance = new _EnterpriseLogger();
}
return _EnterpriseLogger.instance;
}
/**
* Create a new request context with correlation ID
*/
createRequestContext(method, userId, organizationId) {
return {
requestId: randomUUID(),
userId,
organizationId,
method,
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
source: "mcp-server",
version: "0.2.0"
};
}
/**
* Log MCP request with structured data
*/
logRequest(context, params) {
const logEntry = {
level: "info",
...context,
type: "mcp_request",
params: this.sanitizeParams(params),
message: `MCP Request: ${context.method}`
};
console.log(JSON.stringify(logEntry));
this.recordAuditEvent({
eventId: randomUUID(),
eventType: "request",
severity: "info",
details: { params },
context
});
}
/**
* Log MCP response with performance metrics
*/
logResponse(context, result, duration) {
const logEntry = {
level: "info",
...context,
type: "mcp_response",
result: this.sanitizeResult(result),
duration_ms: duration,
message: `MCP Response: ${context.method} (${duration}ms)`
};
console.log(JSON.stringify(logEntry));
this.recordMetric({
name: "mcp_request_duration",
value: duration,
unit: "ms",
labels: {
method: context.method,
userId: context.userId || "anonymous",
organizationId: context.organizationId || "default"
},
timestamp: (/* @__PURE__ */ new Date()).toISOString()
});
this.recordAuditEvent({
eventId: randomUUID(),
eventType: "response",
severity: "info",
details: { duration, success: true },
context
});
}
/**
* Log error with full context and stack trace
*/
logError(context, error, details) {
const logEntry = {
level: "error",
...context,
type: "mcp_error",
error: {
name: error.name,
message: error.message,
stack: error.stack
},
details: details || {},
message: `MCP Error: ${context.method} - ${error.message}`
};
console.error(JSON.stringify(logEntry));
this.recordMetric({
name: "mcp_request_errors",
value: 1,
unit: "count",
labels: {
method: context.method,
errorType: error.name,
userId: context.userId || "anonymous",
organizationId: context.organizationId || "default"
},
timestamp: (/* @__PURE__ */ new Date()).toISOString()
});
this.recordAuditEvent({
eventId: randomUUID(),
eventType: "error",
severity: "error",
details: { error: error.message, stack: error.stack, ...details },
context
});
}
/**
* Record performance metric for analytics
*/
recordMetric(metric) {
this.metrics.push(metric);
if (this.metrics.length > 1e3) {
this.metrics = this.metrics.slice(-1e3);
}
}
/**
* Record audit event for compliance
*/
recordAuditEvent(event) {
this.auditTrail.push(event);
if (this.auditTrail.length > 500) {
this.auditTrail = this.auditTrail.slice(-500);
}
}
/**
* Get performance analytics
*/
getAnalytics(timeWindow = 36e5) {
const cutoff = new Date(Date.now() - timeWindow);
const recentMetrics = this.metrics.filter((m) => new Date(m.timestamp) > cutoff);
const requestMetrics = recentMetrics.filter((m) => m.name === "mcp_request_duration");
const errorMetrics = recentMetrics.filter((m) => m.name === "mcp_request_errors");
const methodCounts = requestMetrics.reduce((acc, metric) => {
const method = metric.labels.method;
acc[method] = (acc[method] || 0) + 1;
return acc;
}, {});
const topMethods = Object.entries(methodCounts).map(([method, count]) => ({ method, count })).sort((a, b) => b.count - a.count).slice(0, 5);
return {
requestCount: requestMetrics.length,
averageResponseTime: requestMetrics.length > 0 ? requestMetrics.reduce((sum, m) => sum + m.value, 0) / requestMetrics.length : 0,
errorRate: requestMetrics.length > 0 ? errorMetrics.length / requestMetrics.length * 100 : 0,
topMethods,
performanceMetrics: recentMetrics
};
}
/**
* Get audit trail for compliance
*/
getAuditTrail(timeWindow = 36e5) {
const cutoff = new Date(Date.now() - timeWindow);
return this.auditTrail.filter((event) => new Date(event.context.timestamp) > cutoff);
}
/**
* Generate compliance report
*/
generateComplianceReport() {
const last24h = 24 * 60 * 60 * 1e3;
const recentEvents = this.getAuditTrail(last24h);
const totalRequests = recentEvents.filter((e) => e.eventType === "request").length;
const authenticatedRequests = recentEvents.filter(
(e) => e.eventType === "request" && e.context.userId
).length;
const errorEvents = recentEvents.filter((e) => e.eventType === "error").length;
const criticalEvents = recentEvents.filter((e) => e.severity === "critical").length;
return {
totalRequests,
authenticatedRequests,
errorEvents,
criticalEvents,
dataIntegrity: true,
// Enhanced validation in production
auditCoverage: totalRequests > 0 ? recentEvents.length / totalRequests * 100 : 100
};
}
/**
* Sanitize sensitive data from parameters
*/
sanitizeParams(params) {
if (!params || typeof params !== "object") return params;
const sanitized = { ...params };
const sensitiveFields = ["password", "token", "key", "secret", "apiKey"];
for (const field of sensitiveFields) {
if (sanitized[field]) {
sanitized[field] = "[REDACTED]";
}
}
return sanitized;
}
/**
* Sanitize sensitive data from results
*/
sanitizeResult(result) {
if (!result || typeof result !== "object") return result;
const resultStr = JSON.stringify(result);
if (resultStr.length > 1e3) {
return {
_truncated: true,
_size: resultStr.length,
preview: resultStr.substring(0, 200) + "..."
};
}
return result;
}
};
var enterpriseLogger = EnterpriseLogger.getInstance();
// src/auth/authentication-manager.ts
var AuthenticationManager = class _AuthenticationManager {
static instance;
users = /* @__PURE__ */ new Map();
organizations = /* @__PURE__ */ new Map();
apiKeys = /* @__PURE__ */ new Map();
sessions = /* @__PURE__ */ new Map();
roles = /* @__PURE__ */ new Map();
permissions = /* @__PURE__ */ new Map();
constructor() {
this.initializeSystemRoles();
this.initializeDefaultOrganization();
}
static getInstance() {
if (!_AuthenticationManager.instance) {
_AuthenticationManager.instance = new _AuthenticationManager();
}
return _AuthenticationManager.instance;
}
/**
* Initialize system roles and permissions
*/
initializeSystemRoles() {
const permissions = [
{ id: "read_intelligence", name: "Read Intelligence", description: "Access AI intelligence tools", resource: "intelligence", action: "read" },
{ id: "write_intelligence", name: "Write Intelligence", description: "Use AI intelligence tools", resource: "intelligence", action: "write" },
{ id: "read_resources", name: "Read Resources", description: "Access Romanian business resources", resource: "resources", action: "read" },
{ id: "read_prompts", name: "Read Prompts", description: "Access prompt templates", resource: "prompts", action: "read" },
{ id: "manage_users", name: "Manage Users", description: "Create and manage organization users", resource: "users", action: "manage" },
{ id: "manage_api_keys", name: "Manage API Keys", description: "Create and manage API keys", resource: "api_keys", action: "manage" },
{ id: "view_analytics", name: "View Analytics", description: "Access usage analytics", resource: "analytics", action: "read" },
{ id: "manage_organization", name: "Manage Organization", description: "Configure organization settings", resource: "organization", action: "manage" }
];
permissions.forEach((permission) => {
this.permissions.set(permission.id, permission);
});
const roles = [
{
id: "user",
name: "User",
description: "Basic user with access to AI tools",
permissions: [
this.permissions.get("read_intelligence"),
this.permissions.get("write_intelligence"),
this.permissions.get("read_resources"),
this.permissions.get("read_prompts")
]
},
{
id: "admin",
name: "Administrator",
description: "Organization administrator with full access",
permissions: Array.from(this.permissions.values())
},
{
id: "analyst",
name: "Analyst",
description: "Business analyst with intelligence and analytics access",
permissions: [
this.permissions.get("read_intelligence"),
this.permissions.get("write_intelligence"),
this.permissions.get("read_resources"),
this.permissions.get("read_prompts"),
this.permissions.get("view_analytics")
]
},
{
id: "readonly",
name: "Read Only",
description: "Read-only access to resources and prompts",
permissions: [
this.permissions.get("read_resources"),
this.permissions.get("read_prompts"),
this.permissions.get("view_analytics")
]
}
];
roles.forEach((role) => {
this.roles.set(role.id, role);
});
}
/**
* Initialize default organization for single-tenant mode
*/
initializeDefaultOrganization() {
const defaultOrg = {
id: "default",
name: "Default Organization",
domain: "default.romai.local",
plan: "enterprise",
status: "active",
settings: {
maxUsers: 1e3,
maxApiCalls: 1e6,
features: ["intelligence", "resources", "prompts", "analytics"],
customization: {}
},
apiKeys: [],
createdAt: (/* @__PURE__ */ new Date()).toISOString()
};
this.organizations.set(defaultOrg.id, defaultOrg);
}
/**
* Create a new organization
*/
createOrganization(data) {
const organizationId = randomUUID();
const userId = randomUUID();
const apiKeyId = randomUUID();
const organization = {
id: organizationId,
name: data.name,
domain: data.domain,
plan: data.plan,
status: "active",
settings: this.getDefaultSettingsForPlan(data.plan),
apiKeys: [],
createdAt: (/* @__PURE__ */ new Date()).toISOString()
};
const user = {
id: userId,
email: data.adminUser.email,
name: data.adminUser.name,
organizationId,
roles: ["admin"],
status: "active",
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
preferences: {}
};
const apiKey = {
id: apiKeyId,
key: this.generateApiKey(),
name: "Default Admin Key",
organizationId,
userId,
permissions: ["*"],
// All permissions for admin
status: "active",
createdAt: (/* @__PURE__ */ new Date()).toISOString()
};
this.organizations.set(organizationId, organization);
this.users.set(userId, user);
this.apiKeys.set(apiKey.key, apiKey);
organization.apiKeys.push(apiKey);
enterpriseLogger.recordAuditEvent({
eventId: randomUUID(),
eventType: "auth",
severity: "info",
details: {
action: "organization_created",
organizationId,
adminUserId: userId,
plan: data.plan
},
context: {
requestId: randomUUID(),
userId,
organizationId,
method: "create_organization",
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
source: "mcp-server",
version: "0.2.0"
}
});
return { organization, user, apiKey };
}
/**
* Authenticate user with API key
*/
authenticateApiKey(apiKey) {
const key = this.apiKeys.get(apiKey);
if (!key) {
return { success: false, error: "Invalid API key" };
}
if (key.status !== "active") {
return { success: false, error: "API key is revoked" };
}
if (key.expiresAt && new Date(key.expiresAt) < /* @__PURE__ */ new Date()) {
return { success: false, error: "API key has expired" };
}
const user = this.users.get(key.userId);
const organization = this.organizations.get(key.organizationId);
if (!user || !organization) {
return { success: false, error: "Associated user or organization not found" };
}
if (user.status !== "active" || organization.status !== "active") {
return { success: false, error: "User or organization is not active" };
}
key.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString();
enterpriseLogger.recordAuditEvent({
eventId: randomUUID(),
eventType: "auth",
severity: "info",
details: {
action: "api_key_authentication",
userId: user.id,
organizationId: organization.id,
apiKeyId: key.id
},
context: {
requestId: randomUUID(),
userId: user.id,
organizationId: organization.id,
method: "authenticate_api_key",
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
source: "mcp-server",
version: "0.2.0"
}
});
return {
success: true,
user,
organization,
permissions: key.permissions
};
}
/**
* Create session for user
*/
createSession(userId, options = {}) {
const session = {
id: randomUUID(),
userId,
organizationId: this.users.get(userId)?.organizationId || "default",
token: this.generateSessionToken(),
expiresAt: new Date(Date.now() + (options.expiresInHours || 24) * 60 * 60 * 1e3).toISOString(),
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
lastActivityAt: (/* @__PURE__ */ new Date()).toISOString(),
ipAddress: options.ipAddress,
userAgent: options.userAgent
};
this.sessions.set(session.token, session);
enterpriseLogger.recordAuditEvent({
eventId: randomUUID(),
eventType: "auth",
severity: "info",
details: {
action: "session_created",
sessionId: session.id,
userId,
expiresAt: session.expiresAt
},
context: {
requestId: randomUUID(),
userId,
organizationId: session.organizationId,
method: "create_session",
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
source: "mcp-server",
version: "0.2.0"
}
});
return session;
}
/**
* Validate session token
*/
validateSession(token) {
const session = this.sessions.get(token);
if (!session) {
return { valid: false };
}
if (new Date(session.expiresAt) < /* @__PURE__ */ new Date()) {
this.sessions.delete(token);
return { valid: false };
}
const user = this.users.get(session.userId);
const organization = this.organizations.get(session.organizationId);
if (!user || !organization) {
return { valid: false };
}
session.lastActivityAt = (/* @__PURE__ */ new Date()).toISOString();
return {
valid: true,
session,
user,
organization
};
}
/**
* Check if user has permission
*/
hasPermission(userId, resource, action) {
const user = this.users.get(userId);
if (!user) return false;
for (const roleName of user.roles) {
const role = this.roles.get(roleName);
if (!role) continue;
for (const permission of role.permissions) {
if (permission.resource === resource && permission.action === action) {
return true;
}
if (permission.resource === "*" || permission.action === "*") {
return true;
}
}
}
return false;
}
/**
* Check usage quotas for organization
*/
checkQuota(organizationId, resource, amount = 1) {
const organization = this.organizations.get(organizationId);
if (!organization) {
return { allowed: false, remaining: 0, limit: 0, resetDate: "" };
}
const usage = organization.billingInfo?.usage || {
apiCalls: 0,
storageUsed: 0,
bandwidthUsed: 0,
lastResetDate: (/* @__PURE__ */ new Date()).toISOString(),
quotaLimits: {
apiCalls: organization.settings.maxApiCalls,
storage: organization.settings.maxStorage || 1e9,
// 1GB default
bandwidth: organization.settings.maxBandwidth || 1e10
// 10GB default
}
};
let currentUsage = 0;
let limit = 0;
switch (resource) {
case "api_calls":
currentUsage = usage.apiCalls;
limit = usage.quotaLimits.apiCalls;
break;
case "storage":
currentUsage = usage.storageUsed;
limit = usage.quotaLimits.storage;
break;
case "bandwidth":
currentUsage = usage.bandwidthUsed;
limit = usage.quotaLimits.bandwidth;
break;
default:
return { allowed: true, remaining: Infinity, limit: Infinity, resetDate: "" };
}
const remaining = Math.max(0, limit - currentUsage);
const allowed = currentUsage + amount <= limit;
return {
allowed,
remaining,
limit,
resetDate: usage.lastResetDate
};
}
/**
* Update usage metrics
*/
updateUsage(organizationId, resource, amount) {
const organization = this.organizations.get(organizationId);
if (!organization) return;
if (!organization.billingInfo) {
organization.billingInfo = {
subscriptionId: "",
nextBillingDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1e3).toISOString(),
usage: {
apiCalls: 0,
storageUsed: 0,
bandwidthUsed: 0,
lastResetDate: (/* @__PURE__ */ new Date()).toISOString(),
quotaLimits: {
apiCalls: organization.settings.maxApiCalls,
storage: organization.settings.maxStorage || 1e9,
bandwidth: organization.settings.maxBandwidth || 1e10
}
}
};
}
switch (resource) {
case "api_calls":
organization.billingInfo.usage.apiCalls += amount;
break;
case "storage":
organization.billingInfo.usage.storageUsed += amount;
break;
case "bandwidth":
organization.billingInfo.usage.bandwidthUsed += amount;
break;
}
}
/**
* Generate API key
*/
generateApiKey() {
const prefix = "romai_";
const randomBytes = randomUUID().replace(/-/g, "");
return `${prefix}${randomBytes}`;
}
/**
* Generate session token
*/
generateSessionToken() {
return createHash("sha256").update(randomUUID() + Date.now()).digest("hex");
}
/**
* Get default settings for plan
*/
getDefaultSettingsForPlan(plan) {
switch (plan) {
case "free":
return {
maxUsers: 1,
maxApiCalls: 1e3,
maxStorage: 1e8,
// 100MB
maxBandwidth: 1e9,
// 1GB
features: ["intelligence"],
customization: {}
};
case "professional":
return {
maxUsers: 10,
maxApiCalls: 5e4,
maxStorage: 5e9,
// 5GB
maxBandwidth: 5e10,
// 50GB
features: ["intelligence", "resources", "prompts"],
customization: {}
};
case "enterprise":
return {
maxUsers: 1e3,
maxApiCalls: 1e6,
maxStorage: 1e11,
// 100GB
maxBandwidth: 1e12,
// 1TB
features: ["intelligence", "resources", "prompts", "analytics"],
customization: {}
};
default:
return {
maxUsers: 1,
maxApiCalls: 100,
maxStorage: 1e7,
// 10MB
maxBandwidth: 1e8,
// 100MB
features: ["intelligence"],
customization: {}
};
}
}
/**
* Get organization statistics
*/
getOrganizationStats(organizationId) {
const organization = this.organizations.get(organizationId);
if (!organization) {
return { users: 0, activeUsers: 0, apiKeys: 0, activeSessions: 0, usage: {} };
}
const orgUsers = Array.from(this.users.values()).filter((u) => u.organizationId === organizationId);
const activeUsers = orgUsers.filter((u) => u.status === "active").length;
const apiKeys = Array.from(this.apiKeys.values()).filter((k) => k.organizationId === organizationId).length;
const activeSessions = Array.from(this.sessions.values()).filter(
(s) => s.organizationId === organizationId && new Date(s.expiresAt) > /* @__PURE__ */ new Date()
).length;
return {
users: orgUsers.length,
activeUsers,
apiKeys,
activeSessions,
usage: organization.billingInfo?.usage || {}
};
}
/**
* Cleanup expired sessions
*/
cleanupExpiredSessions() {
let cleaned = 0;
const now = /* @__PURE__ */ new Date();
for (const [token, session] of this.sessions.entries()) {
if (new Date(session.expiresAt) < now) {
this.sessions.delete(token);
cleaned++;
}
}
return cleaned;
}
};
var authManager = AuthenticationManager.getInstance();
var AuthorizationMiddleware = class _AuthorizationMiddleware {
static instance;
rateLimitStore = /* @__PURE__ */ new Map();
constructor() {
setInterval(() => this.cleanupRateLimitStore(), 6e4);
}
static getInstance() {
if (!_AuthorizationMiddleware.instance) {
_AuthorizationMiddleware.instance = new _AuthorizationMiddleware();
}
return _AuthorizationMiddleware.instance;
}
/**
* Main authorization middleware function
*/
async authorize(apiKey, method, resource, options = {}) {
const requestId = randomUUID();
const startTime = Date.now();
try {
const authResult = authManager.authenticateApiKey(apiKey);
if (!authResult.success) {
await this.logAuthEvent("authentication_failed", {
requestId,
method,
resource,
error: authResult.error,
apiKey: apiKey.substring(0, 10) + "..."
});
return {
authorized: false,
error: authResult.error || "Authentication failed",
statusCode: 401
};
}
const { user, organization, permissions } = authResult;
if (!user || !organization) {
return {
authorized: false,
error: "Invalid user or organization",
statusCode: 401
};
}
if (options.rateLimitConfig) {
const rateLimitResult = this.checkRateLimit(
organization.id,
options.rateLimitConfig
);
if (!rateLimitResult.allowed) {
await this.logAuthEvent("rate_limit_exceeded", {
requestId,
method,
resource,
organizationId: organization.id,
userId: user.id,
limit: options.rateLimitConfig.maxRequests,
window: options.rateLimitConfig.windowMs
});
return {
authorized: false,
error: "Rate limit exceeded",
statusCode: 429
};
}
}
if (options.quotaConfig?.checkApiCalls) {
const quotaResult = authManager.checkQuota(organization.id, "api_calls", 1);
if (!quotaResult.allowed) {
await this.logAuthEvent("quota_exceeded", {
requestId,
method,
resource,
organizationId: organization.id,
userId: user.id,
quotaType: "api_calls",
limit: quotaResult.limit,
current: quotaResult.limit - quotaResult.remaining
});
return {
authorized: false,
error: "API call quota exceeded",
statusCode: 402
};
}
}
if (options.requiredPermissions && options.requiredPermissions.length > 0) {
const hasAllPermissions = this.checkPermissions(
user,
permissions || [],
options.requiredPermissions
);
if (!hasAllPermissions) {
await this.logAuthEvent("permission_denied", {
requestId,
method,
resource,
organizationId: organization.id,
userId: user.id,
requiredPermissions: options.requiredPermissions,
userPermissions: permissions || []
});
return {
authorized: false,
error: "Insufficient permissions",
statusCode: 403
};
}
}
authManager.updateUsage(organization.id, "api_calls", 1);
const authContext = {
user,
organization,
permissions: permissions || [],
requestId,
startTime
};
await this.logAuthEvent("authorization_success", {
requestId,
method,
resource,
organizationId: organization.id,
userId: user.id,
permissions: permissions || []
});
return {
authorized: true,
context: authContext
};
} catch (error) {
await this.logAuthEvent("authorization_error", {
requestId,
method,
resource,
error: error instanceof Error ? error.message : "Unknown error"
});
return {
authorized: false,
error: "Internal authorization error",
statusCode: 500
};
}
}
/**
* Check rate limits for organization
*/
checkRateLimit(organizationId, config) {
const key = `ratelimit:${organizationId}`;
const now = Date.now();
const resetTime = now + config.windowMs;
let rateLimitInfo = this.rateLimitStore.get(key);
if (!rateLimitInfo || now >= rateLimitInfo.resetTime) {
rateLimitInfo = {
count: 0,
resetTime
};
this.rateLimitStore.set(key, rateLimitInfo);
}
if (rateLimitInfo.count >= config.maxRequests) {
return {
allowed: false,
remaining: 0,
resetTime: rateLimitInfo.resetTime
};
}
rateLimitInfo.count++;
return {
allowed: true,
remaining: config.maxRequests - rateLimitInfo.count,
resetTime: rateLimitInfo.resetTime
};
}
/**
* Check if user has required permissions
*/
checkPermissions(user, userPermissions, requiredPermissions) {
if (userPermissions.includes("*")) {
return true;
}
for (const required of requiredPermissions) {
const hasPermission = userPermissions.includes(required) || authManager.hasPermission(user.id, required.split(":")[0] || "", required.split(":")[1] || "");
if (!hasPermission) {
return false;
}
}
return true;
}
/**
* Complete request authorization cycle
*/
async completeRequest(context, success, responseSize, error) {
const duration = Date.now() - context.startTime;
try {
if (responseSize) {
authManager.updateUsage(context.organization.id, "bandwidth", responseSize);
}
await this.logAuthEvent("request_completed", {
requestId: context.requestId,
organizationId: context.organization.id,
userId: context.user.id,
duration,
success,
responseSize,
error
});
} catch (error2) {
const errorMessage = error2 instanceof Error ? error2.message : String(error2);
enterpriseLogger.recordAuditEvent({
eventId: randomUUID(),
eventType: "error",
severity: "error",
details: {
action: "complete_request_error",
error: errorMessage,
requestId: context.requestId,
organizationId: context.organization.id,
userId: context.user.id
},
context: {
requestId: context.requestId,
organizationId: context.organization.id,
userId: context.user.id,
method: "complete_request",
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
source: "mcp-server",
version: "0.2.0"
}
});
}
}
/**
* Get rate limit status for organization
*/
getRateLimitStatus(organizationId) {
const key = `ratelimit:${organizationId}`;
const rateLimitInfo = this.rateLimitStore.get(key);
if (!rateLimitInfo || Date.now() >= rateLimitInfo.resetTime) {
return { current: 0, resetTime: 0 };
}
return {
current: rateLimitInfo.count,
resetTime: rateLimitInfo.resetTime
};
}
/**
* Get organization usage statistics
*/
getUsageStats(organizationId) {
const stats = authManager.getOrganizationStats(organizationId);
const rateLimitStatus = this.getRateLimitStatus(organizationId);
return {
apiCalls: stats.usage.apiCalls || 0,
storageUsed: stats.usage.storageUsed || 0,
bandwidthUsed: stats.usage.bandwidthUsed || 0,
quotaLimits: stats.usage.quotaLimits || {
apiCalls: 0,
storage: 0,
bandwidth: 0
},
rateLimitStatus
};
}
/**
* Reset usage for organization (for testing or billing cycle)
*/
resetUsage(organizationId) {
const organization = authManager["organizations"].get(organizationId);
if (organization?.billingInfo) {
organization.billingInfo.usage.apiCalls = 0;
organization.billingInfo.usage.storageUsed = 0;
organization.billingInfo.usage.bandwidthUsed = 0;
organization.billingInfo.usage.lastResetDate = (/* @__PURE__ */ new Date()).toISOString();
}
const key = `ratelimit:${organizationId}`;
this.rateLimitStore.delete(key);
enterpriseLogger.recordAuditEvent({
eventId: randomUUID(),
eventType: "auth",
severity: "info",
details: {
action: "usage_reset",
organizationId,
timestamp: (/* @__PURE__ */ new Date()).toISOString()
},
context: {
requestId: randomUUID(),
organizationId,
method: "reset_usage",
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
source: "mcp-server",
version: "0.2.0"
}
});
}
/**
* Log authentication/authorization events
*/
async logAuthEvent(eventType, details) {
enterpriseLogger.recordAuditEvent({
eventId: randomUUID(),
eventType: "auth",
severity: this.getEventSeverity(eventType),
details: {
action: eventType,
...details
},
context: {
requestId: details.requestId || randomUUID(),
userId: details.userId,
organizationId: details.organizationId,
method: details.method,
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
source: "mcp-server",
version: "0.2.0"
}
});
}
/**
* Get event severity based on event type
*/
getEventSeverity(eventType) {
switch (eventType) {
case "authentication_failed":
case "permission_denied":
case "authorization_error":
return "error";
case "rate_limit_exceeded":
case "quota_exceeded":
return "warn";
default:
return "info";
}
}
/**
* Cleanup expired rate limit entries
*/
cleanupRateLimitStore() {
const now = Date.now();
let cleaned = 0;
for (const [key, info] of this.rateLimitStore.entries()) {
if (now >= info.resetTime) {
this.rateLimitStore.delete(key);
cleaned++;
}
}
if (cleaned > 0) {
enterpriseLogger.recordAuditEvent({
eventId: randomUUID(),
eventType: "auth",
severity: "info",
details: {
action: "rate_limit_cleanup",
cleanedEntries: cleaned,
remainingEntries: this.rateLimitStore.size
},
context: {
requestId: randomUUID(),
method: "cleanup_rate_limits",
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
source: "mcp-server",
version: "0.2.0"
}
});
}
}
/**
* Get authorization health status
*/
getHealthStatus() {
const orgStats = Array.from(authManager["organizations"].values());
const totalApiKeys = Array.from(authManager["apiKeys"].values()).length;
return {
status: "healthy",
// Simplified health check
rateLimitStoreSize: this.rateLimitStore.size,
activeOrganizations: orgStats.filter((org) => org.status === "active").length,
totalApiKeys,
averageResponseTime: 50
// Placeholder
};
}
};
var authMiddleware = AuthorizationMiddleware.getInstance();
export { AuthorizationMiddleware, authMiddleware };
//# sourceMappingURL=authorization-middleware.js.map
//# sourceMappingURL=authorization-middleware.js.map