#!/usr/bin/env node
/**
* Debug script to analyze why OAuth test is failing
*
* ISSUE:
* 1. Authenticating with david+allcloud@umbrellacost.com (OAuth)
* 2. Sending request with customer_account_key=22676 and customer_division_id=139
* 3. Getting back account 268413799883 instead of expected 696314371547
*
* This script will trace the flow to understand why customer_account_key is not being respected.
*/
const axios = require('axios');
const MCP_BASE = 'https://localhost:3000';
console.log('🔍 OAUTH CUSTOMER_ACCOUNT_KEY BUG ANALYSIS');
console.log('═══════════════════════════════════════════');
console.log();
console.log('🎯 Testing scenario:');
console.log(' Authentication: david+allcloud@umbrellacost.com (OAuth flow)');
console.log(' Request params: customer_account_key=22676, customer_division_id=139');
console.log(' Expected account: 696314371547 (Bank Leumi)');
console.log(' Actual account: 268413799883 (Mark.Watson_Sandbox)');
console.log();
async function analyzeOAuthCustomerKeyBug() {
try {
// Configure axios to ignore SSL issues for localhost
const axiosInstance = axios.create({
httpsAgent: new (require('https').Agent)({
rejectUnauthorized: false
})
});
console.log('1️⃣ Testing OAuth authentication flow...');
console.log('─────────────────────────────────────────');
// Step 1: Get OAuth access token
const oauthResponse = await axiosInstance.post(`${MCP_BASE}/oauth/token`, {
username: 'david+allcloud@umbrellacost.com',
password: 'B4*zcI7#F7poEC'
}, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (!oauthResponse.data?.access_token) {
throw new Error('Failed to get OAuth access token');
}
const accessToken = oauthResponse.data.access_token;
console.log('✅ OAuth token obtained');
console.log(` Token: ${accessToken.substring(0, 20)}...`);
console.log();
// Step 2: Initialize MCP session
console.log('2️⃣ Initializing MCP session...');
console.log('─────────────────────────────────────────');
const initResponse = await axiosInstance.post(`${MCP_BASE}/mcp`, {
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: {
protocolVersion: "2024-11-05",
clientInfo: {
name: "debug-oauth-test",
version: "1.0.0"
},
capabilities: {}
}
}, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
}
});
console.log('✅ MCP session initialized');
console.log();
// Step 3: Test the failing scenario - customer_account_key without division auto-lookup
console.log('3️⃣ Testing problematic request (customer_account_key=22676, customer_division_id=139)...');
console.log('─────────────────────────────────────────────────────────────────────────────────────');
const testRequest = {
jsonrpc: "2.0",
id: 2,
method: "tools/call",
params: {
name: "api__invoices_caui",
arguments: {
customer_account_key: "22676", // Bank Leumi account key
customer_division_id: "139", // Bank Leumi division ID
startDate: "2025-08-01",
endDate: "2025-08-31",
periodGranLevel: "month",
groupBy: "none",
costType: "[\"cost\", \"discount\"]",
isUnblended: "true",
userQuery: "Bank Leumi costs"
}
}
};
console.log('📤 Request details:');
console.log(` customer_account_key: ${testRequest.params.arguments.customer_account_key}`);
console.log(` customer_division_id: ${testRequest.params.arguments.customer_division_id}`);
console.log(` userQuery: ${testRequest.params.arguments.userQuery}`);
console.log();
const response = await axiosInstance.post(`${MCP_BASE}/mcp`, testRequest, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
}
});
// Parse response (handle SSE format)
let parsedData;
if (typeof response.data === 'string' && response.data.includes('event: message')) {
const dataMatch = response.data.match(/data: ({.*})/);
if (dataMatch) {
parsedData = JSON.parse(dataMatch[1]);
}
} else {
parsedData = response.data;
}
console.log('📥 Response analysis:');
console.log('─────────────────────');
if (parsedData?.result?.content?.[0]?.text) {
const content = parsedData.result.content[0].text;
// Extract key information
const accountMatch = content.match(/"account_id":\s*"(\d+)"/);
const costMatch = content.match(/"total_cost":\s*([0-9.]+)/);
const apiKeyMatch = content.match(/API key.*?(\w+:\d+:\d+)/);
if (accountMatch) {
const returnedAccount = accountMatch[1];
console.log(` Returned Account ID: ${returnedAccount}`);
if (returnedAccount === '696314371547') {
console.log(' ✅ CORRECT! This is Bank Leumi');
} else if (returnedAccount === '268413799883') {
console.log(' ❌ BUG CONFIRMED! This is Mark.Watson_Sandbox');
console.log(' 🔍 The OAuth flow is NOT respecting customer_account_key parameter');
} else {
console.log(` ⚠️ Unknown account: ${returnedAccount}`);
}
}
if (costMatch) {
const cost = parseFloat(costMatch[1]);
console.log(` Total Cost: $${cost.toLocaleString()}`);
if (cost < 1) {
console.log(' 📊 Low cost suggests Bank Leumi (expected)');
} else if (cost > 20) {
console.log(' 📊 High cost suggests Mark.Watson_Sandbox (wrong account)');
}
}
if (apiKeyMatch) {
console.log(` API Key used: ${apiKeyMatch[1]}`);
const keyParts = apiKeyMatch[1].split(':');
if (keyParts.length === 3) {
console.log(` - User Key: ${keyParts[0]}`);
console.log(` - Account Key: ${keyParts[1]}`);
console.log(` - Division ID: ${keyParts[2]}`);
if (keyParts[1] === '22676') {
console.log(' ✅ API key uses correct account key (22676)');
} else {
console.log(` ❌ API key uses wrong account key (${keyParts[1]} instead of 22676)`);
}
if (keyParts[2] === '139') {
console.log(' ✅ API key uses correct division ID (139)');
} else {
console.log(` ❌ API key uses wrong division ID (${keyParts[2]} instead of 139)`);
}
}
}
console.log();
console.log('🔍 DETAILED ANALYSIS:');
console.log('──────────────────────');
// Check if the issue is in API key construction or parameter handling
if (apiKeyMatch) {
const keyParts = apiKeyMatch[1].split(':');
if (keyParts[1] === '22676' && keyParts[2] === '139') {
console.log('✅ API key is correctly constructed with customer parameters');
console.log('❌ The issue is likely in how the authentication method detection works');
console.log(' OAuth authentication might be triggering Keycloak path instead of Cognito');
console.log(' This could cause the division lookup logic to fail');
} else {
console.log('❌ API key construction is wrong');
console.log(' The customer_account_key/customer_division_id parameters are not being used');
}
}
// Additional detailed response for debugging
console.log();
console.log('📋 FULL RESPONSE CONTENT:');
console.log('──────────────────────────');
console.log(content.substring(0, 500) + '...');
} else {
console.log('⚠️ No valid response content found');
console.log('Raw response:', JSON.stringify(parsedData, null, 2));
}
console.log();
console.log('🎯 SUMMARY & NEXT STEPS:');
console.log('──────────────────────────');
console.log('1. This script confirms if the OAuth bug exists');
console.log('2. Check if API key is constructed correctly with customer parameters');
console.log('3. Verify user management detection (Keycloak vs Cognito) in OAuth flow');
console.log('4. Review buildCustomerApiKey method for OAuth-specific logic');
console.log();
} catch (error) {
console.error('❌ Error during analysis:', error.message);
if (error.response) {
console.error('Response status:', error.response.status);
console.error('Response data:', error.response.data);
}
}
}
// Run the analysis
analyzeOAuthCustomerKeyBug().catch(console.error);