-
Notifications
You must be signed in to change notification settings - Fork 3.7k
feat(integrations): add Ramp integration with spend, receipts, and bill tools #4982
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
waleedlatif1
wants to merge
3
commits into
staging
Choose a base branch
from
worktree-ramp-integration
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
77f9858
feat(integrations): add Ramp integration with spend, receipts, and bi…
waleedlatif1 da035fa
fix(ramp): sanitize MIME type before embedding in multipart header
waleedlatif1 eceb558
fix(ramp): sanitize multipart field values against CRLF injection
waleedlatif1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -158,6 +158,7 @@ | |
| "qdrant", | ||
| "quiver", | ||
| "railway", | ||
| "ramp", | ||
| "rb2b", | ||
| "rds", | ||
| "reddit", | ||
|
|
||
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { getErrorMessage } from '@sim/utils/errors' | ||
| import { generateId } from '@sim/utils/id' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { rampUploadReceiptContract } from '@/lib/api/contracts/tools/ramp' | ||
| import { parseRequest } from '@/lib/api/server' | ||
| import { checkInternalAuth } from '@/lib/auth/hybrid' | ||
| import { generateRequestId } from '@/lib/core/utils/request' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { processFilesToUserFiles, type RawFileInput } from '@/lib/uploads/utils/file-utils' | ||
| import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server' | ||
| import { assertToolFileAccess } from '@/app/api/files/authorization' | ||
| import { extractRampError } from '@/tools/ramp/utils' | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| const logger = createLogger('RampUploadReceiptAPI') | ||
|
|
||
| const RAMP_RECEIPTS_URL = 'https://api.ramp.com/developer/v1/receipts' | ||
|
|
||
| /** | ||
| * Builds the multipart body for Ramp's receipt upload endpoint. Ramp expects | ||
| * metadata parts with `Content-Disposition: form-data` and the receipt image | ||
| * as a part named `receipt` with `Content-Disposition: attachment`. | ||
| */ | ||
| function buildReceiptMultipartBody( | ||
| boundary: string, | ||
| fields: Record<string, string>, | ||
| file: { name: string; type: string; buffer: Buffer } | ||
| ): Buffer { | ||
| const parts: Buffer[] = [] | ||
|
|
||
| for (const [name, value] of Object.entries(fields)) { | ||
| const safeValue = value.replace(/[\r\n]/g, '') | ||
| parts.push( | ||
| Buffer.from( | ||
| `--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${safeValue}\r\n` | ||
| ) | ||
| ) | ||
| } | ||
|
|
||
| const safeFileName = file.name.replace(/[\r\n"]/g, '_') | ||
| const safeContentType = file.type.replace(/[\r\n]/g, '') || 'application/octet-stream' | ||
| parts.push( | ||
| Buffer.from( | ||
| `--${boundary}\r\nContent-Disposition: attachment; name="receipt"; filename="${safeFileName}"\r\nContent-Type: ${safeContentType}\r\n\r\n` | ||
| ) | ||
| ) | ||
| parts.push(file.buffer) | ||
| parts.push(Buffer.from(`\r\n--${boundary}--\r\n`)) | ||
|
|
||
| return Buffer.concat(parts) | ||
| } | ||
|
|
||
| export const POST = withRouteHandler(async (request: NextRequest) => { | ||
| const requestId = generateRequestId() | ||
|
|
||
| try { | ||
| const authResult = await checkInternalAuth(request, { requireWorkflowId: false }) | ||
|
|
||
| if (!authResult.success || !authResult.userId) { | ||
| logger.warn(`[${requestId}] Unauthorized Ramp receipt upload attempt: ${authResult.error}`) | ||
| return NextResponse.json( | ||
| { success: false, error: authResult.error || 'Authentication required' }, | ||
| { status: 401 } | ||
| ) | ||
| } | ||
|
|
||
| const parsed = await parseRequest(rampUploadReceiptContract, request, {}) | ||
| if (!parsed.success) return parsed.response | ||
| const validatedData = parsed.data.body | ||
|
|
||
| const userFiles = processFilesToUserFiles( | ||
| [validatedData.file as RawFileInput], | ||
| requestId, | ||
| logger | ||
| ) | ||
|
|
||
| if (userFiles.length === 0) { | ||
| return NextResponse.json({ success: false, error: 'Invalid file input' }, { status: 400 }) | ||
| } | ||
|
|
||
| const userFile = userFiles[0] | ||
| logger.info( | ||
| `[${requestId}] Downloading receipt file: ${userFile.name} (${userFile.size} bytes)` | ||
| ) | ||
|
|
||
| const denied = await assertToolFileAccess(userFile.key, authResult.userId, requestId, logger) | ||
| if (denied) return denied | ||
| const fileBuffer = await downloadFileFromStorage(userFile, requestId, logger) | ||
|
|
||
| const fields: Record<string, string> = { | ||
| idempotency_key: generateId(), | ||
| user_id: validatedData.userId, | ||
| } | ||
| if (validatedData.transactionId) { | ||
| fields.transaction_id = validatedData.transactionId | ||
| } | ||
|
|
||
| const boundary = `----sim-ramp-receipt-${generateId()}` | ||
| const body = buildReceiptMultipartBody(boundary, fields, { | ||
| name: userFile.name, | ||
| type: userFile.type || 'application/octet-stream', | ||
| buffer: fileBuffer, | ||
| }) | ||
|
|
||
| logger.info(`[${requestId}] Uploading receipt to Ramp (${fileBuffer.length} bytes)`) | ||
|
|
||
| const response = await fetch(RAMP_RECEIPTS_URL, { | ||
| method: 'POST', | ||
| headers: { | ||
| Authorization: `Bearer ${validatedData.accessToken}`, | ||
| 'Content-Type': `multipart/form-data; boundary=${boundary}`, | ||
| }, | ||
| body: new Uint8Array(body), | ||
| }) | ||
|
|
||
| const data = await response.json().catch(() => ({})) | ||
|
|
||
| if (!response.ok) { | ||
| const errorMessage = extractRampError(data, 'Failed to upload receipt to Ramp') | ||
| logger.error(`[${requestId}] Ramp API error:`, { status: response.status, data }) | ||
| return NextResponse.json({ success: false, error: errorMessage }, { status: response.status }) | ||
| } | ||
|
|
||
| logger.info(`[${requestId}] Receipt uploaded successfully: ${data.id}`) | ||
|
|
||
| return NextResponse.json({ | ||
| success: true, | ||
| output: { | ||
| receiptId: data.id, | ||
| }, | ||
| }) | ||
| } catch (error) { | ||
| logger.error(`[${requestId}] Unexpected error:`, error) | ||
| return NextResponse.json( | ||
| { success: false, error: getErrorMessage(error, 'Unknown error') }, | ||
| { status: 500 } | ||
| ) | ||
| } | ||
| }) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.