chore: import upstream snapshot with attribution
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
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:20:55 +08:00
commit d25d482dc2
13754 changed files with 4996608 additions and 0 deletions
@@ -0,0 +1,98 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { outlookCopyContract } from '@/lib/api/contracts/tools/microsoft'
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'
export const dynamic = 'force-dynamic'
const logger = createLogger('OutlookCopyAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateRequestId()
try {
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
if (!authResult.success) {
logger.warn(`[${requestId}] Unauthorized Outlook copy attempt: ${authResult.error}`)
return NextResponse.json(
{
success: false,
error: authResult.error || 'Authentication required',
},
{ status: 401 }
)
}
logger.info(`[${requestId}] Authenticated Outlook copy request via ${authResult.authType}`, {
userId: authResult.userId,
})
const parsed = await parseRequest(outlookCopyContract, request, {})
if (!parsed.success) return parsed.response
const validatedData = parsed.data.body
logger.info(`[${requestId}] Copying Outlook email`, {
messageId: validatedData.messageId,
destinationId: validatedData.destinationId,
})
const graphEndpoint = `https://graph.microsoft.com/v1.0/me/messages/${validatedData.messageId}/copy`
logger.info(`[${requestId}] Sending to Microsoft Graph API: ${graphEndpoint}`)
const graphResponse = await fetch(graphEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${validatedData.accessToken}`,
},
body: JSON.stringify({
destinationId: validatedData.destinationId,
}),
})
if (!graphResponse.ok) {
const errorData = await graphResponse.json().catch(() => ({}))
logger.error(`[${requestId}] Microsoft Graph API error:`, errorData)
return NextResponse.json(
{
success: false,
error: errorData.error?.message || 'Failed to copy email',
},
{ status: graphResponse.status }
)
}
const responseData = await graphResponse.json()
logger.info(`[${requestId}] Email copied successfully`, {
originalMessageId: validatedData.messageId,
copiedMessageId: responseData.id,
destinationFolderId: responseData.parentFolderId,
})
return NextResponse.json({
success: true,
output: {
message: 'Email copied successfully',
originalMessageId: validatedData.messageId,
copiedMessageId: responseData.id,
destinationFolderId: responseData.parentFolderId,
},
})
} catch (error) {
logger.error(`[${requestId}] Error copying Outlook email:`, error)
return NextResponse.json(
{
success: false,
error: getErrorMessage(error, 'Unknown error occurred'),
},
{ status: 500 }
)
}
})
@@ -0,0 +1,88 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { outlookDeleteContract } from '@/lib/api/contracts/tools/microsoft'
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'
export const dynamic = 'force-dynamic'
const logger = createLogger('OutlookDeleteAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateRequestId()
try {
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
if (!authResult.success) {
logger.warn(`[${requestId}] Unauthorized Outlook delete attempt: ${authResult.error}`)
return NextResponse.json(
{
success: false,
error: authResult.error || 'Authentication required',
},
{ status: 401 }
)
}
logger.info(`[${requestId}] Authenticated Outlook delete request via ${authResult.authType}`, {
userId: authResult.userId,
})
const parsed = await parseRequest(outlookDeleteContract, request, {})
if (!parsed.success) return parsed.response
const validatedData = parsed.data.body
logger.info(`[${requestId}] Deleting Outlook email`, {
messageId: validatedData.messageId,
})
const graphEndpoint = `https://graph.microsoft.com/v1.0/me/messages/${validatedData.messageId}`
logger.info(`[${requestId}] Sending to Microsoft Graph API: ${graphEndpoint}`)
const graphResponse = await fetch(graphEndpoint, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${validatedData.accessToken}`,
},
})
if (!graphResponse.ok) {
const errorData = await graphResponse.json().catch(() => ({}))
logger.error(`[${requestId}] Microsoft Graph API error:`, errorData)
return NextResponse.json(
{
success: false,
error: errorData.error?.message || 'Failed to delete email',
},
{ status: graphResponse.status }
)
}
logger.info(`[${requestId}] Email deleted successfully`, {
messageId: validatedData.messageId,
})
return NextResponse.json({
success: true,
output: {
message: 'Email moved to Deleted Items successfully',
messageId: validatedData.messageId,
status: 'deleted',
},
})
} catch (error) {
logger.error(`[${requestId}] Error deleting Outlook email:`, error)
return NextResponse.json(
{
success: false,
error: getErrorMessage(error, 'Unknown error occurred'),
},
{ status: 500 }
)
}
})
@@ -0,0 +1,205 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { outlookDraftContract } from '@/lib/api/contracts/tools/microsoft'
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('OutlookDraftAPI')
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 Outlook draft attempt: ${authResult.error}`)
return NextResponse.json(
{
success: false,
error: authResult.error || 'Authentication required',
},
{ status: 401 }
)
}
const userId = authResult.userId
logger.info(`[${requestId}] Authenticated Outlook draft request via ${authResult.authType}`, {
userId,
})
const parsed = await parseRequest(outlookDraftContract, request, {})
if (!parsed.success) return parsed.response
const validatedData = parsed.data.body
logger.info(`[${requestId}] Creating Outlook draft`, {
to: validatedData.to,
subject: validatedData.subject,
hasAttachments: !!(validatedData.attachments && validatedData.attachments.length > 0),
attachmentCount: validatedData.attachments?.length || 0,
})
const toRecipients = validatedData.to.split(',').map((email) => ({
emailAddress: { address: email.trim() },
}))
const ccRecipients = validatedData.cc
? validatedData.cc.split(',').map((email) => ({
emailAddress: { address: email.trim() },
}))
: undefined
const bccRecipients = validatedData.bcc
? validatedData.bcc.split(',').map((email) => ({
emailAddress: { address: email.trim() },
}))
: undefined
const message: any = {
subject: validatedData.subject,
body: {
contentType: validatedData.contentType || 'text',
content: validatedData.body,
},
toRecipients,
}
if (ccRecipients) {
message.ccRecipients = ccRecipients
}
if (bccRecipients) {
message.bccRecipients = bccRecipients
}
if (validatedData.attachments && validatedData.attachments.length > 0) {
const rawAttachments = validatedData.attachments
logger.info(`[${requestId}] Processing ${rawAttachments.length} attachment(s)`)
const attachments = processFilesToUserFiles(rawAttachments, requestId, logger)
if (attachments.length > 0) {
const totalSize = attachments.reduce((sum, file) => sum + file.size, 0)
const maxSize = 4 * 1024 * 1024 // 4MB
if (totalSize > maxSize) {
const sizeMB = (totalSize / (1024 * 1024)).toFixed(2)
return NextResponse.json(
{
success: false,
error: `Total attachment size (${sizeMB}MB) exceeds Outlook's limit of 4MB per request`,
},
{ status: 400 }
)
}
const accessResults = await Promise.all(
attachments.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(
attachments.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)
if (resolvedTotal > maxSize) {
const sizeMB = (resolvedTotal / (1024 * 1024)).toFixed(2)
return NextResponse.json(
{
success: false,
error: `Total attachment size (${sizeMB}MB) exceeds Outlook's limit of 4MB per request`,
},
{ status: 400 }
)
}
const attachmentObjects = attachments.map((file, i) => ({
'@odata.type': '#microsoft.graph.fileAttachment',
name: file.name,
contentType: resolved[i].contentType || file.type || 'application/octet-stream',
contentBytes: resolved[i].buffer.toString('base64'),
}))
logger.info(`[${requestId}] Converted ${attachmentObjects.length} attachments to base64`)
message.attachments = attachmentObjects
}
}
const graphEndpoint = 'https://graph.microsoft.com/v1.0/me/messages'
logger.info(`[${requestId}] Creating draft via Microsoft Graph API`)
const graphResponse = await fetch(graphEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${validatedData.accessToken}`,
},
body: JSON.stringify(message),
})
if (!graphResponse.ok) {
const errorData = await graphResponse.json().catch(() => ({}))
logger.error(`[${requestId}] Microsoft Graph API error:`, errorData)
return NextResponse.json(
{
success: false,
error: errorData.error?.message || 'Failed to create draft',
},
{ status: graphResponse.status }
)
}
const responseData = await graphResponse.json()
logger.info(`[${requestId}] Draft created successfully, ID: ${responseData.id}`)
return NextResponse.json({
success: true,
output: {
message: 'Draft created successfully',
messageId: responseData.id,
subject: responseData.subject,
attachmentCount: message.attachments?.length || 0,
},
})
} catch (error) {
logger.error(`[${requestId}] Error creating Outlook draft:`, error)
return NextResponse.json(
{
success: false,
error: getErrorMessage(error, 'Unknown error occurred'),
},
{ status: 500 }
)
}
})
@@ -0,0 +1,169 @@
import { createLogger } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { outlookFoldersSelectorContract } from '@/lib/api/contracts/selectors/microsoft'
import { parseRequest } from '@/lib/api/server'
import { authorizeCredentialUse } from '@/lib/auth/credential-access'
import { validateAlphanumericId } from '@/lib/core/security/input-validation'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
import { assertGraphNextPageUrl, getGraphNextPageUrl } from '@/tools/sharepoint/utils'
export const dynamic = 'force-dynamic'
const logger = createLogger('OutlookFoldersAPI')
/**
* Microsoft Graph paginates `mailFolders` via the `@odata.nextLink` absolute
* URL in the response body (default page size is ~10). Bound the drain so a
* pathological account can't loop unbounded; `$top` is capped at 999 by Graph.
* See https://learn.microsoft.com/en-us/graph/paging
*/
const OUTLOOK_FOLDERS_PAGE_SIZE = 999
const MAX_OUTLOOK_FOLDERS_PAGES = 20
interface OutlookFolder {
id: string
displayName: string
totalItemCount?: number
unreadItemCount?: number
}
export const GET = withRouteHandler(async (request: NextRequest) => {
try {
const parsed = await parseRequest(outlookFoldersSelectorContract, request, {})
if (!parsed.success) return parsed.response
const { credentialId } = parsed.data.query
const credentialIdValidation = validateAlphanumericId(credentialId, 'credentialId')
if (!credentialIdValidation.isValid) {
logger.warn('Invalid credentialId format', { error: credentialIdValidation.error })
return NextResponse.json({ error: credentialIdValidation.error }, { status: 400 })
}
try {
const credAccess = await authorizeCredentialUse(request, {
credentialId,
requireWorkflowIdForInternal: false,
})
if (!credAccess.ok || !credAccess.credentialOwnerUserId) {
logger.warn('Credential access denied', { error: credAccess.error })
return NextResponse.json(
{ error: credAccess.error || 'Authentication required' },
{ status: 401 }
)
}
const accessToken = await refreshAccessTokenIfNeeded(
credentialId,
credAccess.credentialOwnerUserId,
generateRequestId()
)
if (!accessToken) {
logger.error('Failed to get access token', {
credentialId,
userId: credAccess.credentialOwnerUserId,
})
return NextResponse.json(
{
error: 'Could not retrieve access token',
authRequired: true,
},
{ status: 401 }
)
}
const folders: OutlookFolder[] = []
let nextUrl: string | undefined =
`https://graph.microsoft.com/v1.0/me/mailFolders?$top=${OUTLOOK_FOLDERS_PAGE_SIZE}`
for (let page = 0; page < MAX_OUTLOOK_FOLDERS_PAGES && nextUrl; page++) {
const response = await fetch(nextUrl, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
})
if (!response.ok) {
const errorData = await response.json()
logger.error('Microsoft Graph API error getting folders', {
status: response.status,
error: errorData,
endpoint: nextUrl,
})
if (response.status === 401) {
return NextResponse.json(
{
error: 'Authentication failed. Please reconnect your Outlook account.',
authRequired: true,
},
{ status: 401 }
)
}
throw new Error(`Microsoft Graph API error: ${JSON.stringify(errorData)}`)
}
const data = await response.json()
folders.push(...((data.value as OutlookFolder[]) || []))
const nextLink = getGraphNextPageUrl(data)
nextUrl = nextLink ? assertGraphNextPageUrl(nextLink) : undefined
if (nextUrl && page === MAX_OUTLOOK_FOLDERS_PAGES - 1) {
logger.warn('Outlook mailFolders hit pagination cap; folder list may be incomplete', {
pages: MAX_OUTLOOK_FOLDERS_PAGES,
collected: folders.length,
})
}
}
const transformedFolders = folders.map((folder: OutlookFolder) => ({
id: folder.id,
name: folder.displayName,
type: 'folder',
messagesTotal: folder.totalItemCount || 0,
messagesUnread: folder.unreadItemCount || 0,
}))
return NextResponse.json({
folders: transformedFolders,
})
} catch (innerError) {
logger.error('Error during API requests:', innerError)
const errorMessage = toError(innerError).message
if (
errorMessage.includes('auth') ||
errorMessage.includes('token') ||
errorMessage.includes('unauthorized') ||
errorMessage.includes('unauthenticated')
) {
return NextResponse.json(
{
error: 'Authentication failed. Please reconnect your Outlook account.',
authRequired: true,
details: errorMessage,
},
{ status: 401 }
)
}
throw innerError
}
} catch (error) {
logger.error('Error processing Outlook folders request:', error)
return NextResponse.json(
{
error: 'Failed to retrieve Outlook folders',
details: (error as Error).message,
},
{ status: 500 }
)
}
})
@@ -0,0 +1,98 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { outlookMarkReadContract } from '@/lib/api/contracts/tools/microsoft'
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'
export const dynamic = 'force-dynamic'
const logger = createLogger('OutlookMarkReadAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateRequestId()
try {
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
if (!authResult.success) {
logger.warn(`[${requestId}] Unauthorized Outlook mark read attempt: ${authResult.error}`)
return NextResponse.json(
{
success: false,
error: authResult.error || 'Authentication required',
},
{ status: 401 }
)
}
logger.info(
`[${requestId}] Authenticated Outlook mark read request via ${authResult.authType}`,
{
userId: authResult.userId,
}
)
const parsed = await parseRequest(outlookMarkReadContract, request, {})
if (!parsed.success) return parsed.response
const validatedData = parsed.data.body
logger.info(`[${requestId}] Marking Outlook email as read`, {
messageId: validatedData.messageId,
})
const graphEndpoint = `https://graph.microsoft.com/v1.0/me/messages/${validatedData.messageId}`
logger.info(`[${requestId}] Sending to Microsoft Graph API: ${graphEndpoint}`)
const graphResponse = await fetch(graphEndpoint, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${validatedData.accessToken}`,
},
body: JSON.stringify({
isRead: true,
}),
})
if (!graphResponse.ok) {
const errorData = await graphResponse.json().catch(() => ({}))
logger.error(`[${requestId}] Microsoft Graph API error:`, errorData)
return NextResponse.json(
{
success: false,
error: errorData.error?.message || 'Failed to mark email as read',
},
{ status: graphResponse.status }
)
}
const responseData = await graphResponse.json()
logger.info(`[${requestId}] Email marked as read successfully`, {
messageId: responseData.id,
isRead: responseData.isRead,
})
return NextResponse.json({
success: true,
output: {
message: 'Email marked as read successfully',
messageId: responseData.id,
isRead: responseData.isRead,
},
})
} catch (error) {
logger.error(`[${requestId}] Error marking Outlook email as read:`, error)
return NextResponse.json(
{
success: false,
error: getErrorMessage(error, 'Unknown error occurred'),
},
{ status: 500 }
)
}
})
@@ -0,0 +1,98 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { outlookMarkUnreadContract } from '@/lib/api/contracts/tools/microsoft'
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'
export const dynamic = 'force-dynamic'
const logger = createLogger('OutlookMarkUnreadAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateRequestId()
try {
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
if (!authResult.success) {
logger.warn(`[${requestId}] Unauthorized Outlook mark unread attempt: ${authResult.error}`)
return NextResponse.json(
{
success: false,
error: authResult.error || 'Authentication required',
},
{ status: 401 }
)
}
logger.info(
`[${requestId}] Authenticated Outlook mark unread request via ${authResult.authType}`,
{
userId: authResult.userId,
}
)
const parsed = await parseRequest(outlookMarkUnreadContract, request, {})
if (!parsed.success) return parsed.response
const validatedData = parsed.data.body
logger.info(`[${requestId}] Marking Outlook email as unread`, {
messageId: validatedData.messageId,
})
const graphEndpoint = `https://graph.microsoft.com/v1.0/me/messages/${validatedData.messageId}`
logger.info(`[${requestId}] Sending to Microsoft Graph API: ${graphEndpoint}`)
const graphResponse = await fetch(graphEndpoint, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${validatedData.accessToken}`,
},
body: JSON.stringify({
isRead: false,
}),
})
if (!graphResponse.ok) {
const errorData = await graphResponse.json().catch(() => ({}))
logger.error(`[${requestId}] Microsoft Graph API error:`, errorData)
return NextResponse.json(
{
success: false,
error: errorData.error?.message || 'Failed to mark email as unread',
},
{ status: graphResponse.status }
)
}
const responseData = await graphResponse.json()
logger.info(`[${requestId}] Email marked as unread successfully`, {
messageId: responseData.id,
isRead: responseData.isRead,
})
return NextResponse.json({
success: true,
output: {
message: 'Email marked as unread successfully',
messageId: responseData.id,
isRead: responseData.isRead,
},
})
} catch (error) {
logger.error(`[${requestId}] Error marking Outlook email as unread:`, error)
return NextResponse.json(
{
success: false,
error: getErrorMessage(error, 'Unknown error occurred'),
},
{ status: 500 }
)
}
})
@@ -0,0 +1,96 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { outlookMoveContract } from '@/lib/api/contracts/tools/microsoft'
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'
export const dynamic = 'force-dynamic'
const logger = createLogger('OutlookMoveAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateRequestId()
try {
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
if (!authResult.success) {
logger.warn(`[${requestId}] Unauthorized Outlook move attempt: ${authResult.error}`)
return NextResponse.json(
{
success: false,
error: authResult.error || 'Authentication required',
},
{ status: 401 }
)
}
logger.info(`[${requestId}] Authenticated Outlook move request via ${authResult.authType}`, {
userId: authResult.userId,
})
const parsed = await parseRequest(outlookMoveContract, request, {})
if (!parsed.success) return parsed.response
const validatedData = parsed.data.body
logger.info(`[${requestId}] Moving Outlook email`, {
messageId: validatedData.messageId,
destinationId: validatedData.destinationId,
})
const graphEndpoint = `https://graph.microsoft.com/v1.0/me/messages/${validatedData.messageId}/move`
logger.info(`[${requestId}] Sending to Microsoft Graph API: ${graphEndpoint}`)
const graphResponse = await fetch(graphEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${validatedData.accessToken}`,
},
body: JSON.stringify({
destinationId: validatedData.destinationId,
}),
})
if (!graphResponse.ok) {
const errorData = await graphResponse.json().catch(() => ({}))
logger.error(`[${requestId}] Microsoft Graph API error:`, errorData)
return NextResponse.json(
{
success: false,
error: errorData.error?.message || 'Failed to move email',
},
{ status: graphResponse.status }
)
}
const responseData = await graphResponse.json()
logger.info(`[${requestId}] Email moved successfully`, {
messageId: responseData.id,
parentFolderId: responseData.parentFolderId,
})
return NextResponse.json({
success: true,
output: {
message: 'Email moved successfully',
messageId: responseData.id,
newFolderId: responseData.parentFolderId,
},
})
} catch (error) {
logger.error(`[${requestId}] Error moving Outlook email:`, error)
return NextResponse.json(
{
success: false,
error: getErrorMessage(error, 'Unknown error occurred'),
},
{ status: 500 }
)
}
})
@@ -0,0 +1,216 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { outlookSendContract } from '@/lib/api/contracts/tools/microsoft'
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('OutlookSendAPI')
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 Outlook send attempt: ${authResult.error}`)
return NextResponse.json(
{
success: false,
error: authResult.error || 'Authentication required',
},
{ status: 401 }
)
}
const userId = authResult.userId
logger.info(`[${requestId}] Authenticated Outlook send request via ${authResult.authType}`, {
userId,
})
const parsed = await parseRequest(outlookSendContract, request, {})
if (!parsed.success) return parsed.response
const validatedData = parsed.data.body
logger.info(`[${requestId}] Sending Outlook email`, {
to: validatedData.to,
subject: validatedData.subject,
hasAttachments: !!(validatedData.attachments && validatedData.attachments.length > 0),
attachmentCount: validatedData.attachments?.length || 0,
})
const toRecipients = validatedData.to.split(',').map((email) => ({
emailAddress: { address: email.trim() },
}))
const ccRecipients = validatedData.cc
? validatedData.cc.split(',').map((email) => ({
emailAddress: { address: email.trim() },
}))
: undefined
const bccRecipients = validatedData.bcc
? validatedData.bcc.split(',').map((email) => ({
emailAddress: { address: email.trim() },
}))
: undefined
const message: any = {
subject: validatedData.subject,
body: {
contentType: validatedData.contentType || 'text',
content: validatedData.body,
},
toRecipients,
}
if (ccRecipients) {
message.ccRecipients = ccRecipients
}
if (bccRecipients) {
message.bccRecipients = bccRecipients
}
if (validatedData.attachments && validatedData.attachments.length > 0) {
const rawAttachments = validatedData.attachments
logger.info(`[${requestId}] Processing ${rawAttachments.length} attachment(s)`)
const attachments = processFilesToUserFiles(rawAttachments, requestId, logger)
if (attachments.length > 0) {
const totalSize = attachments.reduce((sum, file) => sum + file.size, 0)
const maxSize = 3 * 1024 * 1024 // 3MB - Microsoft Graph API limit for inline attachments
if (totalSize > maxSize) {
const sizeMB = (totalSize / (1024 * 1024)).toFixed(2)
return NextResponse.json(
{
success: false,
error: `Total attachment size (${sizeMB}MB) exceeds Microsoft Graph API limit of 3MB per request`,
},
{ status: 400 }
)
}
const accessResults = await Promise.all(
attachments.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(
attachments.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)
if (resolvedTotal > maxSize) {
const sizeMB = (resolvedTotal / (1024 * 1024)).toFixed(2)
return NextResponse.json(
{
success: false,
error: `Total attachment size (${sizeMB}MB) exceeds Microsoft Graph API limit of 3MB per request`,
},
{ status: 400 }
)
}
const attachmentObjects = attachments.map((file, i) => ({
'@odata.type': '#microsoft.graph.fileAttachment',
name: file.name,
contentType: resolved[i].contentType || file.type || 'application/octet-stream',
contentBytes: resolved[i].buffer.toString('base64'),
}))
logger.info(`[${requestId}] Converted ${attachmentObjects.length} attachments to base64`)
message.attachments = attachmentObjects
}
}
const graphEndpoint = validatedData.replyToMessageId
? `https://graph.microsoft.com/v1.0/me/messages/${validatedData.replyToMessageId}/reply`
: 'https://graph.microsoft.com/v1.0/me/sendMail'
logger.info(`[${requestId}] Sending to Microsoft Graph API: ${graphEndpoint}`)
const graphResponse = await fetch(graphEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${validatedData.accessToken}`,
},
body: JSON.stringify(
validatedData.replyToMessageId
? {
comment: validatedData.body,
message: message,
}
: {
message: message,
saveToSentItems: true,
}
),
})
if (!graphResponse.ok) {
const errorData = await graphResponse.json().catch(() => ({}))
logger.error(`[${requestId}] Microsoft Graph API error:`, errorData)
return NextResponse.json(
{
success: false,
error: errorData.error?.message || 'Failed to send email',
},
{ status: graphResponse.status }
)
}
logger.info(`[${requestId}] Email sent successfully`)
return NextResponse.json({
success: true,
output: {
message: 'Email sent successfully',
status: 'sent',
timestamp: new Date().toISOString(),
attachmentCount: message.attachments?.length || 0,
},
})
} catch (error) {
logger.error(`[${requestId}] Error sending Outlook email:`, error)
return NextResponse.json(
{
success: false,
error: getErrorMessage(error, 'Unknown error occurred'),
},
{ status: 500 }
)
}
})