|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { toError } from '@sim/utils/errors' |
| 3 | +import { type NextRequest, NextResponse } from 'next/server' |
| 4 | +import { getValidationErrorMessage, isZodError } from '@/lib/api/server' |
| 5 | +import { checkInternalAuth } from '@/lib/auth/hybrid' |
| 6 | +import { secureFetchWithValidation } from '@/lib/core/security/input-validation.server' |
| 7 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 8 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 9 | +import { |
| 10 | + assertSafeExternalUrl, |
| 11 | + extractSapConcurError, |
| 12 | + fetchSapConcurAccessToken, |
| 13 | + SAP_CONCUR_OUTBOUND_FETCH_TIMEOUT_MS, |
| 14 | + type SapConcurProxyRequest, |
| 15 | + SapConcurProxyRequestSchema, |
| 16 | +} from '@/app/api/tools/sap_concur/shared' |
| 17 | + |
| 18 | +export const dynamic = 'force-dynamic' |
| 19 | + |
| 20 | +const logger = createLogger('SapConcurProxyAPI') |
| 21 | + |
| 22 | +type ProxyRequest = SapConcurProxyRequest |
| 23 | + |
| 24 | +function buildApiUrl(geolocation: string, req: ProxyRequest): string { |
| 25 | + const base = geolocation.replace(/\/+$/, '') |
| 26 | + const subPath = req.path.startsWith('/') ? req.path : `/${req.path}` |
| 27 | + const url = `${base}${subPath}` |
| 28 | + |
| 29 | + if (!req.query || Object.keys(req.query).length === 0) { |
| 30 | + return url |
| 31 | + } |
| 32 | + const search = new URLSearchParams() |
| 33 | + for (const [key, value] of Object.entries(req.query)) { |
| 34 | + if (value === undefined || value === null) continue |
| 35 | + search.append(key, String(value)) |
| 36 | + } |
| 37 | + const queryString = search.toString() |
| 38 | + if (!queryString) return url |
| 39 | + return url.includes('?') ? `${url}&${queryString}` : `${url}?${queryString}` |
| 40 | +} |
| 41 | + |
| 42 | +interface Invocation { |
| 43 | + status: number |
| 44 | + body: unknown |
| 45 | + raw: string |
| 46 | +} |
| 47 | + |
| 48 | +async function callConcur( |
| 49 | + req: ProxyRequest, |
| 50 | + accessToken: string, |
| 51 | + geolocation: string |
| 52 | +): Promise<Invocation> { |
| 53 | + const url = assertSafeExternalUrl(buildApiUrl(geolocation, req), 'apiUrl').toString() |
| 54 | + const hasBody = req.body !== undefined && req.body !== null |
| 55 | + const headers: Record<string, string> = { |
| 56 | + Authorization: `Bearer ${accessToken}`, |
| 57 | + Accept: 'application/json', |
| 58 | + } |
| 59 | + if (hasBody) headers['Content-Type'] = req.contentType ?? 'application/json' |
| 60 | + if (req.companyUuid) headers['concur-correlationid'] = req.companyUuid |
| 61 | + |
| 62 | + const response = await secureFetchWithValidation( |
| 63 | + url, |
| 64 | + { |
| 65 | + method: req.method, |
| 66 | + headers, |
| 67 | + body: hasBody |
| 68 | + ? typeof req.body === 'string' |
| 69 | + ? req.body |
| 70 | + : JSON.stringify(req.body) |
| 71 | + : undefined, |
| 72 | + timeout: SAP_CONCUR_OUTBOUND_FETCH_TIMEOUT_MS, |
| 73 | + }, |
| 74 | + 'apiUrl' |
| 75 | + ) |
| 76 | + |
| 77 | + const raw = await response.text() |
| 78 | + let parsed: unknown = null |
| 79 | + if (raw.length > 0) { |
| 80 | + try { |
| 81 | + parsed = JSON.parse(raw) |
| 82 | + } catch { |
| 83 | + parsed = raw |
| 84 | + } |
| 85 | + } |
| 86 | + return { status: response.status, body: parsed, raw } |
| 87 | +} |
| 88 | + |
| 89 | +export const POST = withRouteHandler(async (request: NextRequest) => { |
| 90 | + const requestId = generateRequestId() |
| 91 | + |
| 92 | + try { |
| 93 | + const authResult = await checkInternalAuth(request, { requireWorkflowId: false }) |
| 94 | + if (!authResult.success) { |
| 95 | + logger.warn(`[${requestId}] Unauthorized Concur proxy request: ${authResult.error}`) |
| 96 | + return NextResponse.json( |
| 97 | + { success: false, error: authResult.error || 'Authentication required' }, |
| 98 | + { status: 401 } |
| 99 | + ) |
| 100 | + } |
| 101 | + |
| 102 | + // boundary-raw-json: internal proxy envelope validated by SapConcurProxyRequestSchema below; not a public boundary |
| 103 | + const json = await request.json() |
| 104 | + const proxyReq = SapConcurProxyRequestSchema.parse(json) |
| 105 | + |
| 106 | + const { accessToken, geolocation } = await fetchSapConcurAccessToken(proxyReq, requestId) |
| 107 | + const invocation = await callConcur(proxyReq, accessToken, geolocation) |
| 108 | + |
| 109 | + if (invocation.status >= 200 && invocation.status < 300) { |
| 110 | + const data = invocation.status === 204 ? null : invocation.body |
| 111 | + return NextResponse.json({ success: true, output: { status: invocation.status, data } }) |
| 112 | + } |
| 113 | + |
| 114 | + const message = extractSapConcurError(invocation.body, invocation.status) |
| 115 | + logger.warn( |
| 116 | + `[${requestId}] Concur API error (${invocation.status}) ${proxyReq.path}: ${message}` |
| 117 | + ) |
| 118 | + return NextResponse.json( |
| 119 | + { success: false, error: message, status: invocation.status }, |
| 120 | + { status: invocation.status } |
| 121 | + ) |
| 122 | + } catch (error) { |
| 123 | + if (isZodError(error)) { |
| 124 | + logger.warn(`[${requestId}] Validation error:`, error.issues) |
| 125 | + return NextResponse.json( |
| 126 | + { success: false, error: getValidationErrorMessage(error, 'Validation failed') }, |
| 127 | + { status: 400 } |
| 128 | + ) |
| 129 | + } |
| 130 | + logger.error(`[${requestId}] Unexpected Concur proxy error:`, error) |
| 131 | + return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 }) |
| 132 | + } |
| 133 | +}) |
0 commit comments