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
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:
@@ -0,0 +1,124 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { jiraAddAttachmentContract } from '@/lib/api/contracts/selectors/jira'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
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'
|
||||
import { getJiraCloudId, parseAtlassianErrorMessage } from '@/tools/jira/utils'
|
||||
|
||||
const logger = createLogger('JiraAddAttachmentAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = `jira-attach-${Date.now()}`
|
||||
|
||||
try {
|
||||
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(jiraAddAttachmentContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
const validatedData = parsed.data.body
|
||||
|
||||
const userFiles = processFilesToUserFiles(validatedData.files, requestId, logger)
|
||||
if (userFiles.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'No valid files provided for upload' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const cloudId =
|
||||
validatedData.cloudId ||
|
||||
(await getJiraCloudId(validatedData.domain, validatedData.accessToken))
|
||||
|
||||
const formData = new FormData()
|
||||
|
||||
for (const file of userFiles) {
|
||||
const denied = await assertToolFileAccess(file.key, authResult.userId, requestId, logger)
|
||||
if (denied) return denied
|
||||
let buffer: Buffer
|
||||
let downloadedContentType = ''
|
||||
try {
|
||||
const result = await downloadServableFileFromStorage(file, requestId, logger)
|
||||
buffer = result.buffer
|
||||
downloadedContentType = result.contentType
|
||||
} catch (error) {
|
||||
const notReady = docNotReadyResponse(error)
|
||||
if (notReady) return notReady
|
||||
throw error
|
||||
}
|
||||
const blob = new Blob([new Uint8Array(buffer)], {
|
||||
type: downloadedContentType || file.type || 'application/octet-stream',
|
||||
})
|
||||
formData.append('file', blob, file.name)
|
||||
}
|
||||
|
||||
const url = `https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/issue/${validatedData.issueKey}/attachments`
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${validatedData.accessToken}`,
|
||||
'X-Atlassian-Token': 'no-check',
|
||||
},
|
||||
body: formData,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
logger.error(`[${requestId}] Jira attachment upload failed`, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
error: errorText,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: parseAtlassianErrorMessage(response.status, response.statusText, errorText),
|
||||
},
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const jiraAttachments = await response.json()
|
||||
const attachmentsList = Array.isArray(jiraAttachments) ? jiraAttachments : []
|
||||
|
||||
const attachmentIds = attachmentsList.map((att: any) => att.id).filter(Boolean)
|
||||
const attachments = attachmentsList.map((att: any) => ({
|
||||
id: att.id ?? '',
|
||||
filename: att.filename ?? '',
|
||||
mimeType: att.mimeType ?? '',
|
||||
size: att.size ?? 0,
|
||||
content: att.content ?? '',
|
||||
}))
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: {
|
||||
ts: new Date().toISOString(),
|
||||
issueKey: validatedData.issueKey,
|
||||
attachments,
|
||||
attachmentIds,
|
||||
files: userFiles,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Jira attachment upload error`, error)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: getErrorMessage(error, 'Internal server error') },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,237 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import {
|
||||
jiraIssueSelectorContract,
|
||||
jiraIssuesSelectorContract,
|
||||
} from '@/lib/api/contracts/selectors/jira'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { validateAlphanumericId, validateJiraCloudId } from '@/lib/core/security/input-validation'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { getJiraCloudId, parseAtlassianErrorMessage } from '@/tools/jira/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('JiraIssuesAPI')
|
||||
|
||||
const createErrorResponse = async (response: Response) => {
|
||||
const errorText = await response.text().catch(() => '')
|
||||
return parseAtlassianErrorMessage(response.status, response.statusText, errorText)
|
||||
}
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(jiraIssueSelectorContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { domain, accessToken, issueKeys, cloudId: providedCloudId } = parsed.data.body
|
||||
|
||||
if (issueKeys.length === 0) {
|
||||
logger.info('No issue keys provided, returning empty result')
|
||||
return NextResponse.json({ issues: [] })
|
||||
}
|
||||
|
||||
const ISSUE_KEY_RE = /^[A-Za-z][A-Za-z0-9_]*-\d+$/
|
||||
const sanitizedKeys: string[] = []
|
||||
for (const k of issueKeys) {
|
||||
if (typeof k !== 'string') continue
|
||||
const trimmed = k.trim()
|
||||
if (!ISSUE_KEY_RE.test(trimmed)) {
|
||||
return NextResponse.json({ error: `Invalid Jira issue key: "${trimmed}"` }, { status: 400 })
|
||||
}
|
||||
sanitizedKeys.push(trimmed)
|
||||
}
|
||||
if (sanitizedKeys.length === 0) {
|
||||
return NextResponse.json({ issues: [] })
|
||||
}
|
||||
|
||||
const cloudId = providedCloudId || (await getJiraCloudId(domain, accessToken))
|
||||
|
||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
||||
if (!cloudIdValidation.isValid) {
|
||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||
}
|
||||
|
||||
// Use search/jql endpoint (GET) with URL parameters
|
||||
const jql = `issueKey in (${sanitizedKeys.join(',')})`
|
||||
const params = new URLSearchParams({
|
||||
jql,
|
||||
fields: 'summary,status,assignee,updated,project',
|
||||
maxResults: String(Math.min(sanitizedKeys.length, 100)),
|
||||
})
|
||||
const searchUrl = `https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/search/jql?${params.toString()}`
|
||||
|
||||
const response = await fetch(searchUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
logger.error(`Jira API error: ${response.status} ${response.statusText}`)
|
||||
const errorMessage = await createErrorResponse(response)
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: errorMessage,
|
||||
authRequired: true,
|
||||
requiredScopes: ['read:jira-work'],
|
||||
},
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const issues = (data.issues || []).map((it: any) => ({
|
||||
id: it.key,
|
||||
name: it.fields?.summary || it.key,
|
||||
mimeType: 'jira/issue',
|
||||
url: `https://${domain}/browse/${it.key}`,
|
||||
modifiedTime: it.fields?.updated,
|
||||
webViewLink: `https://${domain}/browse/${it.key}`,
|
||||
}))
|
||||
|
||||
return NextResponse.json({ issues, cloudId })
|
||||
} catch (error) {
|
||||
logger.error('Error fetching Jira issues:', error)
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message || 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
export const GET = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(jiraIssuesSelectorContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const {
|
||||
domain,
|
||||
accessToken,
|
||||
cloudId: providedCloudId,
|
||||
query = '',
|
||||
projectId = '',
|
||||
manualProjectId = '',
|
||||
all,
|
||||
limit,
|
||||
} = parsed.data.query
|
||||
|
||||
const cloudId = providedCloudId || (await getJiraCloudId(domain, accessToken))
|
||||
|
||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
||||
if (!cloudIdValidation.isValid) {
|
||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||
}
|
||||
|
||||
if (projectId) {
|
||||
const projectIdValidation = validateAlphanumericId(projectId, 'projectId', 100)
|
||||
if (!projectIdValidation.isValid) {
|
||||
return NextResponse.json({ error: projectIdValidation.error }, { status: 400 })
|
||||
}
|
||||
}
|
||||
if (manualProjectId) {
|
||||
const manualProjectIdValidation = validateAlphanumericId(
|
||||
manualProjectId,
|
||||
'manualProjectId',
|
||||
100
|
||||
)
|
||||
if (!manualProjectIdValidation.isValid) {
|
||||
return NextResponse.json({ error: manualProjectIdValidation.error }, { status: 400 })
|
||||
}
|
||||
}
|
||||
|
||||
let data: any
|
||||
|
||||
if (query || projectId || manualProjectId) {
|
||||
const SAFETY_CAP = 1000
|
||||
const PAGE_SIZE = 100
|
||||
const target = Math.min(all ? limit || SAFETY_CAP : 25, SAFETY_CAP)
|
||||
const projectKey = (projectId || manualProjectId || '').trim()
|
||||
|
||||
const escapeJql = (s: string) => s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
|
||||
|
||||
const buildUrl = (token?: string) => {
|
||||
const jqlParts: string[] = []
|
||||
if (projectKey) jqlParts.push(`project = "${escapeJql(projectKey)}"`)
|
||||
if (query) {
|
||||
const q = escapeJql(query)
|
||||
jqlParts.push(`(key ~ "${q}" OR summary ~ "${q}")`)
|
||||
}
|
||||
const jql = `${jqlParts.length ? `${jqlParts.join(' AND ')} ` : ''}ORDER BY updated DESC`
|
||||
const params = new URLSearchParams({
|
||||
jql,
|
||||
fields: 'summary,key,updated',
|
||||
maxResults: String(Math.min(PAGE_SIZE, target)),
|
||||
})
|
||||
if (token) params.set('nextPageToken', token)
|
||||
return `https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/search/jql?${params.toString()}`
|
||||
}
|
||||
|
||||
let nextPageToken: string | undefined
|
||||
let collected: any[] = []
|
||||
|
||||
do {
|
||||
const apiUrl = buildUrl(nextPageToken)
|
||||
const response = await fetch(apiUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMessage = await createErrorResponse(response)
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: errorMessage,
|
||||
authRequired: true,
|
||||
requiredScopes: ['read:jira-work'],
|
||||
},
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
||||
}
|
||||
|
||||
const page = await response.json()
|
||||
const issues = page.issues || []
|
||||
collected = collected.concat(issues)
|
||||
nextPageToken = page.nextPageToken
|
||||
if (!nextPageToken || issues.length === 0) break
|
||||
} while (all && collected.length < target)
|
||||
|
||||
const issues = collected.slice(0, target).map((it: any) => ({
|
||||
key: it.key,
|
||||
summary: it.fields?.summary || it.key,
|
||||
}))
|
||||
data = { sections: [{ issues }], cloudId }
|
||||
} else {
|
||||
data = { sections: [], cloudId }
|
||||
}
|
||||
|
||||
return NextResponse.json({ ...data, cloudId })
|
||||
} catch (error) {
|
||||
logger.error('Error fetching Jira issue suggestions:', error)
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message || 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,251 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import {
|
||||
jiraProjectSelectorContract,
|
||||
jiraProjectsSelectorContract,
|
||||
} from '@/lib/api/contracts/selectors/jira'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { validateAlphanumericId, validateJiraCloudId } from '@/lib/core/security/input-validation'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { getJiraCloudId, parseAtlassianErrorMessage } from '@/tools/jira/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('JiraProjectsAPI')
|
||||
|
||||
const JIRA_PROJECTS_PAGE_SIZE = 50
|
||||
const MAX_JIRA_PROJECTS_PAGES = 40
|
||||
|
||||
interface JiraProjectSearchPage {
|
||||
values?: unknown[]
|
||||
isLast?: boolean
|
||||
maxResults?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Drains the offset-paginated Jira `/project/search` endpoint, advancing
|
||||
* `startAt` by the server-returned page size until `isLast === true` (or a short
|
||||
* page is seen). Bounded by `MAX_JIRA_PROJECTS_PAGES`; emits a `logger.warn` and
|
||||
* returns the partial set rather than looping unbounded when the cap is hit.
|
||||
*/
|
||||
async function fetchAllJiraProjects(
|
||||
apiUrl: string,
|
||||
baseParams: URLSearchParams,
|
||||
accessToken: string
|
||||
): Promise<{ values: unknown[]; lastResponse: Response }> {
|
||||
const values: unknown[] = []
|
||||
let startAt = 0
|
||||
let lastResponse: Response
|
||||
|
||||
for (let page = 0; page < MAX_JIRA_PROJECTS_PAGES; page++) {
|
||||
const params = new URLSearchParams(baseParams)
|
||||
params.set('startAt', String(startAt))
|
||||
params.set('maxResults', String(JIRA_PROJECTS_PAGE_SIZE))
|
||||
|
||||
const finalUrl = `${apiUrl}?${params.toString()}`
|
||||
logger.info(`Fetching Jira projects from: ${finalUrl}`)
|
||||
|
||||
const response = await fetch(finalUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
logger.info(`Response status: ${response.status} ${response.statusText}`)
|
||||
|
||||
if (!response.ok) {
|
||||
return { values, lastResponse: response }
|
||||
}
|
||||
|
||||
const data = (await response.json()) as JiraProjectSearchPage
|
||||
lastResponse = response
|
||||
|
||||
const pageValues = data.values ?? []
|
||||
values.push(...pageValues)
|
||||
|
||||
const pageSize =
|
||||
data.maxResults && data.maxResults > 0 ? data.maxResults : JIRA_PROJECTS_PAGE_SIZE
|
||||
if (data.isLast === true || pageValues.length < pageSize) {
|
||||
return { values, lastResponse }
|
||||
}
|
||||
|
||||
startAt += pageValues.length
|
||||
|
||||
if (page === MAX_JIRA_PROJECTS_PAGES - 1) {
|
||||
logger.warn('Jira project search hit pagination cap; project list may be incomplete', {
|
||||
pages: MAX_JIRA_PROJECTS_PAGES,
|
||||
collected: values.length,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return { values, lastResponse: lastResponse! }
|
||||
}
|
||||
|
||||
export const GET = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(jiraProjectsSelectorContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { domain, accessToken, cloudId: providedCloudId, query = '' } = parsed.data.query
|
||||
|
||||
if (!domain) {
|
||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!accessToken) {
|
||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const cloudId = providedCloudId || (await getJiraCloudId(domain, accessToken))
|
||||
logger.info(`Using cloud ID: ${cloudId}`)
|
||||
|
||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
||||
if (!cloudIdValidation.isValid) {
|
||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||
}
|
||||
|
||||
const apiUrl = `https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/project/search`
|
||||
|
||||
const queryParams = new URLSearchParams()
|
||||
if (query) {
|
||||
queryParams.append('query', query)
|
||||
}
|
||||
queryParams.append('orderBy', 'name')
|
||||
queryParams.append('expand', 'description,lead,url,projectKeys')
|
||||
|
||||
const { values, lastResponse } = await fetchAllJiraProjects(apiUrl, queryParams, accessToken)
|
||||
|
||||
if (!lastResponse.ok) {
|
||||
const errorText = await lastResponse.text()
|
||||
logger.error('Jira API error:', { status: lastResponse.status, error: errorText })
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: parseAtlassianErrorMessage(
|
||||
lastResponse.status,
|
||||
lastResponse.statusText,
|
||||
errorText
|
||||
),
|
||||
},
|
||||
{ status: lastResponse.status }
|
||||
)
|
||||
}
|
||||
|
||||
logger.info(`Jira API Response Status: ${lastResponse.status}`)
|
||||
logger.info(`Found projects: ${values.length}`)
|
||||
|
||||
const projects =
|
||||
values.map((project: any) => ({
|
||||
id: project.id,
|
||||
key: project.key,
|
||||
name: project.name,
|
||||
url: project.self,
|
||||
avatarUrl: project.avatarUrls?.['48x48'],
|
||||
description: project.description,
|
||||
projectTypeKey: project.projectTypeKey,
|
||||
simplified: project.simplified,
|
||||
style: project.style,
|
||||
isPrivate: project.isPrivate,
|
||||
})) || []
|
||||
|
||||
return NextResponse.json({
|
||||
projects,
|
||||
cloudId,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Error fetching Jira projects:', error)
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message || 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(jiraProjectSelectorContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { domain, accessToken, projectId, cloudId: providedCloudId } = parsed.data.body
|
||||
|
||||
if (!domain) {
|
||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!accessToken) {
|
||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!projectId) {
|
||||
return NextResponse.json({ error: 'Project ID is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const cloudId = providedCloudId || (await getJiraCloudId(domain, accessToken))
|
||||
|
||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
||||
if (!cloudIdValidation.isValid) {
|
||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||
}
|
||||
|
||||
const projectIdValidation = validateAlphanumericId(projectId, 'projectId', 100)
|
||||
if (!projectIdValidation.isValid) {
|
||||
return NextResponse.json({ error: projectIdValidation.error }, { status: 400 })
|
||||
}
|
||||
|
||||
const apiUrl = `https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/project/${projectId}`
|
||||
|
||||
const response = await fetch(apiUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
logger.error('Jira API error:', { status: response.status, error: errorText })
|
||||
return NextResponse.json(
|
||||
{ error: parseAtlassianErrorMessage(response.status, response.statusText, errorText) },
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const project = await response.json()
|
||||
|
||||
return NextResponse.json({
|
||||
project: {
|
||||
id: project.id,
|
||||
key: project.key,
|
||||
name: project.name,
|
||||
url: project.self,
|
||||
avatarUrl: project.avatarUrls?.['48x48'],
|
||||
description: project.description,
|
||||
projectTypeKey: project.projectTypeKey,
|
||||
simplified: project.simplified,
|
||||
style: project.style,
|
||||
isPrivate: project.isPrivate,
|
||||
},
|
||||
cloudId,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Error fetching Jira project:', error)
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message || 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage, toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { jiraUpdateContract } from '@/lib/api/contracts/selectors/jira'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { validateJiraCloudId, validateJiraIssueKey } from '@/lib/core/security/input-validation'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { getJiraCloudId, parseAtlassianErrorMessage, toAdf } from '@/tools/jira/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('JiraUpdateAPI')
|
||||
|
||||
export const PUT = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(jiraUpdateContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const {
|
||||
domain,
|
||||
accessToken,
|
||||
issueKey,
|
||||
summary,
|
||||
title,
|
||||
description,
|
||||
priority,
|
||||
assignee,
|
||||
labels,
|
||||
components,
|
||||
duedate,
|
||||
fixVersions,
|
||||
environment,
|
||||
customFieldId,
|
||||
customFieldValue,
|
||||
notifyUsers,
|
||||
cloudId: providedCloudId,
|
||||
} = parsed.data.body
|
||||
|
||||
const cloudId = providedCloudId || (await getJiraCloudId(domain, accessToken))
|
||||
logger.info('Using cloud ID:', cloudId)
|
||||
|
||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
||||
if (!cloudIdValidation.isValid) {
|
||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||
}
|
||||
|
||||
const issueKeyValidation = validateJiraIssueKey(issueKey, 'issueKey')
|
||||
if (!issueKeyValidation.isValid) {
|
||||
return NextResponse.json({ error: issueKeyValidation.error }, { status: 400 })
|
||||
}
|
||||
|
||||
const notifyParam =
|
||||
notifyUsers === false ? '?notifyUsers=false' : notifyUsers === true ? '?notifyUsers=true' : ''
|
||||
const url = `https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/issue/${issueKey}${notifyParam}`
|
||||
|
||||
logger.info('Updating Jira issue at:', url)
|
||||
|
||||
const summaryValue = summary || title
|
||||
const fields: Record<string, any> = {}
|
||||
|
||||
if (summaryValue !== undefined && summaryValue !== null && summaryValue !== '') {
|
||||
fields.summary = summaryValue
|
||||
}
|
||||
|
||||
if (description !== undefined && description !== null && description !== '') {
|
||||
fields.description = toAdf(description)
|
||||
}
|
||||
|
||||
if (priority !== undefined && priority !== null && priority !== '') {
|
||||
const isNumericId = /^\d+$/.test(priority)
|
||||
fields.priority = isNumericId ? { id: priority } : { name: priority }
|
||||
}
|
||||
|
||||
if (assignee !== undefined && assignee !== null && assignee !== '') {
|
||||
fields.assignee = {
|
||||
accountId: assignee,
|
||||
}
|
||||
}
|
||||
|
||||
if (labels !== undefined && labels !== null && labels.length > 0) {
|
||||
fields.labels = labels
|
||||
}
|
||||
|
||||
if (components !== undefined && components !== null && components.length > 0) {
|
||||
fields.components = components.map((name) => ({ name }))
|
||||
}
|
||||
|
||||
if (duedate !== undefined && duedate !== null && duedate !== '') {
|
||||
fields.duedate = duedate
|
||||
}
|
||||
|
||||
if (fixVersions !== undefined && fixVersions !== null && fixVersions.length > 0) {
|
||||
fields.fixVersions = fixVersions.map((name) => ({ name }))
|
||||
}
|
||||
|
||||
if (environment !== undefined && environment !== null && environment !== '') {
|
||||
fields.environment = toAdf(environment)
|
||||
}
|
||||
|
||||
if (
|
||||
customFieldId !== undefined &&
|
||||
customFieldId !== null &&
|
||||
customFieldId !== '' &&
|
||||
customFieldValue !== undefined &&
|
||||
customFieldValue !== null &&
|
||||
customFieldValue !== ''
|
||||
) {
|
||||
const fieldId = customFieldId.startsWith('customfield_')
|
||||
? customFieldId
|
||||
: `customfield_${customFieldId}`
|
||||
fields[fieldId] = customFieldValue
|
||||
}
|
||||
|
||||
const requestBody = { fields }
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
logger.error('Jira API error:', {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
error: errorText,
|
||||
})
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: parseAtlassianErrorMessage(response.status, response.statusText, errorText),
|
||||
details: errorText,
|
||||
},
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const responseData =
|
||||
response.status === 204 ? {} : await response.json().catch(() => ({}) as Record<string, any>)
|
||||
logger.info('Successfully updated Jira issue:', issueKey)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: {
|
||||
ts: new Date().toISOString(),
|
||||
issueKey: responseData.key || issueKey,
|
||||
summary: responseData.fields?.summary || summaryValue || 'Issue updated',
|
||||
success: true,
|
||||
},
|
||||
})
|
||||
} catch (error: any) {
|
||||
logger.error('Error updating Jira issue:', {
|
||||
error: toError(error).message,
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
})
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: getErrorMessage(error, 'Internal server error'),
|
||||
success: false,
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,251 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage, toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { jiraWriteContract } from '@/lib/api/contracts/selectors/jira'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { validateAlphanumericId, validateJiraCloudId } from '@/lib/core/security/input-validation'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { getJiraCloudId, parseAtlassianErrorMessage, toAdf } from '@/tools/jira/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('JiraWriteAPI')
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(jiraWriteContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const {
|
||||
domain,
|
||||
accessToken,
|
||||
projectId,
|
||||
summary,
|
||||
description,
|
||||
priority,
|
||||
assignee,
|
||||
cloudId: providedCloudId,
|
||||
issueType,
|
||||
parent,
|
||||
labels,
|
||||
duedate,
|
||||
reporter,
|
||||
environment,
|
||||
customFieldId,
|
||||
customFieldValue,
|
||||
components,
|
||||
fixVersions,
|
||||
} = parsed.data.body
|
||||
|
||||
if (!domain) {
|
||||
logger.error('Missing domain in request')
|
||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!accessToken) {
|
||||
logger.error('Missing access token in request')
|
||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!projectId) {
|
||||
logger.error('Missing project ID in request')
|
||||
return NextResponse.json({ error: 'Project ID is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!summary) {
|
||||
logger.error('Missing summary in request')
|
||||
return NextResponse.json({ error: 'Summary is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const normalizedIssueType = issueType || 'Task'
|
||||
|
||||
const cloudId = providedCloudId || (await getJiraCloudId(domain, accessToken))
|
||||
logger.info('Using cloud ID:', cloudId)
|
||||
|
||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
||||
if (!cloudIdValidation.isValid) {
|
||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||
}
|
||||
|
||||
const projectIdValidation = validateAlphanumericId(projectId, 'projectId', 100)
|
||||
if (!projectIdValidation.isValid) {
|
||||
return NextResponse.json({ error: projectIdValidation.error }, { status: 400 })
|
||||
}
|
||||
|
||||
const url = `https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/issue`
|
||||
|
||||
logger.info('Creating Jira issue at:', url)
|
||||
|
||||
const isNumericProjectId = /^\d+$/.test(projectId)
|
||||
const fields: Record<string, any> = {
|
||||
project: isNumericProjectId ? { id: projectId } : { key: projectId },
|
||||
issuetype: {
|
||||
name: normalizedIssueType,
|
||||
},
|
||||
summary: summary,
|
||||
}
|
||||
|
||||
if (description !== undefined && description !== null && description !== '') {
|
||||
fields.description = toAdf(description)
|
||||
}
|
||||
|
||||
if (parent !== undefined && parent !== null && parent !== '') {
|
||||
if (typeof parent === 'string') {
|
||||
fields.parent = /^\d+$/.test(parent) ? { id: parent } : { key: parent }
|
||||
} else if (typeof parent === 'object') {
|
||||
fields.parent = parent
|
||||
}
|
||||
}
|
||||
|
||||
if (priority !== undefined && priority !== null && priority !== '') {
|
||||
const isNumericId = /^\d+$/.test(priority)
|
||||
fields.priority = isNumericId ? { id: priority } : { name: priority }
|
||||
}
|
||||
|
||||
if (labels !== undefined && labels !== null && Array.isArray(labels) && labels.length > 0) {
|
||||
fields.labels = labels
|
||||
}
|
||||
|
||||
if (
|
||||
components !== undefined &&
|
||||
components !== null &&
|
||||
Array.isArray(components) &&
|
||||
components.length > 0
|
||||
) {
|
||||
fields.components = components.map((name: string) => ({ name }))
|
||||
}
|
||||
|
||||
if (duedate !== undefined && duedate !== null && duedate !== '') {
|
||||
fields.duedate = duedate
|
||||
}
|
||||
|
||||
if (
|
||||
fixVersions !== undefined &&
|
||||
fixVersions !== null &&
|
||||
Array.isArray(fixVersions) &&
|
||||
fixVersions.length > 0
|
||||
) {
|
||||
fields.fixVersions = fixVersions.map((name: string) => ({ name }))
|
||||
}
|
||||
|
||||
if (reporter !== undefined && reporter !== null && reporter !== '') {
|
||||
fields.reporter = {
|
||||
accountId: reporter,
|
||||
}
|
||||
}
|
||||
|
||||
if (environment !== undefined && environment !== null && environment !== '') {
|
||||
fields.environment = toAdf(environment)
|
||||
}
|
||||
|
||||
if (
|
||||
customFieldId !== undefined &&
|
||||
customFieldId !== null &&
|
||||
customFieldId !== '' &&
|
||||
customFieldValue !== undefined &&
|
||||
customFieldValue !== null &&
|
||||
customFieldValue !== ''
|
||||
) {
|
||||
const fieldId = customFieldId.startsWith('customfield_')
|
||||
? customFieldId
|
||||
: `customfield_${customFieldId}`
|
||||
|
||||
fields[fieldId] = customFieldValue
|
||||
}
|
||||
|
||||
const body = { fields }
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
logger.error('Jira API error:', {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
error: errorText,
|
||||
})
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: parseAtlassianErrorMessage(response.status, response.statusText, errorText),
|
||||
details: errorText,
|
||||
},
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const responseData = await response.json()
|
||||
const issueKey = responseData.key || 'unknown'
|
||||
logger.info('Successfully created Jira issue:', issueKey)
|
||||
|
||||
let assigneeId: string | undefined
|
||||
if (assignee !== undefined && assignee !== null && assignee !== '') {
|
||||
const assignUrl = `https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/issue/${issueKey}/assignee`
|
||||
logger.info('Assigning issue to:', assignee)
|
||||
|
||||
const assignResponse = await fetch(assignUrl, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
accountId: assignee,
|
||||
}),
|
||||
})
|
||||
|
||||
if (!assignResponse.ok) {
|
||||
const assignErrorText = await assignResponse.text()
|
||||
logger.warn('Failed to assign issue (issue was created successfully):', {
|
||||
status: assignResponse.status,
|
||||
error: assignErrorText,
|
||||
})
|
||||
} else {
|
||||
assigneeId = assignee
|
||||
logger.info('Successfully assigned issue to:', assignee)
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: {
|
||||
ts: new Date().toISOString(),
|
||||
id: responseData.id || '',
|
||||
issueKey: issueKey,
|
||||
self: responseData.self || '',
|
||||
summary: responseData.fields?.summary || summary || 'Issue created',
|
||||
success: true,
|
||||
url: `https://${domain}/browse/${issueKey}`,
|
||||
...(assigneeId && { assigneeId }),
|
||||
},
|
||||
})
|
||||
} catch (error: any) {
|
||||
logger.error('Error creating Jira issue:', {
|
||||
error: toError(error).message,
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
})
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: getErrorMessage(error, 'Internal server error'),
|
||||
success: false,
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user