Skip to content
Merged

Stage #9276

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/mcp/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/mcp/src",
"projectType": "application",
"implicitDependencies": ["mcp-server"],
"targets": {
"build": {
"executor": "@nx/js:tsc",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@
"doc:build": "compodoc -p tsconfig.json -d dist/docs",
"doc:serve": "compodoc -s -d dist/docs",
"doc:build-serve": "compodoc -p tsconfig.json -d docs -s",
"postinstall.manual": "yarn ts-node ./.scripts/postinstall.js",
"postinstall.manual": "yarn node ./.scripts/postinstall.js",
"postinstall.electron": "yarn electron-builder install-app-deps && yarn node tools/electron/postinstall",
"postinstall.web": "yarn node ./decorate-angular-cli.js && yarn node tools/web/postinstall",
"build:desktop": "cross-env NODE_ENV=production yarn run copy-files-i18n-desktop && yarn run postinstall.electron && yarn run config:prod && yarn run config:desktop:prod && yarn run build:package:all:prod && yarn run pack:desktop && yarn run generate:icons:desktop --environment=prod && yarn ng:prod run gauzy:desktop-ui --base-href ./ && yarn run prepare:desktop && yarn ng:prod run api:desktop-api && yarn ng:prod build desktop-api --output-path=dist/apps/desktop/desktop-api && yarn ng:prod build desktop --base-href ./ && yarn run copy-files-desktop && yarn run copy-assets-gauzy",
Expand Down
11 changes: 5 additions & 6 deletions packages/mcp-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,17 @@
},
"private": true,
"type": "commonjs",
"main": "./src/index.js",
"types": "./src/index.d.ts",
"main": "../../../dist/packages/mcp-server/src/index.js",
"types": "../../../dist/packages/mcp-server/src/index.d.ts",
"homepage": "https://ever.co",
"license": "AGPL-3.0",
"scripts": {
"start": "nx serve mcp",
"lib:build": "yarn nx build mcp-server",
"lib:build:prod": "cross-env NODE_ENV=production yarn ts-node scripts/replace-env-files.ts --environment=prod && yarn nx build mcp-server",
"lib:watch": "yarn nx build mcp-server --watch"
"lib:build": "cross-env NODE_OPTIONS=--max-old-space-size=12288 yarn nx build mcp-server",
"lib:build:prod": "cross-env NODE_ENV=production NODE_OPTIONS=--max-old-space-size=12288 yarn ts-node scripts/replace-env-files.ts --environment=prod && yarn nx build mcp-server",
"lib:watch": "cross-env NODE_OPTIONS=--max-old-space-size=12288 yarn nx build mcp-server --watch"
},
"dependencies": {
"@gauzy/auth": "^0.1.0",
"@modelcontextprotocol/sdk": "^1.13.1",
"@nestjs/common": "^11.1.0",
"@nestjs/core": "^11.1.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/mcp-server/src/lib/common/api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import axios, { AxiosInstance, AxiosRequestConfig, AxiosError } from 'axios';
import { Logger } from '@nestjs/common';
import { environment } from '../environments/environment';
import { authManager } from './auth-manager';
import { sanitizeErrorMessage } from '@gauzy/auth';
import { sanitizeErrorMessage } from './error-utils';

const logger = new Logger('ApiClient');

Expand Down
2 changes: 1 addition & 1 deletion packages/mcp-server/src/lib/common/auth-manager.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { environment } from '../environments/environment';
import { sanitizeForLogging } from '@gauzy/auth';
import { sanitizeForLogging } from './error-utils';
import { Logger } from '@nestjs/common';

const logger = new Logger('AuthManager');
Expand Down
214 changes: 214 additions & 0 deletions packages/mcp-server/src/lib/common/auth-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
/**
* Authorization types for MCP Server
*
* These types are defined locally to avoid importing from @gauzy/auth,
* which causes TypeScript compilation performance issues due to its complex
* dependency chain in the monorepo.
*/

import { Request, Response } from 'express';

/**
* Authorization server configuration
*/
export interface AuthorizationServerConfig {
issuer: string;
jwksUri?: string;
tokenEndpoint?: string;
authorizationEndpoint?: string;
}

/**
* Authorization configuration
*/
export interface AuthorizationConfig {
enabled: boolean;
requiredScopes: string[];
resourceUri?: string;
authorizationServers: AuthorizationServerConfig[];
tokenValidation?: {
audience?: string;
issuer?: string | string[];
clockTolerance?: number;
};
}

/**
* OAuth 2.0 Protected Resource Metadata (RFC 9728)
*/
export interface ProtectedResourceMetadata {
resource: string;
authorizationServers: string[];
scopesRequired?: string[];
bearerMethodsSupported?: string[];
policyUri?: string;
}

/**
* OAuth authorization error
*/
export interface OAuthAuthorizationError {
error: string;
errorDescription?: string;
errorUri?: string;
scope?: string;
}

/**
* Token validation result
*/
export interface TokenValidationResult {
valid: boolean;
error?: string;
payload?: unknown;
scopes?: string[];
subject?: string;
clientId?: string;
}

/**
* Load authorization configuration from environment
*/
export function loadAuthorizationConfig(): AuthorizationConfig {
const enabled = process.env.MCP_AUTHORIZATION_ENABLED === 'true';

return {
enabled,
requiredScopes: (process.env.MCP_REQUIRED_SCOPES || 'mcp:read mcp:write').split(' ').filter(Boolean),
resourceUri: process.env.MCP_RESOURCE_URI,
authorizationServers: enabled
? [
{
issuer: process.env.MCP_AUTH_ISSUER || 'https://auth.example.com',
jwksUri: process.env.MCP_AUTH_JWKS_URI,
tokenEndpoint: process.env.MCP_AUTH_TOKEN_ENDPOINT,
authorizationEndpoint: process.env.MCP_AUTH_AUTHORIZATION_ENDPOINT
}
]
: []
};
}

/**
* OAuth validator for token validation
*/
export class OAuthValidator {
constructor(private config: AuthorizationConfig) {}

/**
* Extract bearer token from request
*/
extractBearerToken(req: Request): string | null {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return null;
}
return authHeader.substring(7);
}

/**
* Validate an OAuth token
*/
async validateToken(token: string, requiredScopes?: string[]): Promise<TokenValidationResult> {
if (!this.config.enabled) {
return { valid: true };
}

// TODO: Implement actual JWT validation when authorization is enabled
// For now, return invalid if authorization is enabled but no implementation
return {
valid: false,
error: 'Token validation not implemented'
};
Comment on lines +117 to +122
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Token validation returns valid: false when authorization is enabled, effectively blocking all requests. This creates a security issue where the feature appears enabled but isn't functional. Is authorization intended to be non-functional in this PR, or should there be basic JWT validation implemented?

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/mcp-server/src/lib/common/auth-types.ts
Line: 117:122

Comment:
**logic:** Token validation returns `valid: false` when authorization is enabled, effectively blocking all requests. This creates a security issue where the feature appears enabled but isn't functional. Is authorization intended to be non-functional in this PR, or should there be basic JWT validation implemented?

How can I resolve this? If you propose a fix, please make it concise.

}

/**
* Create authorization error object
*/
static createAuthorizationError(
error: string,
errorDescription?: string,
scope?: string
): OAuthAuthorizationError {
return {
error,
errorDescription,
scope
};
}

/**
* Format WWW-Authenticate header
*/
static formatWWWAuthenticateHeader(resourceUri: string, error?: OAuthAuthorizationError): string {
let header = 'Bearer';

if (resourceUri) {
header += ` resource="${resourceUri}"`;
}

if (error) {
if (error.error) {
header += ` error="${error.error}"`;
}
if (error.errorDescription) {
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Dec 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Values interpolated into the WWW-Authenticate header should be escaped to prevent header injection. Double quotes and backslashes in error values would create malformed headers per RFC 7230.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/mcp-server/src/lib/common/auth-types.ts, line 154:

<comment>Values interpolated into the WWW-Authenticate header should be escaped to prevent header injection. Double quotes and backslashes in error values would create malformed headers per RFC 7230.</comment>

<file context>
@@ -0,0 +1,214 @@
+			if (error.error) {
+				header += ` error=&quot;${error.error}&quot;`;
+			}
+			if (error.errorDescription) {
+				header += ` error_description=&quot;${error.errorDescription}&quot;`;
+			}
</file context>
Fix with Cubic

header += ` error_description="${error.errorDescription}"`;
}
if (error.scope) {
header += ` scope="${error.scope}"`;
}
}

return header;
}
}

/**
* Response builder utilities
*/
export class ResponseBuilder {
/**
* Set security headers on response
*/
static setSecurityHeaders(res: Response): void {
// Content-Type options
res.setHeader('X-Content-Type-Options', 'nosniff');

// Frame options
res.setHeader('X-Frame-Options', 'DENY');

// XSS protection
res.setHeader('X-XSS-Protection', '1; mode=block');

// Referrer policy
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');

// Content Security Policy
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
);

// Strict Transport Security (for HTTPS)
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');

// Cache control for API responses
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
}

/**
* Build success response
*/
static success<T>(data: T, message?: string): { success: true; data: T; message?: string } {
return { success: true, data, message };
}

/**
* Build error response
*/
static error(message: string, code?: string): { success: false; error: string; code?: string } {
return { success: false, error: message, code };
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
*/

import { Request, Response, NextFunction } from 'express';
import { AuthorizationConfig, ProtectedResourceMetadata, OAuthValidator, SecurityLogger } from '@gauzy/auth';
import { AuthorizationConfig, ProtectedResourceMetadata, OAuthValidator } from './auth-types';
import { SecurityLogger } from './security-logger';

export interface AuthorizedRequest extends Request {
/** OAuth token validation result */
Expand Down
4 changes: 1 addition & 3 deletions packages/mcp-server/src/lib/common/authorization-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@

import { URL } from 'node:url';
import { createHash, randomBytes } from 'node:crypto';
import { SecurityLogger } from '@gauzy/auth';

const securityLogger = new SecurityLogger();
import { SecurityLogger, securityLogger } from './security-logger';

/**
* Validate canonical resource URI according to RFC 8707
Expand Down
Loading
Loading