// =============================================================================
// USER AUTHORIZATION CLIENT
// =============================================================================
//
// This calls the USER WALLET SERVICE to get authorization.
//
// THE FLOW (now realistic):
// 1. Agent wants to make payment
// 2. Agent calls this function
// 3. This function calls the User Wallet Service (separate container)
// 4. Wallet Service simulates user approval (Face ID / PIN)
// 5. Wallet Service signs mandate with user's PRIVATE KEY
// 6. Signed mandate returned to agent
//
// WHY SEPARATE SERVICE?
// - Agent does NOT have access to user's private key
// - Mandate creation happens in user's "phone" (wallet service)
// - Agent can only REQUEST authorization, not create mandates
// - More realistic architecture
//
// IN REAL WORLD:
// - Wallet Service = Apple Wallet / Google Pay / Banking App
// - Private key stored in Secure Enclave / TEE / HSM
// - User approves via Face ID / fingerprint / PIN
// =============================================================================
import type { Mandate, MandateRequest } from './interfaces.js';
const WALLET_SERVICE_URL = `http://${process.env.WALLET_HOST || 'user-wallet'}:8006`;
// Request authorization from user's wallet service
// Agent calls this → Wallet prompts user → User approves → Mandate returned
export async function authorizePayment(req: MandateRequest): Promise<Mandate> {
console.log('📱 Requesting authorization from user wallet...');
const response = await fetch(`${WALLET_SERVICE_URL}/authorize`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: req.userId,
agentId: req.agentId,
action: req.action,
maxAmount: req.maxAmount,
currency: req.currency,
orderId: req.orderId,
merchantName: 'Food Delivery Order',
}),
});
if (!response.ok) {
throw new Error('User denied authorization');
}
const data = await response.json() as { success: boolean; mandate: Mandate };
if (!data.success) {
throw new Error('User denied authorization');
}
console.log('✅ User authorized payment via wallet');
return data.mandate;
}