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,147 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import {
|
||||
createMockRequest,
|
||||
hybridAuthMockFns,
|
||||
inputValidationMock,
|
||||
inputValidationMockFns,
|
||||
} from '@sim/testing'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { mockProcessFilesToUserFiles, mockDownloadFileFromStorage, mockAssertToolFileAccess } =
|
||||
vi.hoisted(() => ({
|
||||
mockProcessFilesToUserFiles: vi.fn(),
|
||||
mockDownloadFileFromStorage: vi.fn(),
|
||||
mockAssertToolFileAccess: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock)
|
||||
vi.mock('@/lib/uploads/utils/file-utils', () => ({
|
||||
processFilesToUserFiles: mockProcessFilesToUserFiles,
|
||||
}))
|
||||
vi.mock('@/lib/uploads/utils/file-utils.server', () => ({
|
||||
downloadServableFileFromStorage: mockDownloadFileFromStorage,
|
||||
}))
|
||||
vi.mock('@/app/api/files/authorization', () => ({
|
||||
assertToolFileAccess: mockAssertToolFileAccess,
|
||||
}))
|
||||
|
||||
import { POST } from '@/app/api/tools/agiloft/attach/route'
|
||||
|
||||
const PINNED_IP = '93.184.216.34'
|
||||
|
||||
const baseBody = {
|
||||
instanceUrl: 'https://example.agiloft.com',
|
||||
knowledgeBase: 'demo',
|
||||
login: 'admin',
|
||||
password: 'secret',
|
||||
table: 'contracts',
|
||||
recordId: '42',
|
||||
fieldName: 'attachments',
|
||||
file: { key: 's3://bucket/file.txt', name: 'file.txt', size: 5, type: 'text/plain' },
|
||||
fileName: 'file.txt',
|
||||
}
|
||||
|
||||
function mockSecureFetchResponse(body: {
|
||||
ok?: boolean
|
||||
status?: number
|
||||
json?: unknown
|
||||
text?: string
|
||||
}) {
|
||||
return {
|
||||
ok: body.ok ?? true,
|
||||
status: body.status ?? 200,
|
||||
statusText: '',
|
||||
headers: new Headers(),
|
||||
body: null,
|
||||
text: async () => body.text ?? '',
|
||||
json: async () => body.json ?? {},
|
||||
arrayBuffer: async () => new ArrayBuffer(0),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
hybridAuthMockFns.mockCheckInternalAuth.mockResolvedValue({
|
||||
success: true,
|
||||
userId: 'user-1',
|
||||
authType: 'internal_jwt',
|
||||
})
|
||||
inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValue({
|
||||
isValid: true,
|
||||
resolvedIP: PINNED_IP,
|
||||
originalHostname: 'example.agiloft.com',
|
||||
})
|
||||
mockProcessFilesToUserFiles.mockReturnValue([
|
||||
{ key: 's3://bucket/file.txt', name: 'file.txt', size: 5, type: 'text/plain' },
|
||||
])
|
||||
mockAssertToolFileAccess.mockResolvedValue(null)
|
||||
mockDownloadFileFromStorage.mockResolvedValue({
|
||||
buffer: Buffer.from('hello'),
|
||||
contentType: 'application/octet-stream',
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/tools/agiloft/attach', () => {
|
||||
it('rejects unauthenticated requests', async () => {
|
||||
hybridAuthMockFns.mockCheckInternalAuth.mockResolvedValueOnce({
|
||||
success: false,
|
||||
error: 'unauthorized',
|
||||
})
|
||||
|
||||
const response = await POST(createMockRequest('POST', baseBody))
|
||||
expect(response.status).toBe(401)
|
||||
expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks SSRF when the instance URL fails DNS validation', async () => {
|
||||
inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValueOnce({
|
||||
isValid: false,
|
||||
error: 'instanceUrl resolves to a blocked IP address',
|
||||
})
|
||||
|
||||
const response = await POST(
|
||||
createMockRequest('POST', { ...baseBody, instanceUrl: 'https://attacker.example.com' })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('pins the resolved IP for login, attach, and logout (TOCTOU fix)', async () => {
|
||||
inputValidationMockFns.mockSecureFetchWithPinnedIP
|
||||
.mockResolvedValueOnce(mockSecureFetchResponse({ json: { access_token: 'tok-att' } }))
|
||||
.mockResolvedValueOnce(mockSecureFetchResponse({ text: '1' }))
|
||||
.mockResolvedValueOnce(mockSecureFetchResponse({}))
|
||||
|
||||
const response = await POST(createMockRequest('POST', baseBody))
|
||||
expect(response.status).toBe(200)
|
||||
const data = (await response.json()) as {
|
||||
success: true
|
||||
output: { totalAttachments: number; fileName: string }
|
||||
}
|
||||
expect(data.output.totalAttachments).toBe(1)
|
||||
expect(data.output.fileName).toBe('file.txt')
|
||||
|
||||
const calls = inputValidationMockFns.mockSecureFetchWithPinnedIP.mock.calls
|
||||
expect(calls).toHaveLength(3)
|
||||
for (const call of calls) {
|
||||
expect(call[1]).toBe(PINNED_IP)
|
||||
}
|
||||
|
||||
expect(calls[0][0]).toContain('https://example.agiloft.com/ewws/EWLogin')
|
||||
expect(calls[1][0]).toContain('https://example.agiloft.com/ewws/EWAttach')
|
||||
expect(calls[1][2]).toMatchObject({
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: 'Bearer tok-att',
|
||||
'Content-Type': 'application/octet-stream',
|
||||
},
|
||||
})
|
||||
expect(calls[2][0]).toContain('https://example.agiloft.com/ewws/EWLogout')
|
||||
|
||||
// DNS only resolved once.
|
||||
expect(inputValidationMockFns.mockValidateUrlWithDNS).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,161 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftAttachContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { secureFetchWithPinnedIP } from '@/lib/core/security/input-validation.server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import type { RawFileInput } from '@/lib/uploads/utils/file-schemas'
|
||||
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 { buildAttachFileUrl } from '@/tools/agiloft/utils'
|
||||
import {
|
||||
agiloftLoginPinned,
|
||||
agiloftLogoutPinned,
|
||||
resolveAgiloftInstance,
|
||||
} from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftAttachAPI')
|
||||
|
||||
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 Agiloft attach attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftAttachContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const data = parsed.data.body
|
||||
|
||||
if (!data.file) {
|
||||
return NextResponse.json({ success: false, error: 'File is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const userFiles = processFilesToUserFiles([data.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 file for Agiloft attach: ${userFile.name} (${userFile.size} bytes)`
|
||||
)
|
||||
|
||||
const denied = await assertToolFileAccess(userFile.key, authResult.userId, requestId, logger)
|
||||
if (denied) return denied
|
||||
|
||||
let fileBuffer: Buffer
|
||||
try {
|
||||
const servable = await downloadServableFileFromStorage(userFile, requestId, logger)
|
||||
fileBuffer = servable.buffer
|
||||
} catch (error) {
|
||||
const notReady = docNotReadyResponse(error)
|
||||
if (notReady) return notReady
|
||||
logger.error(`[${requestId}] Failed to download file from storage:`, error)
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
|
||||
const resolvedFileName = data.fileName || userFile.name || 'attachment'
|
||||
|
||||
let resolvedIP: string
|
||||
try {
|
||||
resolvedIP = await resolveAgiloftInstance(data.instanceUrl)
|
||||
} catch (error) {
|
||||
logger.warn(`[${requestId}] SSRF attempt blocked for Agiloft instance URL`, {
|
||||
instanceUrl: data.instanceUrl,
|
||||
})
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 400 })
|
||||
}
|
||||
|
||||
const token = await agiloftLoginPinned(data, resolvedIP)
|
||||
const base = data.instanceUrl.replace(/\/$/, '')
|
||||
|
||||
try {
|
||||
const url = buildAttachFileUrl(base, data, resolvedFileName)
|
||||
|
||||
logger.info(`[${requestId}] Uploading file to Agiloft: ${resolvedFileName}`)
|
||||
|
||||
const agiloftResponse = await secureFetchWithPinnedIP(url, resolvedIP, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: new Uint8Array(fileBuffer),
|
||||
})
|
||||
|
||||
if (!agiloftResponse.ok) {
|
||||
const errorText = await agiloftResponse.text()
|
||||
logger.error(
|
||||
`[${requestId}] Agiloft attach error: ${agiloftResponse.status} - ${errorText}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: `Agiloft error: ${agiloftResponse.status} - ${errorText}` },
|
||||
{ status: agiloftResponse.status }
|
||||
)
|
||||
}
|
||||
|
||||
let totalAttachments = 0
|
||||
const responseText = await agiloftResponse.text()
|
||||
try {
|
||||
const responseData = JSON.parse(responseText)
|
||||
const result = responseData.result ?? responseData
|
||||
totalAttachments = typeof result === 'number' ? result : (result.count ?? result.total ?? 1)
|
||||
} catch {
|
||||
totalAttachments = Number(responseText) || 1
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] File attached successfully. Total attachments: ${totalAttachments}`
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: {
|
||||
recordId: data.recordId.trim(),
|
||||
fieldName: data.fieldName.trim(),
|
||||
fileName: resolvedFileName,
|
||||
totalAttachments,
|
||||
},
|
||||
})
|
||||
} finally {
|
||||
await agiloftLogoutPinned(data.instanceUrl, data.knowledgeBase, token, resolvedIP)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error attaching file to Agiloft:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftAttachmentInfoContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, 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 type { AgiloftAttachmentInfoResponse } from '@/tools/agiloft/types'
|
||||
import { buildAttachmentInfoUrl } from '@/tools/agiloft/utils'
|
||||
import { executeAgiloftRequest } from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftAttachmentInfoAPI')
|
||||
|
||||
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 Agiloft attachment_info attempt: ${authResult.error}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftAttachmentInfoContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const result = await executeAgiloftRequest<AgiloftAttachmentInfoResponse>(
|
||||
params,
|
||||
(base) => ({
|
||||
url: buildAttachmentInfoUrl(base, params),
|
||||
method: 'GET',
|
||||
}),
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
return {
|
||||
success: false,
|
||||
output: { attachments: [], totalCount: 0 },
|
||||
error: `Agiloft error: ${response.status} - ${errorText}`,
|
||||
}
|
||||
}
|
||||
|
||||
const data = (await response.json()) as Record<string, unknown>
|
||||
const result = (data.result ?? data) as Record<string, unknown>
|
||||
|
||||
const attachments: Array<{ position: number; name: string; size: number }> = []
|
||||
|
||||
if (Array.isArray(result)) {
|
||||
for (let i = 0; i < result.length; i++) {
|
||||
const item = result[i] as Record<string, unknown>
|
||||
attachments.push({
|
||||
position: (item.filePosition as number) ?? (item.position as number) ?? i,
|
||||
name:
|
||||
(item.fileName as string) ??
|
||||
(item.name as string) ??
|
||||
(item.filename as string) ??
|
||||
'',
|
||||
size: (item.size as number) ?? (item.fileSize as number) ?? 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: data.success !== false,
|
||||
output: {
|
||||
attachments,
|
||||
totalCount: attachments.length,
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return NextResponse.json(result)
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error getting Agiloft attachment info:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftCreateRecordContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, 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 type { AgiloftRecordResponse } from '@/tools/agiloft/types'
|
||||
import { buildCreateRecordUrl } from '@/tools/agiloft/utils'
|
||||
import { executeAgiloftRequest } from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftCreateRecordAPI')
|
||||
|
||||
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 Agiloft create_record attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftCreateRecordContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
let body: string
|
||||
try {
|
||||
body = JSON.stringify(JSON.parse(params.data))
|
||||
} catch {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: { id: null, fields: {} },
|
||||
error: 'Invalid JSON in data parameter',
|
||||
})
|
||||
}
|
||||
|
||||
const result = await executeAgiloftRequest<AgiloftRecordResponse>(
|
||||
params,
|
||||
(base) => ({
|
||||
url: buildCreateRecordUrl(base, params),
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body,
|
||||
}),
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
return {
|
||||
success: false,
|
||||
output: { id: null, fields: {} },
|
||||
error: `Agiloft error: ${response.status} - ${errorText}`,
|
||||
}
|
||||
}
|
||||
|
||||
const data = (await response.json()) as Record<string, unknown>
|
||||
const result = (data.result ?? data) as Record<string, unknown>
|
||||
const id = result.id ?? result.ID ?? data.id ?? data.ID ?? null
|
||||
|
||||
return {
|
||||
success: data.success !== false,
|
||||
output: {
|
||||
id: id != null ? String(id) : null,
|
||||
fields: result ?? {},
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return NextResponse.json(result)
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error creating Agiloft record:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftDeleteRecordContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, 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 type { AgiloftDeleteResponse } from '@/tools/agiloft/types'
|
||||
import { buildDeleteRecordUrl } from '@/tools/agiloft/utils'
|
||||
import { executeAgiloftRequest } from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftDeleteRecordAPI')
|
||||
|
||||
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 Agiloft delete_record attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftDeleteRecordContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const result = await executeAgiloftRequest<AgiloftDeleteResponse>(
|
||||
params,
|
||||
(base) => ({
|
||||
url: buildDeleteRecordUrl(base, params),
|
||||
method: 'DELETE',
|
||||
headers: { Accept: 'application/json' },
|
||||
}),
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
return {
|
||||
success: false,
|
||||
output: { id: params.recordId?.trim() ?? '', deleted: false },
|
||||
error: `Agiloft error: ${response.status} - ${errorText}`,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
output: {
|
||||
id: params.recordId?.trim() ?? '',
|
||||
deleted: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return NextResponse.json(result)
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error deleting Agiloft record:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftGetChoiceLineIdContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, 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 type { AgiloftGetChoiceLineIdResponse } from '@/tools/agiloft/types'
|
||||
import { buildGetChoiceLineIdUrl } from '@/tools/agiloft/utils'
|
||||
import { executeAgiloftRequest } from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftGetChoiceLineIdAPI')
|
||||
|
||||
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 Agiloft get_choice_line_id attempt: ${authResult.error}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftGetChoiceLineIdContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const result = await executeAgiloftRequest<AgiloftGetChoiceLineIdResponse>(
|
||||
params,
|
||||
(base) => ({
|
||||
url: buildGetChoiceLineIdUrl(base, params),
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json' },
|
||||
}),
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
return {
|
||||
success: false,
|
||||
output: { choiceLineId: null },
|
||||
error: `Agiloft error: ${response.status} - ${errorText}`,
|
||||
}
|
||||
}
|
||||
|
||||
const data = (await response.json()) as Record<string, unknown>
|
||||
const result = data.result ?? data
|
||||
let choiceLineId: number | null = null
|
||||
|
||||
if (typeof result === 'number') {
|
||||
choiceLineId = result
|
||||
} else if (typeof result === 'string') {
|
||||
const parsed = Number(result)
|
||||
choiceLineId = Number.isFinite(parsed) ? parsed : null
|
||||
} else if (typeof result === 'object' && result !== null) {
|
||||
const obj = result as Record<string, unknown>
|
||||
const idVal = obj.id ?? obj.choiceLineId ?? obj.lineId
|
||||
if (typeof idVal === 'number') {
|
||||
choiceLineId = idVal
|
||||
} else if (typeof idVal === 'string') {
|
||||
const parsed = Number(idVal)
|
||||
choiceLineId = Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
}
|
||||
|
||||
if (choiceLineId === null) {
|
||||
return {
|
||||
success: false,
|
||||
output: { choiceLineId: null },
|
||||
error: `No choice line ID found for value "${params.value}" in field "${params.fieldName}"`,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: data.success !== false,
|
||||
output: { choiceLineId },
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return NextResponse.json(result)
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error getting Agiloft choice line ID:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,99 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftLockRecordContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, 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 type { AgiloftLockResponse } from '@/tools/agiloft/types'
|
||||
import { buildLockRecordUrl, getLockHttpMethod } from '@/tools/agiloft/utils'
|
||||
import { executeAgiloftRequest } from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftLockRecordAPI')
|
||||
|
||||
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 Agiloft lock_record attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftLockRecordContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const result = await executeAgiloftRequest<AgiloftLockResponse>(
|
||||
params,
|
||||
(base) => ({
|
||||
url: buildLockRecordUrl(base, params),
|
||||
method: getLockHttpMethod(params.lockAction),
|
||||
}),
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
return {
|
||||
success: false,
|
||||
output: {
|
||||
id: params.recordId?.trim() ?? '',
|
||||
lockStatus: 'UNKNOWN',
|
||||
lockedBy: null,
|
||||
lockExpiresInMinutes: null,
|
||||
},
|
||||
error: `Agiloft error: ${response.status} - ${errorText}`,
|
||||
}
|
||||
}
|
||||
|
||||
const data = (await response.json()) as Record<string, unknown>
|
||||
const result = (data.result ?? data) as Record<string, unknown>
|
||||
|
||||
return {
|
||||
success: data.success !== false,
|
||||
output: {
|
||||
id: String(result.id ?? params.recordId?.trim() ?? ''),
|
||||
lockStatus:
|
||||
(result.lock_status as string) ?? (result.lockStatus as string) ?? 'UNKNOWN',
|
||||
lockedBy:
|
||||
(result.locked_by as string | null) ?? (result.lockedBy as string | null) ?? null,
|
||||
lockExpiresInMinutes:
|
||||
(result.lock_expires_in_minutes as number | null) ??
|
||||
(result.lockExpiresInMinutes as number | null) ??
|
||||
null,
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return NextResponse.json(result)
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error locking Agiloft record:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftReadRecordContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, 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 type { AgiloftRecordResponse } from '@/tools/agiloft/types'
|
||||
import { buildReadRecordUrl } from '@/tools/agiloft/utils'
|
||||
import { executeAgiloftRequest } from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftReadRecordAPI')
|
||||
|
||||
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 Agiloft read_record attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftReadRecordContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const result = await executeAgiloftRequest<AgiloftRecordResponse>(
|
||||
params,
|
||||
(base) => ({
|
||||
url: buildReadRecordUrl(base, params),
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json' },
|
||||
}),
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
return {
|
||||
success: false,
|
||||
output: { id: null, fields: {} },
|
||||
error: `Agiloft error: ${response.status} - ${errorText}`,
|
||||
}
|
||||
}
|
||||
|
||||
const data = (await response.json()) as Record<string, unknown>
|
||||
const result = (data.result ?? data) as Record<string, unknown>
|
||||
const id = result.id ?? result.ID ?? data.id ?? data.ID ?? null
|
||||
|
||||
return {
|
||||
success: data.success !== false,
|
||||
output: {
|
||||
id: id != null ? String(id) : null,
|
||||
fields: result ?? {},
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return NextResponse.json(result)
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error reading Agiloft record:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftRemoveAttachmentContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, 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 type { AgiloftRemoveAttachmentResponse } from '@/tools/agiloft/types'
|
||||
import { buildRemoveAttachmentUrl } from '@/tools/agiloft/utils'
|
||||
import { executeAgiloftRequest } from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftRemoveAttachmentAPI')
|
||||
|
||||
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 Agiloft remove_attachment attempt: ${authResult.error}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftRemoveAttachmentContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const result = await executeAgiloftRequest<AgiloftRemoveAttachmentResponse>(
|
||||
params,
|
||||
(base) => ({
|
||||
url: buildRemoveAttachmentUrl(base, params),
|
||||
method: 'DELETE',
|
||||
}),
|
||||
async (response) => {
|
||||
const text = await response.text()
|
||||
|
||||
if (!response.ok) {
|
||||
return {
|
||||
success: false,
|
||||
output: {
|
||||
recordId: params.recordId?.trim() ?? '',
|
||||
fieldName: params.fieldName?.trim() ?? '',
|
||||
remainingAttachments: 0,
|
||||
},
|
||||
error: `Agiloft error: ${response.status} - ${text}`,
|
||||
}
|
||||
}
|
||||
|
||||
let remainingAttachments = 0
|
||||
try {
|
||||
const data = JSON.parse(text)
|
||||
const result = data.result ?? data
|
||||
remainingAttachments =
|
||||
typeof result === 'number' ? result : (result.count ?? result.remaining ?? 0)
|
||||
} catch {
|
||||
remainingAttachments = Number(text) || 0
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
output: {
|
||||
recordId: params.recordId?.trim() ?? '',
|
||||
fieldName: params.fieldName?.trim() ?? '',
|
||||
remainingAttachments,
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return NextResponse.json(result)
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error removing Agiloft attachment:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import {
|
||||
createMockRequest,
|
||||
hybridAuthMockFns,
|
||||
inputValidationMock,
|
||||
inputValidationMockFns,
|
||||
} from '@sim/testing'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock)
|
||||
|
||||
import { POST } from '@/app/api/tools/agiloft/retrieve/route'
|
||||
|
||||
const PINNED_IP = '93.184.216.34'
|
||||
|
||||
const baseBody = {
|
||||
instanceUrl: 'https://example.agiloft.com',
|
||||
knowledgeBase: 'demo',
|
||||
login: 'admin',
|
||||
password: 'secret',
|
||||
table: 'contracts',
|
||||
recordId: '42',
|
||||
fieldName: 'attachments',
|
||||
position: '0',
|
||||
}
|
||||
|
||||
function mockSecureFetchResponse(body: {
|
||||
ok?: boolean
|
||||
status?: number
|
||||
json?: unknown
|
||||
text?: string
|
||||
arrayBuffer?: ArrayBuffer
|
||||
headers?: Headers
|
||||
}) {
|
||||
return {
|
||||
ok: body.ok ?? true,
|
||||
status: body.status ?? 200,
|
||||
statusText: '',
|
||||
headers: body.headers ?? new Headers(),
|
||||
body: null,
|
||||
text: async () => body.text ?? '',
|
||||
json: async () => body.json ?? {},
|
||||
arrayBuffer: async () => body.arrayBuffer ?? new ArrayBuffer(0),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
hybridAuthMockFns.mockCheckInternalAuth.mockResolvedValue({
|
||||
success: true,
|
||||
userId: 'user-1',
|
||||
authType: 'internal_jwt',
|
||||
})
|
||||
inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValue({
|
||||
isValid: true,
|
||||
resolvedIP: PINNED_IP,
|
||||
originalHostname: 'example.agiloft.com',
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/tools/agiloft/retrieve', () => {
|
||||
it('rejects unauthenticated requests', async () => {
|
||||
hybridAuthMockFns.mockCheckInternalAuth.mockResolvedValueOnce({
|
||||
success: false,
|
||||
error: 'unauthorized',
|
||||
})
|
||||
|
||||
const response = await POST(createMockRequest('POST', baseBody))
|
||||
expect(response.status).toBe(401)
|
||||
expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks SSRF when the instance URL fails DNS validation', async () => {
|
||||
inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValueOnce({
|
||||
isValid: false,
|
||||
error: 'instanceUrl resolves to a blocked IP address',
|
||||
})
|
||||
|
||||
const response = await POST(
|
||||
createMockRequest('POST', { ...baseBody, instanceUrl: 'https://attacker.example.com' })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const data = (await response.json()) as { success: false; error: string }
|
||||
expect(data.success).toBe(false)
|
||||
expect(data.error).toContain('blocked IP')
|
||||
expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('pins the resolved IP for login, retrieve, and logout (TOCTOU fix)', async () => {
|
||||
const fileBytes = Buffer.from('hello-attachment', 'utf-8')
|
||||
|
||||
inputValidationMockFns.mockSecureFetchWithPinnedIP
|
||||
.mockResolvedValueOnce(mockSecureFetchResponse({ json: { access_token: 'tok-xyz' } }))
|
||||
.mockResolvedValueOnce(
|
||||
mockSecureFetchResponse({
|
||||
arrayBuffer: fileBytes.buffer.slice(
|
||||
fileBytes.byteOffset,
|
||||
fileBytes.byteOffset + fileBytes.byteLength
|
||||
) as ArrayBuffer,
|
||||
headers: new Headers({
|
||||
'content-type': 'text/plain',
|
||||
'content-disposition': 'attachment; filename="report.txt"',
|
||||
}),
|
||||
})
|
||||
)
|
||||
.mockResolvedValueOnce(mockSecureFetchResponse({}))
|
||||
|
||||
const response = await POST(createMockRequest('POST', baseBody))
|
||||
expect(response.status).toBe(200)
|
||||
const data = (await response.json()) as {
|
||||
success: true
|
||||
output: { file: { name: string; mimeType: string; data: string; size: number } }
|
||||
}
|
||||
|
||||
expect(data.output.file.name).toBe('report.txt')
|
||||
expect(data.output.file.mimeType).toBe('text/plain')
|
||||
expect(data.output.file.size).toBe(fileBytes.length)
|
||||
expect(Buffer.from(data.output.file.data, 'base64').toString('utf-8')).toBe('hello-attachment')
|
||||
|
||||
const calls = inputValidationMockFns.mockSecureFetchWithPinnedIP.mock.calls
|
||||
expect(calls).toHaveLength(3)
|
||||
|
||||
// All three outbound calls must use the pre-resolved IP.
|
||||
for (const call of calls) {
|
||||
expect(call[1]).toBe(PINNED_IP)
|
||||
}
|
||||
|
||||
// Original hostname is preserved in the URL (so TLS SNI works).
|
||||
expect(calls[0][0]).toContain('https://example.agiloft.com/ewws/EWLogin')
|
||||
expect(calls[1][0]).toContain('https://example.agiloft.com/ewws/EWRetrieve')
|
||||
expect(calls[1][2]).toMatchObject({
|
||||
method: 'GET',
|
||||
headers: { Authorization: 'Bearer tok-xyz' },
|
||||
})
|
||||
expect(calls[2][0]).toContain('https://example.agiloft.com/ewws/EWLogout')
|
||||
|
||||
// DNS only resolved once — no second lookup that could rebind.
|
||||
expect(inputValidationMockFns.mockValidateUrlWithDNS).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('propagates upstream errors and still calls logout', async () => {
|
||||
inputValidationMockFns.mockSecureFetchWithPinnedIP
|
||||
.mockResolvedValueOnce(mockSecureFetchResponse({ json: { access_token: 'tok-err' } }))
|
||||
.mockResolvedValueOnce(
|
||||
mockSecureFetchResponse({ ok: false, status: 404, text: 'Record not found' })
|
||||
)
|
||||
.mockResolvedValueOnce(mockSecureFetchResponse({}))
|
||||
|
||||
const response = await POST(createMockRequest('POST', baseBody))
|
||||
expect(response.status).toBe(404)
|
||||
const data = (await response.json()) as { success: false; error: string }
|
||||
expect(data.error).toContain('Record not found')
|
||||
|
||||
// Logout still runs.
|
||||
expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).toHaveBeenCalledTimes(3)
|
||||
expect(inputValidationMockFns.mockSecureFetchWithPinnedIP.mock.calls[2][0]).toContain(
|
||||
'/ewws/EWLogout'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,137 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftRetrieveContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { secureFetchWithPinnedIP } from '@/lib/core/security/input-validation.server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { buildRetrieveAttachmentUrl } from '@/tools/agiloft/utils'
|
||||
import {
|
||||
agiloftLoginPinned,
|
||||
agiloftLogoutPinned,
|
||||
resolveAgiloftInstance,
|
||||
} from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftRetrieveAPI')
|
||||
|
||||
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 Agiloft retrieve attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftRetrieveContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const data = parsed.data.body
|
||||
|
||||
let resolvedIP: string
|
||||
try {
|
||||
resolvedIP = await resolveAgiloftInstance(data.instanceUrl)
|
||||
} catch (error) {
|
||||
logger.warn(`[${requestId}] SSRF attempt blocked for Agiloft instance URL`, {
|
||||
instanceUrl: data.instanceUrl,
|
||||
})
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 400 })
|
||||
}
|
||||
|
||||
const token = await agiloftLoginPinned(data, resolvedIP)
|
||||
const base = data.instanceUrl.replace(/\/$/, '')
|
||||
|
||||
try {
|
||||
const url = buildRetrieveAttachmentUrl(base, data)
|
||||
|
||||
logger.info(`[${requestId}] Downloading attachment from Agiloft`, {
|
||||
recordId: data.recordId,
|
||||
fieldName: data.fieldName,
|
||||
position: data.position,
|
||||
})
|
||||
|
||||
const agiloftResponse = await secureFetchWithPinnedIP(url, resolvedIP, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
|
||||
if (!agiloftResponse.ok) {
|
||||
const errorText = await agiloftResponse.text()
|
||||
logger.error(
|
||||
`[${requestId}] Agiloft retrieve error: ${agiloftResponse.status} - ${errorText}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: `Agiloft error: ${agiloftResponse.status} - ${errorText}` },
|
||||
{ status: agiloftResponse.status }
|
||||
)
|
||||
}
|
||||
|
||||
const contentType = agiloftResponse.headers.get('content-type') || 'application/octet-stream'
|
||||
const contentDisposition = agiloftResponse.headers.get('content-disposition')
|
||||
let fileName = 'attachment'
|
||||
|
||||
if (contentDisposition) {
|
||||
const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
|
||||
if (match?.[1]) {
|
||||
fileName = match[1].replace(/['"]/g, '')
|
||||
}
|
||||
}
|
||||
|
||||
const arrayBuffer = await agiloftResponse.arrayBuffer()
|
||||
const fileBuffer = Buffer.from(arrayBuffer)
|
||||
|
||||
logger.info(`[${requestId}] Attachment downloaded successfully`, {
|
||||
name: fileName,
|
||||
size: fileBuffer.length,
|
||||
mimeType: contentType,
|
||||
})
|
||||
|
||||
const base64Data = fileBuffer.toString('base64')
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: {
|
||||
file: {
|
||||
name: fileName,
|
||||
mimeType: contentType,
|
||||
data: base64Data,
|
||||
size: fileBuffer.length,
|
||||
},
|
||||
},
|
||||
})
|
||||
} finally {
|
||||
await agiloftLogoutPinned(data.instanceUrl, data.knowledgeBase, token, resolvedIP)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error retrieving Agiloft attachment:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftSavedSearchContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, 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 type { AgiloftSavedSearchResponse } from '@/tools/agiloft/types'
|
||||
import { buildSavedSearchUrl } from '@/tools/agiloft/utils'
|
||||
import { executeAgiloftRequest } from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftSavedSearchAPI')
|
||||
|
||||
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 Agiloft saved_search attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftSavedSearchContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const result = await executeAgiloftRequest<AgiloftSavedSearchResponse>(
|
||||
params,
|
||||
(base) => ({
|
||||
url: buildSavedSearchUrl(base, params),
|
||||
method: 'GET',
|
||||
}),
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
return {
|
||||
success: false,
|
||||
output: { searches: [] },
|
||||
error: `Agiloft error: ${response.status} - ${errorText}`,
|
||||
}
|
||||
}
|
||||
|
||||
const data = (await response.json()) as Record<string, unknown>
|
||||
const result = (data.result ?? data) as Record<string, unknown>
|
||||
|
||||
const searches: Array<{
|
||||
name: string
|
||||
label: string
|
||||
id: string | number
|
||||
description: string | null
|
||||
}> = []
|
||||
|
||||
if (Array.isArray(result)) {
|
||||
for (const item of result as Record<string, unknown>[]) {
|
||||
searches.push({
|
||||
name: (item.name as string) ?? '',
|
||||
label: (item.label as string) ?? (item.name as string) ?? '',
|
||||
id: (item.id as string | number) ?? (item.ID as string | number) ?? '',
|
||||
description: (item.description as string | null) ?? null,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: data.success !== false,
|
||||
output: {
|
||||
searches,
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return NextResponse.json(result)
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error listing Agiloft saved searches:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftSearchRecordsContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, 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 type { AgiloftSearchResponse } from '@/tools/agiloft/types'
|
||||
import { buildSearchRecordsUrl } from '@/tools/agiloft/utils'
|
||||
import { executeAgiloftRequest } from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftSearchRecordsAPI')
|
||||
|
||||
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 Agiloft search_records attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftSearchRecordsContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const result = await executeAgiloftRequest<AgiloftSearchResponse>(
|
||||
params,
|
||||
(base) => ({
|
||||
url: buildSearchRecordsUrl(base, params),
|
||||
method: 'GET',
|
||||
}),
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
return {
|
||||
success: false,
|
||||
output: { records: [], totalCount: 0, page: 0, limit: 25 },
|
||||
error: `Agiloft error: ${response.status} - ${errorText}`,
|
||||
}
|
||||
}
|
||||
|
||||
const data = (await response.json()) as Record<string, unknown>
|
||||
const records: Record<string, unknown>[] = []
|
||||
const result = (data.result ?? data) as Record<string, unknown>
|
||||
|
||||
if (Array.isArray(result)) {
|
||||
for (const item of result as Record<string, unknown>[]) {
|
||||
records.push(item)
|
||||
}
|
||||
} else {
|
||||
const lengthRaw = result.EWREST_length ?? data.EWREST_length
|
||||
const count = typeof lengthRaw === 'string' ? Number(lengthRaw) : (lengthRaw as number)
|
||||
if (typeof count === 'number' && Number.isFinite(count)) {
|
||||
const source = (result.EWREST_length != null ? result : data) as Record<string, unknown>
|
||||
for (let i = 0; i < count; i++) {
|
||||
const record: Record<string, unknown> = {}
|
||||
for (const key of Object.keys(source)) {
|
||||
const match = key.match(/^EWREST_(.+)_(\d+)$/)
|
||||
if (match && Number(match[2]) === i) {
|
||||
record[match[1]] = source[key]
|
||||
}
|
||||
}
|
||||
if (Object.keys(record).length > 0) {
|
||||
records.push(record)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const totalCountRaw =
|
||||
result.totalCount ??
|
||||
result.total ??
|
||||
result.count ??
|
||||
result.EWREST_length ??
|
||||
data.totalCount ??
|
||||
data.total ??
|
||||
data.count ??
|
||||
data.EWREST_length ??
|
||||
records.length
|
||||
const totalCount =
|
||||
typeof totalCountRaw === 'string' ? Number(totalCountRaw) : (totalCountRaw as number)
|
||||
const page = params.page ? Number(params.page) : 0
|
||||
const limit = params.limit ? Number(params.limit) : 25
|
||||
|
||||
return {
|
||||
success: data.success !== false,
|
||||
output: {
|
||||
records,
|
||||
totalCount,
|
||||
page,
|
||||
limit,
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return NextResponse.json(result)
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error searching Agiloft records:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,116 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftSelectRecordsContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, 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 type { AgiloftSelectResponse } from '@/tools/agiloft/types'
|
||||
import { buildSelectRecordsUrl } from '@/tools/agiloft/utils'
|
||||
import { executeAgiloftRequest } from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftSelectRecordsAPI')
|
||||
|
||||
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 Agiloft select_records attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftSelectRecordsContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const result = await executeAgiloftRequest<AgiloftSelectResponse>(
|
||||
params,
|
||||
(base) => ({
|
||||
url: buildSelectRecordsUrl(base, params),
|
||||
method: 'GET',
|
||||
}),
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
return {
|
||||
success: false,
|
||||
output: { recordIds: [], totalCount: 0 },
|
||||
error: `Agiloft error: ${response.status} - ${errorText}`,
|
||||
}
|
||||
}
|
||||
|
||||
const data = (await response.json()) as Record<string, unknown>
|
||||
const result = (data.result ?? data) as Record<string, unknown>
|
||||
const recordIds: string[] = []
|
||||
|
||||
if (Array.isArray(result)) {
|
||||
for (const item of result as Record<string, unknown>[]) {
|
||||
const id = item.id ?? item.ID ?? item
|
||||
recordIds.push(String(id))
|
||||
}
|
||||
} else if (typeof result === 'object' && result !== null) {
|
||||
let i = 0
|
||||
while (result[`id_${i}`] !== undefined || result[`EWREST_id_${i}`] !== undefined) {
|
||||
const id = result[`id_${i}`] ?? result[`EWREST_id_${i}`]
|
||||
recordIds.push(String(id))
|
||||
i++
|
||||
}
|
||||
if (recordIds.length === 0 && result.id !== undefined) {
|
||||
recordIds.push(String(result.id))
|
||||
}
|
||||
}
|
||||
|
||||
const totalCountRaw =
|
||||
result.EWREST_id_length ??
|
||||
result.totalCount ??
|
||||
result.total ??
|
||||
result.count ??
|
||||
data.EWREST_id_length ??
|
||||
data.totalCount ??
|
||||
data.total ??
|
||||
data.count ??
|
||||
recordIds.length
|
||||
|
||||
return {
|
||||
success: data.success !== false,
|
||||
output: {
|
||||
recordIds,
|
||||
totalCount: Number(totalCountRaw),
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return NextResponse.json(result)
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error selecting Agiloft records:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { agiloftUpdateRecordContract } from '@/lib/api/contracts/tools/agiloft'
|
||||
import { getValidationErrorMessage, 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 type { AgiloftRecordResponse } from '@/tools/agiloft/types'
|
||||
import { buildUpdateRecordUrl } from '@/tools/agiloft/utils'
|
||||
import { executeAgiloftRequest } from '@/tools/agiloft/utils.server'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('AgiloftUpdateRecordAPI')
|
||||
|
||||
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 Agiloft update_record attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
agiloftUpdateRecordContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: getValidationErrorMessage(error, 'Invalid request data'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
let body: string
|
||||
try {
|
||||
body = JSON.stringify(JSON.parse(params.data))
|
||||
} catch {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
output: { id: null, fields: {} },
|
||||
error: 'Invalid JSON in data parameter',
|
||||
})
|
||||
}
|
||||
|
||||
const result = await executeAgiloftRequest<AgiloftRecordResponse>(
|
||||
params,
|
||||
(base) => ({
|
||||
url: buildUpdateRecordUrl(base, params),
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body,
|
||||
}),
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
return {
|
||||
success: false,
|
||||
output: { id: null, fields: {} },
|
||||
error: `Agiloft error: ${response.status} - ${errorText}`,
|
||||
}
|
||||
}
|
||||
|
||||
const data = (await response.json()) as Record<string, unknown>
|
||||
const result = (data.result ?? data) as Record<string, unknown>
|
||||
const id = result.id ?? result.ID ?? data.id ?? data.ID ?? null
|
||||
|
||||
return {
|
||||
success: data.success !== false,
|
||||
output: {
|
||||
id: id != null ? String(id) : null,
|
||||
fields: result ?? {},
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return NextResponse.json(result)
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error updating Agiloft record:`, error)
|
||||
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user