d25d482dc2
Publish CLI Package / publish-npm (push) Waiting to run
Publish Python SDK / publish-pypi (push) Waiting to run
Publish TypeScript SDK / publish-npm (push) Waiting to run
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
195 lines
6.9 KiB
TypeScript
195 lines
6.9 KiB
TypeScript
import { createLogger } from '@sim/logger'
|
|
import { getErrorMessage } from '@sim/utils/errors'
|
|
import { type NextRequest, NextResponse } from 'next/server'
|
|
import { sendGridSendMailContract } from '@/lib/api/contracts/tools/communication/email'
|
|
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 } from '@/lib/uploads/utils/file-utils'
|
|
import { downloadServableFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
|
import { docNotReadyResponse } from '@/lib/uploads/utils/servable-file-response'
|
|
import { assertToolFileAccess } from '@/app/api/files/authorization'
|
|
|
|
export const dynamic = 'force-dynamic'
|
|
|
|
const logger = createLogger('SendGridSendMailAPI')
|
|
|
|
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 SendGrid send attempt: ${authResult.error}`)
|
|
return NextResponse.json(
|
|
{ success: false, error: authResult.error || 'Authentication required' },
|
|
{ status: 401 }
|
|
)
|
|
}
|
|
|
|
const userId = authResult.userId
|
|
logger.info(`[${requestId}] Authenticated SendGrid send request via ${authResult.authType}`)
|
|
|
|
const parsed = await parseRequest(sendGridSendMailContract, request, {})
|
|
if (!parsed.success) return parsed.response
|
|
const validatedData = parsed.data.body
|
|
|
|
logger.info(`[${requestId}] Sending SendGrid email`, {
|
|
to: validatedData.to,
|
|
subject: validatedData.subject || '(template)',
|
|
hasAttachments: !!(validatedData.attachments && validatedData.attachments.length > 0),
|
|
attachmentCount: validatedData.attachments?.length || 0,
|
|
})
|
|
|
|
// Build personalizations
|
|
const personalizations: Record<string, unknown> = {
|
|
to: [
|
|
{ email: validatedData.to, ...(validatedData.toName && { name: validatedData.toName }) },
|
|
],
|
|
}
|
|
|
|
if (validatedData.cc) {
|
|
personalizations.cc = [{ email: validatedData.cc }]
|
|
}
|
|
|
|
if (validatedData.bcc) {
|
|
personalizations.bcc = [{ email: validatedData.bcc }]
|
|
}
|
|
|
|
if (validatedData.templateId && validatedData.dynamicTemplateData) {
|
|
personalizations.dynamic_template_data =
|
|
typeof validatedData.dynamicTemplateData === 'string'
|
|
? JSON.parse(validatedData.dynamicTemplateData)
|
|
: validatedData.dynamicTemplateData
|
|
}
|
|
|
|
// Build mail body
|
|
const mailBody: Record<string, unknown> = {
|
|
personalizations: [personalizations],
|
|
from: {
|
|
email: validatedData.from,
|
|
...(validatedData.fromName && { name: validatedData.fromName }),
|
|
},
|
|
subject: validatedData.subject,
|
|
}
|
|
|
|
if (validatedData.templateId) {
|
|
mailBody.template_id = validatedData.templateId
|
|
} else {
|
|
mailBody.content = [
|
|
{
|
|
type: validatedData.contentType || 'text/plain',
|
|
value: validatedData.content,
|
|
},
|
|
]
|
|
}
|
|
|
|
if (validatedData.replyTo) {
|
|
mailBody.reply_to = {
|
|
email: validatedData.replyTo,
|
|
...(validatedData.replyToName && { name: validatedData.replyToName }),
|
|
}
|
|
}
|
|
|
|
// Process attachments from UserFile objects
|
|
if (validatedData.attachments && validatedData.attachments.length > 0) {
|
|
const rawAttachments = validatedData.attachments
|
|
logger.info(`[${requestId}] Processing ${rawAttachments.length} attachment(s)`)
|
|
|
|
const userFiles = processFilesToUserFiles(rawAttachments, requestId, logger)
|
|
|
|
if (userFiles.length > 0) {
|
|
const accessResults = await Promise.all(
|
|
userFiles.map((file) => assertToolFileAccess(file.key, userId, requestId, logger))
|
|
)
|
|
const denied = accessResults.find((r) => r !== null)
|
|
if (denied) return denied
|
|
|
|
let resolved: Array<{ buffer: Buffer; contentType: string }>
|
|
try {
|
|
resolved = await Promise.all(
|
|
userFiles.map(async (file) => {
|
|
logger.info(
|
|
`[${requestId}] Downloading attachment: ${file.name} (${file.size} bytes)`
|
|
)
|
|
return await downloadServableFileFromStorage(file, requestId, logger)
|
|
})
|
|
)
|
|
} catch (error) {
|
|
const notReady = docNotReadyResponse(error)
|
|
if (notReady) return notReady
|
|
logger.error(`[${requestId}] Failed to download an attachment:`, error)
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: `Failed to download attachment: ${getErrorMessage(error, 'Unknown error')}`,
|
|
},
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
|
|
const resolvedTotal = resolved.reduce((sum, r) => sum + r.buffer.length, 0)
|
|
const maxSize = 30 * 1024 * 1024
|
|
if (resolvedTotal > maxSize) {
|
|
const sizeMB = (resolvedTotal / (1024 * 1024)).toFixed(2)
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: `Total attachment size (${sizeMB}MB) exceeds SendGrid's limit of 30MB`,
|
|
},
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const sendGridAttachments = userFiles.map((file, i) => ({
|
|
content: resolved[i].buffer.toString('base64'),
|
|
filename: file.name,
|
|
type: resolved[i].contentType || file.type || 'application/octet-stream',
|
|
disposition: 'attachment',
|
|
}))
|
|
|
|
mailBody.attachments = sendGridAttachments
|
|
}
|
|
}
|
|
|
|
// Send to SendGrid
|
|
const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: `Bearer ${validatedData.apiKey}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(mailBody),
|
|
})
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response.json().catch(() => ({}))
|
|
const errorMessage =
|
|
errorData.errors?.[0]?.message || errorData.message || 'Failed to send email'
|
|
logger.error(`[${requestId}] SendGrid API error:`, { status: response.status, errorData })
|
|
return NextResponse.json({ success: false, error: errorMessage }, { status: response.status })
|
|
}
|
|
|
|
const messageId = response.headers.get('X-Message-Id')
|
|
logger.info(`[${requestId}] Email sent successfully`, { messageId })
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
output: {
|
|
success: true,
|
|
messageId: messageId || undefined,
|
|
to: validatedData.to,
|
|
subject: validatedData.subject || '',
|
|
},
|
|
})
|
|
} catch (error) {
|
|
logger.error(`[${requestId}] Unexpected error:`, error)
|
|
return NextResponse.json(
|
|
{ success: false, error: getErrorMessage(error, 'Unknown error') },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
})
|