Files
aura-courier-mcp/validate_plugin.js
T

311 lines
14 KiB
JavaScript

/**
* Aura Courier MCP — Plugin Validation & Compliance Suite
* Corresponds to `agy plugin validate .` standards.
*/
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PLUGIN_DIR = __dirname;
const PKG_VERSION = JSON.parse(fs.readFileSync(path.join(PLUGIN_DIR, 'package.json'), 'utf8')).version;
let passedChecks = 0;
let totalChecks = 0;
function assert(condition, message) {
totalChecks++;
if (condition) {
passedChecks++;
console.log(` [PASS] ${message}`);
} else {
console.error(` [FAIL] ${message}`);
process.exitCode = 1;
}
}
async function validateManifest() {
console.log('\n--- 1. Validating plugin.json Manifest ---');
const manifestPath = path.join(PLUGIN_DIR, 'plugin.json');
assert(fs.existsSync(manifestPath), 'plugin.json exists');
const content = fs.readFileSync(manifestPath, 'utf8');
let json;
try {
json = JSON.parse(content);
assert(true, 'plugin.json is valid JSON');
} catch (err) {
assert(false, `plugin.json JSON parse error: ${err.message}`);
return;
}
assert(json.$schema === 'https://antigravity.google/schemas/v1/plugin.json', 'plugin.json declares official Antigravity $schema');
assert(json.name === 'aura-courier', `name matches 'aura-courier' (got '${json.name}')`);
assert(json.displayName === 'Aura Courier MCP', `displayName is 'Aura Courier MCP'`);
assert(json.version === PKG_VERSION, `version matches package.json ('${PKG_VERSION}', got '${json.version}')`);
assert(json.privacyPolicyUrl === 'https://courier.auraajenticai.cloud/privacy', 'privacyPolicyUrl is configured');
assert(json.termsOfServiceUrl === 'https://courier.auraajenticai.cloud/terms', 'termsOfServiceUrl is configured');
assert(json.category === 'Business / Logistics', `category is 'Business / Logistics'`);
assert(typeof json.description === 'string' && json.description.length > 20, 'description is informative');
assert(json.logo === 'assets/logo.svg', `logo points to 'assets/logo.svg'`);
assert(Array.isArray(json.suggestedPrompts) && json.suggestedPrompts.length === 3, `suggestedPrompts contains exactly 3 starter prompts`);
assert(json.author && json.author.name && json.author.email, 'author metadata is complete');
assert(json.partner && json.partner.googleCloudPartnerUrl.includes('aura-ajentic-ai'), 'Google Cloud Partner Advantage link is present');
assert(json.repository && (typeof json.repository === 'string' || json.repository.url), 'source repository is configured');
assert(json.repository.url.includes('auraajenticai/aura-courier-mcp'), 'repository points to official auraajenticai/aura-courier-mcp');
assert(json.license === 'Apache-2.0', 'license is Apache-2.0');
assert(Array.isArray(json.keywords) && json.keywords.length >= 5, 'keywords tags array is populated');
assert(json.mcpServers && json.mcpServers['aura-courier'] && json.mcpServers['aura-courier'].url, 'mcpServers declaration exists in manifest');
}
async function validateMcpConfig() {
console.log('\n--- 2. Validating mcp_config.json ---');
const mcpConfigPath = path.join(PLUGIN_DIR, 'mcp_config.json');
assert(fs.existsSync(mcpConfigPath), 'mcp_config.json exists');
const content = fs.readFileSync(mcpConfigPath, 'utf8');
const json = JSON.parse(content);
assert(json.mcpServers && json.mcpServers['aura-courier'], 'server aura-courier is declared');
assert(json.mcpServers['aura-courier'].serverUrl === 'https://courier.auraajenticai.cloud/mcp', 'remote MCP serverUrl is https://courier.auraajenticai.cloud/mcp');
}
async function validateAssets() {
console.log('\n--- 3. Validating Assets ---');
const logoPath = path.join(PLUGIN_DIR, 'assets', 'logo.svg');
assert(fs.existsSync(logoPath), 'assets/logo.svg exists');
const logoContent = fs.readFileSync(logoPath, 'utf8');
assert(logoContent.includes('<svg') && logoContent.includes('</svg>'), 'logo.svg is valid XML/SVG');
assert(logoContent.includes('viewBox="0 0 1024 1024"'), 'logo.svg is square 1024x1024 asset');
}
async function validateSkillsAndRules() {
console.log('\n--- 4. Validating Skills & Rules ---');
const skillPath = path.join(PLUGIN_DIR, 'skills', 'courier-ops', 'SKILL.md');
assert(fs.existsSync(skillPath), 'skills/courier-ops/SKILL.md exists');
const skillContent = fs.readFileSync(skillPath, 'utf8');
assert(skillContent.startsWith('---') && skillContent.includes('name: courier-ops'), 'skill has valid YAML frontmatter');
const expectedTools = [
'list_couriers',
'create_parcel',
'track_parcel',
'get_balance',
'check_fraud_risk',
'validate_and_geocode_address',
'calculate_delivery_zone_and_fee',
'compare_courier_rates',
'resolve_ndr_issue',
'cancel_parcel',
'update_parcel',
'bulk_create_parcels',
'get_webhook_events'
];
for (const tool of expectedTools) {
assert(skillContent.includes(`\`${tool}\``), `skill documents tool '${tool}'`);
}
const courierRulesPath = path.join(PLUGIN_DIR, 'rules', 'COURIER_RULES.md');
const agentsPath = path.join(PLUGIN_DIR, 'rules', 'AGENTS.md');
assert(fs.existsSync(courierRulesPath), 'rules/COURIER_RULES.md exists');
assert(fs.existsSync(agentsPath), 'rules/AGENTS.md exists');
const ruleContent = fs.readFileSync(courierRulesPath, 'utf8');
assert(ruleContent.includes('Zero Mock Data Mandate'), 'COURIER_RULES enforces Zero Mock Data');
assert(ruleContent.includes('Steadfast') && ruleContent.includes('Pathao') && ruleContent.includes('RedX') && ruleContent.includes('Paperfly'), 'all 4 carriers are governed');
assert(ruleContent.includes('Google Maps Platform'), 'Google Maps geocoding policy is defined');
}
async function mintSandboxOAuthToken(baseOrigin, endpoint) {
const dcrRes = await fetch(`${baseOrigin}/oauth/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_name: 'Antigravity Validator',
redirect_uris: ['http://127.0.0.1:54321/callback'],
token_endpoint_auth_method: 'none'
})
});
const dcr = await dcrRes.json();
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
const authUrl = new URL(`${baseOrigin}/oauth/authorize`);
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('client_id', dcr.client_id);
authUrl.searchParams.set('redirect_uri', 'http://127.0.0.1:54321/callback');
authUrl.searchParams.set('code_challenge', challenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
authUrl.searchParams.set('scope', 'read');
authUrl.searchParams.set('state', 'validator');
authUrl.searchParams.set('resource', endpoint);
const consentGet = await fetch(authUrl.toString());
const html = await consentGet.text();
const csrfMatch = html.match(/name="csrf_token"\s+value="([^"]+)"/);
if (!csrfMatch) throw new Error('Could not extract OAuth CSRF token');
const form = new URLSearchParams({
client_id: dcr.client_id,
redirect_uri: 'http://127.0.0.1:54321/callback',
state: 'validator',
scope: 'read',
code_challenge: challenge,
code_challenge_method: 'S256',
resource: endpoint,
csrf_token: csrfMatch[1],
decision: 'sandbox',
auth_mode: 'sandbox'
});
const consentPost = await fetch(`${baseOrigin}/oauth/authorize`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: form.toString(),
redirect: 'manual'
});
const loc = consentPost.headers.get('location') || '';
const code = new URL(loc).searchParams.get('code');
if (!code) throw new Error('OAuth sandbox did not issue authorization code');
const tokRes = await fetch(`${baseOrigin}/oauth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
client_id: dcr.client_id,
redirect_uri: 'http://127.0.0.1:54321/callback',
code_verifier: verifier
}).toString()
});
const tokJson = await tokRes.json();
if (!tokJson.access_token) throw new Error('OAuth token endpoint did not return access_token');
return tokJson.access_token;
}
async function validateRemoteMcpServer() {
console.log('\n--- 5. Validating Live Remote MCP OAuth 2.1 Discovery, Handshake & 13 Tools ---');
const baseOrigin = 'https://courier.auraajenticai.cloud';
const endpoint = `${baseOrigin}/mcp`;
try {
// 5a. RFC 9728 Protected Resource Metadata & RFC 8414 Authorization Server Metadata
const prmRes = await fetch(`${baseOrigin}/.well-known/oauth-protected-resource`);
assert(prmRes.status === 200, `RFC 9728 /.well-known/oauth-protected-resource returned HTTP 200 (got ${prmRes.status})`);
const prmData = await prmRes.json();
assert(prmData.resource === endpoint, `protected resource matches ${endpoint}`);
const asmRes = await fetch(`${baseOrigin}/.well-known/oauth-authorization-server`);
assert(asmRes.status === 200, `RFC 8414 /.well-known/oauth-authorization-server returned HTTP 200 (got ${asmRes.status})`);
const asmData = await asmRes.json();
assert(Array.isArray(asmData.code_challenge_methods_supported) && asmData.code_challenge_methods_supported.includes('S256'), 'OAuth 2.1 PKCE S256 advertised');
// 5b. Unauthenticated initialize returns 401 + WWW-Authenticate challenge
const unauthRes = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 0,
method: 'initialize',
params: {
protocolVersion: '2025-03-26',
capabilities: {},
clientInfo: { name: 'antigravity-validator', version: PKG_VERSION }
}
})
});
assert(unauthRes.status === 401, `unauthenticated initialize returns HTTP 401 OAuth challenge (got ${unauthRes.status})`);
const wwwAuth = unauthRes.headers.get('www-authenticate') || '';
assert(wwwAuth.includes('resource_metadata='), '401 includes RFC 9728 WWW-Authenticate resource_metadata header');
const authToken = process.env.AURA_API_KEY || await mintSandboxOAuthToken(baseOrigin, endpoint);
// 5c. Authenticated initialize handshake + 13 live tools
const initRes = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2025-03-26',
capabilities: {},
clientInfo: { name: 'antigravity-validator', version: PKG_VERSION }
}
})
});
assert(initRes.status === 200, `authenticated initialize endpoint returned HTTP 200 (got ${initRes.status})`);
const sessionId = initRes.headers.get('mcp-session-id');
assert(!!sessionId, `mcp-session-id header received: ${sessionId}`);
const initData = await initRes.json();
assert(initData.result && initData.result.serverInfo && initData.result.serverInfo.name === 'aura-courier-mcp', 'serverInfo is aura-courier-mcp');
const toolsRes = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream',
'Authorization': `Bearer ${authToken}`,
'mcp-session-id': sessionId
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/list',
params: {}
})
});
assert(toolsRes.status === 200, `tools/list returned HTTP 200`);
const toolsData = await toolsRes.json();
const liveTools = toolsData.result?.tools || [];
assert(liveTools.length === 13, `exactly 13 tools returned by remote server (got ${liveTools.length})`);
const allAnnotated = liveTools.every(t => t.annotations && typeof t.annotations.readOnlyHint === 'boolean' && typeof t.annotations.destructiveHint === 'boolean');
assert(allAnnotated, 'all 13 live tools expose MCP readOnlyHint & destructiveHint annotations');
const termsRes = await fetch(`${baseOrigin}/terms`);
assert(termsRes.status === 200, `Terms of Service /terms returned HTTP 200 (got ${termsRes.status})`);
const privRes = await fetch(`${baseOrigin}/privacy`);
assert(privRes.status === 200, `Privacy Policy /privacy returned HTTP 200 (got ${privRes.status})`);
const liveToolNames = liveTools.map(t => t.name);
console.log(` Live tools on server: [ ${liveToolNames.join(', ')} ]`);
assert(liveToolNames.includes('create_parcel'), 'create_parcel tool is live');
assert(liveToolNames.includes('check_fraud_risk'), 'check_fraud_risk tool is live');
assert(liveToolNames.includes('validate_and_geocode_address'), 'validate_and_geocode_address tool is live');
} catch (err) {
assert(false, `Remote MCP server connection error: ${err.message}`);
}
}
async function run() {
console.log('====================================================');
console.log(' Aura Courier MCP — Antigravity Plugin Validator ');
console.log('====================================================');
await validateManifest();
await validateMcpConfig();
await validateAssets();
await validateSkillsAndRules();
await validateRemoteMcpServer();
console.log('\n====================================================');
console.log(` Result: ${passedChecks}/${totalChecks} checks passed.`);
console.log('====================================================\n');
if (process.exitCode) {
process.exit(1);
}
}
run();