d25d482dc2
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
170 lines
5.6 KiB
TypeScript
170 lines
5.6 KiB
TypeScript
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 }
|
|
)
|
|
}
|
|
})
|