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,166 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import type { SFTPWrapper } from 'ssh2'
|
||||
import { sftpDeleteContract } from '@/lib/api/contracts/storage-transfer'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import {
|
||||
createSftpConnection,
|
||||
getFileType,
|
||||
getSftp,
|
||||
isPathSafe,
|
||||
sanitizePath,
|
||||
sftpIsDirectory,
|
||||
} from '@/app/api/tools/sftp/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('SftpDeleteAPI')
|
||||
|
||||
/**
|
||||
* Recursively deletes a directory and all its contents
|
||||
*/
|
||||
async function deleteRecursive(sftp: SFTPWrapper, dirPath: string): Promise<void> {
|
||||
const entries = await new Promise<Array<{ filename: string; attrs: any }>>((resolve, reject) => {
|
||||
sftp.readdir(dirPath, (err, list) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
resolve(list)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.filename === '.' || entry.filename === '..') continue
|
||||
|
||||
const entryPath = `${dirPath}/${entry.filename}`
|
||||
const entryType = getFileType(entry.attrs)
|
||||
|
||||
if (entryType === 'directory') {
|
||||
await deleteRecursive(sftp, entryPath)
|
||||
} else {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
sftp.unlink(entryPath, (err) => {
|
||||
if (err) reject(err)
|
||||
else resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
sftp.rmdir(dirPath, (err) => {
|
||||
if (err) reject(err)
|
||||
else resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
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 SFTP delete attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Authenticated SFTP delete request via ${authResult.authType}`, {
|
||||
userId: authResult.userId,
|
||||
})
|
||||
|
||||
const parsed = await parseRequest(sftpDeleteContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
if (!isPathSafe(params.remotePath)) {
|
||||
logger.warn(`[${requestId}] Path traversal attempt detected in remotePath`)
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid remote path: path traversal sequences are not allowed' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Connecting to SFTP server ${params.host}:${params.port}`)
|
||||
|
||||
const client = await createSftpConnection({
|
||||
host: params.host,
|
||||
port: params.port,
|
||||
username: params.username,
|
||||
password: params.password,
|
||||
privateKey: params.privateKey,
|
||||
passphrase: params.passphrase,
|
||||
})
|
||||
|
||||
try {
|
||||
const sftp = await getSftp(client)
|
||||
const remotePath = sanitizePath(params.remotePath)
|
||||
|
||||
logger.info(`[${requestId}] Deleting ${remotePath} (recursive: ${params.recursive})`)
|
||||
|
||||
const isDir = await sftpIsDirectory(sftp, remotePath)
|
||||
|
||||
if (isDir) {
|
||||
if (params.recursive) {
|
||||
await deleteRecursive(sftp, remotePath)
|
||||
} else {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
sftp.rmdir(remotePath, (err) => {
|
||||
if (err) {
|
||||
if (err.message.includes('not empty')) {
|
||||
reject(
|
||||
new Error(
|
||||
'Directory is not empty. Use recursive: true to delete non-empty directories.'
|
||||
)
|
||||
)
|
||||
} else {
|
||||
reject(err)
|
||||
}
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
} else {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
sftp.unlink(remotePath, (err) => {
|
||||
if (err) {
|
||||
if (err.message.includes('No such file')) {
|
||||
reject(new Error(`File not found: ${remotePath}`))
|
||||
} else {
|
||||
reject(err)
|
||||
}
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Successfully deleted ${remotePath}`)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
deletedPath: remotePath,
|
||||
message: `Successfully deleted ${remotePath}`,
|
||||
})
|
||||
} finally {
|
||||
client.end()
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
|
||||
logger.error(`[${requestId}] SFTP delete failed:`, error)
|
||||
|
||||
return NextResponse.json({ error: `SFTP delete failed: ${errorMessage}` }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,136 @@
|
||||
import path from 'path'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { sftpDownloadContract } from '@/lib/api/contracts/storage-transfer'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { getFileExtension, getMimeTypeFromExtension } from '@/lib/uploads/utils/file-utils'
|
||||
import { createSftpConnection, getSftp, isPathSafe, sanitizePath } from '@/app/api/tools/sftp/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('SftpDownloadAPI')
|
||||
|
||||
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 SFTP download attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Authenticated SFTP download request via ${authResult.authType}`, {
|
||||
userId: authResult.userId,
|
||||
})
|
||||
|
||||
const parsed = await parseRequest(sftpDownloadContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
if (!isPathSafe(params.remotePath)) {
|
||||
logger.warn(`[${requestId}] Path traversal attempt detected in remotePath`)
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid remote path: path traversal sequences are not allowed' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Connecting to SFTP server ${params.host}:${params.port}`)
|
||||
|
||||
const client = await createSftpConnection({
|
||||
host: params.host,
|
||||
port: params.port,
|
||||
username: params.username,
|
||||
password: params.password,
|
||||
privateKey: params.privateKey,
|
||||
passphrase: params.passphrase,
|
||||
})
|
||||
|
||||
try {
|
||||
const sftp = await getSftp(client)
|
||||
const remotePath = sanitizePath(params.remotePath)
|
||||
|
||||
const stats = await new Promise<{ size: number }>((resolve, reject) => {
|
||||
sftp.stat(remotePath, (err, stats) => {
|
||||
if (err) {
|
||||
if (err.message.includes('No such file')) {
|
||||
reject(new Error(`File not found: ${remotePath}`))
|
||||
} else {
|
||||
reject(err)
|
||||
}
|
||||
} else {
|
||||
resolve(stats)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
const maxSize = 50 * 1024 * 1024
|
||||
if (stats.size > maxSize) {
|
||||
const sizeMB = (stats.size / (1024 * 1024)).toFixed(2)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: `File size (${sizeMB}MB) exceeds download limit of 50MB` },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Downloading file ${remotePath} (${stats.size} bytes)`)
|
||||
|
||||
const chunks: Buffer[] = []
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const readStream = sftp.createReadStream(remotePath)
|
||||
|
||||
readStream.on('data', (chunk: Buffer) => {
|
||||
chunks.push(chunk)
|
||||
})
|
||||
|
||||
readStream.on('end', () => resolve())
|
||||
readStream.on('error', reject)
|
||||
})
|
||||
|
||||
const buffer = Buffer.concat(chunks)
|
||||
const fileName = path.basename(remotePath)
|
||||
const extension = getFileExtension(fileName)
|
||||
const mimeType = getMimeTypeFromExtension(extension)
|
||||
|
||||
let content: string
|
||||
if (params.encoding === 'base64') {
|
||||
content = buffer.toString('base64')
|
||||
} else {
|
||||
content = buffer.toString('utf-8')
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Downloaded ${fileName} (${buffer.length} bytes)`)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
fileName,
|
||||
file: {
|
||||
name: fileName,
|
||||
mimeType,
|
||||
data: buffer.toString('base64'),
|
||||
size: buffer.length,
|
||||
},
|
||||
content,
|
||||
size: buffer.length,
|
||||
encoding: params.encoding,
|
||||
message: `Successfully downloaded ${fileName}`,
|
||||
})
|
||||
} finally {
|
||||
client.end()
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
|
||||
logger.error(`[${requestId}] SFTP download failed:`, error)
|
||||
|
||||
return NextResponse.json({ error: `SFTP download failed: ${errorMessage}` }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import type { SFTPWrapper } from 'ssh2'
|
||||
import { sftpMkdirContract } from '@/lib/api/contracts/storage-transfer'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import {
|
||||
createSftpConnection,
|
||||
getSftp,
|
||||
isPathSafe,
|
||||
sanitizePath,
|
||||
sftpExists,
|
||||
} from '@/app/api/tools/sftp/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('SftpMkdirAPI')
|
||||
|
||||
/**
|
||||
* Creates directory recursively (like mkdir -p)
|
||||
*/
|
||||
async function mkdirRecursive(sftp: SFTPWrapper, dirPath: string): Promise<void> {
|
||||
const parts = dirPath.split('/').filter(Boolean)
|
||||
let currentPath = dirPath.startsWith('/') ? '' : ''
|
||||
|
||||
for (const part of parts) {
|
||||
currentPath = currentPath
|
||||
? `${currentPath}/${part}`
|
||||
: dirPath.startsWith('/')
|
||||
? `/${part}`
|
||||
: part
|
||||
|
||||
const exists = await sftpExists(sftp, currentPath)
|
||||
if (!exists) {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
sftp.mkdir(currentPath, (err) => {
|
||||
if (err && !err.message.includes('already exists')) {
|
||||
reject(err)
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 SFTP mkdir attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Authenticated SFTP mkdir request via ${authResult.authType}`, {
|
||||
userId: authResult.userId,
|
||||
})
|
||||
|
||||
const parsed = await parseRequest(sftpMkdirContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
if (!isPathSafe(params.remotePath)) {
|
||||
logger.warn(`[${requestId}] Path traversal attempt detected in remotePath`)
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid remote path: path traversal sequences are not allowed' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Connecting to SFTP server ${params.host}:${params.port}`)
|
||||
|
||||
const client = await createSftpConnection({
|
||||
host: params.host,
|
||||
port: params.port,
|
||||
username: params.username,
|
||||
password: params.password,
|
||||
privateKey: params.privateKey,
|
||||
passphrase: params.passphrase,
|
||||
})
|
||||
|
||||
try {
|
||||
const sftp = await getSftp(client)
|
||||
const remotePath = sanitizePath(params.remotePath)
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] Creating directory ${remotePath} (recursive: ${params.recursive})`
|
||||
)
|
||||
|
||||
if (params.recursive) {
|
||||
await mkdirRecursive(sftp, remotePath)
|
||||
} else {
|
||||
const exists = await sftpExists(sftp, remotePath)
|
||||
if (exists) {
|
||||
return NextResponse.json(
|
||||
{ error: `Directory already exists: ${remotePath}` },
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
sftp.mkdir(remotePath, (err) => {
|
||||
if (err) {
|
||||
if (err.message.includes('No such file')) {
|
||||
reject(
|
||||
new Error(
|
||||
'Parent directory does not exist. Use recursive: true to create parent directories.'
|
||||
)
|
||||
)
|
||||
} else {
|
||||
reject(err)
|
||||
}
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Successfully created directory ${remotePath}`)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
createdPath: remotePath,
|
||||
message: `Successfully created directory ${remotePath}`,
|
||||
})
|
||||
} finally {
|
||||
client.end()
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
|
||||
logger.error(`[${requestId}] SFTP mkdir failed:`, error)
|
||||
|
||||
return NextResponse.json({ error: `SFTP mkdir failed: ${errorMessage}` }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,230 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { sftpUploadContract } from '@/lib/api/contracts/storage-transfer'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
|
||||
import { downloadServableFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
||||
import { docNotReadyResponse } from '@/lib/uploads/utils/servable-file-response'
|
||||
import { assertToolFileAccess } from '@/app/api/files/authorization'
|
||||
import {
|
||||
createSftpConnection,
|
||||
getSftp,
|
||||
isPathSafe,
|
||||
sanitizeFileName,
|
||||
sanitizePath,
|
||||
sftpExists,
|
||||
} from '@/app/api/tools/sftp/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('SftpUploadAPI')
|
||||
|
||||
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 SFTP upload attempt: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Authenticated SFTP upload request via ${authResult.authType}`, {
|
||||
userId: authResult.userId,
|
||||
})
|
||||
|
||||
const parsed = await parseRequest(sftpUploadContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
const hasFiles = params.files && params.files.length > 0
|
||||
const hasDirectContent = params.fileContent && params.fileName
|
||||
|
||||
if (!hasFiles && !hasDirectContent) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Either files or fileContent with fileName must be provided' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (!isPathSafe(params.remotePath)) {
|
||||
logger.warn(`[${requestId}] Path traversal attempt detected in remotePath`)
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid remote path: path traversal sequences are not allowed' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Connecting to SFTP server ${params.host}:${params.port}`)
|
||||
|
||||
const client = await createSftpConnection({
|
||||
host: params.host,
|
||||
port: params.port,
|
||||
username: params.username,
|
||||
password: params.password,
|
||||
privateKey: params.privateKey,
|
||||
passphrase: params.passphrase,
|
||||
})
|
||||
|
||||
try {
|
||||
const sftp = await getSftp(client)
|
||||
const remotePath = sanitizePath(params.remotePath)
|
||||
const uploadedFiles: Array<{ name: string; remotePath: string; size: number }> = []
|
||||
|
||||
if (hasFiles) {
|
||||
const rawFiles = params.files!
|
||||
logger.info(`[${requestId}] Processing ${rawFiles.length} file(s) for upload`)
|
||||
|
||||
const userFiles = processFilesToUserFiles(rawFiles, requestId, logger)
|
||||
|
||||
const totalSize = userFiles.reduce((sum, file) => sum + file.size, 0)
|
||||
const maxSize = 100 * 1024 * 1024
|
||||
|
||||
if (totalSize > maxSize) {
|
||||
const sizeMB = (totalSize / (1024 * 1024)).toFixed(2)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: `Total file size (${sizeMB}MB) exceeds limit of 100MB` },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
let resolvedTotal = 0
|
||||
for (const file of userFiles) {
|
||||
try {
|
||||
const denied = await assertToolFileAccess(
|
||||
file.key,
|
||||
authResult.userId,
|
||||
requestId,
|
||||
logger
|
||||
)
|
||||
if (denied) return denied
|
||||
logger.info(
|
||||
`[${requestId}] Downloading file for upload: ${file.name} (${file.size} bytes)`
|
||||
)
|
||||
const { buffer } = await downloadServableFileFromStorage(file, requestId, logger)
|
||||
|
||||
resolvedTotal += buffer.length
|
||||
if (resolvedTotal > maxSize) {
|
||||
const sizeMB = (resolvedTotal / (1024 * 1024)).toFixed(2)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: `Total file size (${sizeMB}MB) exceeds limit of 100MB` },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const safeFileName = sanitizeFileName(file.name)
|
||||
const fullRemotePath = remotePath.endsWith('/')
|
||||
? `${remotePath}${safeFileName}`
|
||||
: `${remotePath}/${safeFileName}`
|
||||
|
||||
const sanitizedRemotePath = sanitizePath(fullRemotePath)
|
||||
|
||||
if (!params.overwrite) {
|
||||
const exists = await sftpExists(sftp, sanitizedRemotePath)
|
||||
if (exists) {
|
||||
logger.warn(`[${requestId}] File ${sanitizedRemotePath} already exists, skipping`)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const writeStream = sftp.createWriteStream(sanitizedRemotePath, {
|
||||
mode: params.permissions ? Number.parseInt(params.permissions, 8) : 0o644,
|
||||
})
|
||||
|
||||
writeStream.on('error', reject)
|
||||
writeStream.on('close', () => resolve())
|
||||
writeStream.end(buffer)
|
||||
})
|
||||
|
||||
uploadedFiles.push({
|
||||
name: safeFileName,
|
||||
remotePath: sanitizedRemotePath,
|
||||
size: buffer.length,
|
||||
})
|
||||
|
||||
logger.info(`[${requestId}] Uploaded ${safeFileName} to ${sanitizedRemotePath}`)
|
||||
} catch (error) {
|
||||
const notReady = docNotReadyResponse(error)
|
||||
if (notReady) return notReady
|
||||
logger.error(`[${requestId}] Failed to upload file ${file.name}:`, error)
|
||||
throw new Error(
|
||||
`Failed to upload file "${file.name}": ${getErrorMessage(error, 'Unknown error')}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hasDirectContent) {
|
||||
const safeFileName = sanitizeFileName(params.fileName!)
|
||||
const fullRemotePath = remotePath.endsWith('/')
|
||||
? `${remotePath}${safeFileName}`
|
||||
: `${remotePath}/${safeFileName}`
|
||||
|
||||
const sanitizedRemotePath = sanitizePath(fullRemotePath)
|
||||
|
||||
if (!params.overwrite) {
|
||||
const exists = await sftpExists(sftp, sanitizedRemotePath)
|
||||
if (exists) {
|
||||
return NextResponse.json(
|
||||
{ error: 'File already exists and overwrite is disabled' },
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
let content: Buffer
|
||||
try {
|
||||
content = Buffer.from(params.fileContent!, 'base64')
|
||||
const reEncoded = content.toString('base64')
|
||||
if (reEncoded !== params.fileContent) {
|
||||
content = Buffer.from(params.fileContent!, 'utf-8')
|
||||
}
|
||||
} catch {
|
||||
content = Buffer.from(params.fileContent!, 'utf-8')
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const writeStream = sftp.createWriteStream(sanitizedRemotePath, {
|
||||
mode: params.permissions ? Number.parseInt(params.permissions, 8) : 0o644,
|
||||
})
|
||||
|
||||
writeStream.on('error', reject)
|
||||
writeStream.on('close', () => resolve())
|
||||
writeStream.end(content)
|
||||
})
|
||||
|
||||
uploadedFiles.push({
|
||||
name: safeFileName,
|
||||
remotePath: sanitizedRemotePath,
|
||||
size: content.length,
|
||||
})
|
||||
|
||||
logger.info(`[${requestId}] Uploaded direct content to ${sanitizedRemotePath}`)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] SFTP upload completed: ${uploadedFiles.length} file(s)`)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
uploadedFiles,
|
||||
message: `Successfully uploaded ${uploadedFiles.length} file(s)`,
|
||||
})
|
||||
} finally {
|
||||
client.end()
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
|
||||
logger.error(`[${requestId}] SFTP upload failed:`, error)
|
||||
|
||||
return NextResponse.json({ error: `SFTP upload failed: ${errorMessage}` }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,284 @@
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type Attributes, Client, type ConnectConfig, type SFTPWrapper } from 'ssh2'
|
||||
import { validateDatabaseHost } from '@/lib/core/security/input-validation.server'
|
||||
|
||||
const S_IFMT = 0o170000
|
||||
const S_IFDIR = 0o040000
|
||||
const S_IFREG = 0o100000
|
||||
const S_IFLNK = 0o120000
|
||||
|
||||
export interface SftpConnectionConfig {
|
||||
host: string
|
||||
port: number
|
||||
username: string
|
||||
password?: string | null
|
||||
privateKey?: string | null
|
||||
passphrase?: string | null
|
||||
timeout?: number
|
||||
keepaliveInterval?: number
|
||||
readyTimeout?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats SSH/SFTP errors with helpful troubleshooting context
|
||||
*/
|
||||
function formatSftpError(err: Error, config: { host: string; port: number }): Error {
|
||||
const errorMessage = err.message.toLowerCase()
|
||||
const { host, port } = config
|
||||
|
||||
if (errorMessage.includes('econnrefused') || errorMessage.includes('connection refused')) {
|
||||
return new Error(
|
||||
`Connection refused to ${host}:${port}. ` +
|
||||
`Please verify: (1) SSH/SFTP server is running, ` +
|
||||
`(2) Port ${port} is correct, ` +
|
||||
`(3) Firewall allows connections.`
|
||||
)
|
||||
}
|
||||
|
||||
if (errorMessage.includes('econnreset') || errorMessage.includes('connection reset')) {
|
||||
return new Error(
|
||||
`Connection reset by ${host}:${port}. ` +
|
||||
`This usually means: (1) Wrong port number, ` +
|
||||
`(2) Server rejected the connection, ` +
|
||||
`(3) Network/firewall interrupted the connection.`
|
||||
)
|
||||
}
|
||||
|
||||
if (errorMessage.includes('etimedout') || errorMessage.includes('timeout')) {
|
||||
return new Error(
|
||||
`Connection timed out to ${host}:${port}. ` +
|
||||
`Please verify: (1) Host is reachable, ` +
|
||||
`(2) No firewall is blocking the connection, ` +
|
||||
`(3) The SFTP server is responding.`
|
||||
)
|
||||
}
|
||||
|
||||
if (errorMessage.includes('enotfound') || errorMessage.includes('getaddrinfo')) {
|
||||
return new Error(
|
||||
`Could not resolve hostname "${host}". Please verify the hostname or IP address is correct.`
|
||||
)
|
||||
}
|
||||
|
||||
if (errorMessage.includes('authentication') || errorMessage.includes('auth')) {
|
||||
return new Error(
|
||||
`Authentication failed on ${host}:${port}. ` +
|
||||
`Please verify: (1) Username is correct, ` +
|
||||
`(2) Password or private key is valid, ` +
|
||||
`(3) User has SFTP access on the server.`
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
errorMessage.includes('key') &&
|
||||
(errorMessage.includes('parse') || errorMessage.includes('invalid'))
|
||||
) {
|
||||
return new Error(
|
||||
`Invalid private key format. ` +
|
||||
`Please ensure you're using a valid OpenSSH private key ` +
|
||||
`(starts with "-----BEGIN" and ends with "-----END").`
|
||||
)
|
||||
}
|
||||
|
||||
if (errorMessage.includes('host key') || errorMessage.includes('hostkey')) {
|
||||
return new Error(
|
||||
`Host key verification issue for ${host}. ` +
|
||||
`This may be the first connection or the server's key has changed.`
|
||||
)
|
||||
}
|
||||
|
||||
return new Error(`SFTP connection to ${host}:${port} failed: ${err.message}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an SSH connection for SFTP using the provided configuration.
|
||||
* Uses ssh2 library defaults which align with OpenSSH standards.
|
||||
*/
|
||||
export async function createSftpConnection(config: SftpConnectionConfig): Promise<Client> {
|
||||
const host = config.host
|
||||
|
||||
if (!host || host.trim() === '') {
|
||||
throw new Error('Host is required. Please provide a valid hostname or IP address.')
|
||||
}
|
||||
|
||||
const hostValidation = await validateDatabaseHost(host, 'host')
|
||||
if (!hostValidation.isValid) {
|
||||
throw new Error(hostValidation.error)
|
||||
}
|
||||
|
||||
const resolvedHost = hostValidation.resolvedIP ?? host.trim()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = new Client()
|
||||
const port = config.port || 22
|
||||
|
||||
const hasPassword = config.password && config.password.trim() !== ''
|
||||
const hasPrivateKey = config.privateKey && config.privateKey.trim() !== ''
|
||||
|
||||
if (!hasPassword && !hasPrivateKey) {
|
||||
reject(new Error('Authentication required. Please provide either a password or private key.'))
|
||||
return
|
||||
}
|
||||
|
||||
const connectConfig: ConnectConfig = {
|
||||
host: resolvedHost,
|
||||
port,
|
||||
username: config.username,
|
||||
}
|
||||
|
||||
if (config.readyTimeout !== undefined) {
|
||||
connectConfig.readyTimeout = config.readyTimeout
|
||||
}
|
||||
if (config.keepaliveInterval !== undefined) {
|
||||
connectConfig.keepaliveInterval = config.keepaliveInterval
|
||||
}
|
||||
|
||||
if (hasPrivateKey) {
|
||||
connectConfig.privateKey = config.privateKey!
|
||||
if (config.passphrase && config.passphrase.trim() !== '') {
|
||||
connectConfig.passphrase = config.passphrase
|
||||
}
|
||||
} else if (hasPassword) {
|
||||
connectConfig.password = config.password!
|
||||
}
|
||||
|
||||
client.on('ready', () => {
|
||||
resolve(client)
|
||||
})
|
||||
|
||||
client.on('error', (err) => {
|
||||
reject(formatSftpError(err, { host, port }))
|
||||
})
|
||||
|
||||
try {
|
||||
client.connect(connectConfig)
|
||||
} catch (err) {
|
||||
reject(formatSftpError(toError(err), { host, port }))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets SFTP subsystem from SSH client
|
||||
*/
|
||||
export function getSftp(client: Client): Promise<SFTPWrapper> {
|
||||
return new Promise((resolve, reject) => {
|
||||
client.sftp((err, sftp) => {
|
||||
if (err) {
|
||||
reject(new Error(`Failed to start SFTP session: ${err.message}`))
|
||||
} else {
|
||||
resolve(sftp)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes a remote path to prevent path traversal attacks.
|
||||
* Removes null bytes, normalizes path separators, and collapses traversal sequences.
|
||||
* Based on OWASP Path Traversal prevention guidelines.
|
||||
*/
|
||||
export function sanitizePath(path: string): string {
|
||||
let sanitized = path
|
||||
sanitized = sanitized.replace(/\0/g, '')
|
||||
sanitized = decodeURIComponent(sanitized)
|
||||
sanitized = sanitized.replace(/\\/g, '/')
|
||||
sanitized = sanitized.replace(/\/+/g, '/')
|
||||
sanitized = sanitized.trim()
|
||||
return sanitized
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes a filename to prevent path traversal and injection attacks.
|
||||
* Removes directory traversal sequences, path separators, null bytes, and dangerous patterns.
|
||||
* Based on OWASP Input Validation Cheat Sheet recommendations.
|
||||
*/
|
||||
export function sanitizeFileName(fileName: string): string {
|
||||
let sanitized = fileName
|
||||
sanitized = sanitized.replace(/\0/g, '')
|
||||
|
||||
try {
|
||||
sanitized = decodeURIComponent(sanitized)
|
||||
} catch {
|
||||
// Keep original if decode fails (malformed encoding)
|
||||
}
|
||||
|
||||
sanitized = sanitized.replace(/\.\.[/\\]?/g, '')
|
||||
sanitized = sanitized.replace(/[/\\]/g, '_')
|
||||
sanitized = sanitized.replace(/^\.+/, '')
|
||||
sanitized = sanitized.replace(/[\x00-\x1f\x7f]/g, '')
|
||||
sanitized = sanitized.trim()
|
||||
|
||||
return sanitized || 'unnamed_file'
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a path doesn't contain traversal sequences.
|
||||
* Returns true if the path is safe, false if it contains potential traversal attacks.
|
||||
*/
|
||||
export function isPathSafe(path: string): boolean {
|
||||
const normalizedPath = path.replace(/\\/g, '/')
|
||||
|
||||
if (normalizedPath.includes('../') || normalizedPath.includes('..\\')) {
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = decodeURIComponent(normalizedPath)
|
||||
if (decoded.includes('../') || decoded.includes('..\\')) {
|
||||
return false
|
||||
}
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
|
||||
if (normalizedPath.includes('\0')) {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses file permissions from mode bits to octal string representation.
|
||||
*/
|
||||
export function parsePermissions(mode: number): string {
|
||||
return `0${(mode & 0o777).toString(8)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines file type from SFTP attributes mode bits.
|
||||
*/
|
||||
export function getFileType(attrs: Attributes): 'file' | 'directory' | 'symlink' | 'other' {
|
||||
const fileType = attrs.mode & S_IFMT
|
||||
|
||||
if (fileType === S_IFDIR) return 'directory'
|
||||
if (fileType === S_IFREG) return 'file'
|
||||
if (fileType === S_IFLNK) return 'symlink'
|
||||
return 'other'
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a path exists on the SFTP server.
|
||||
*/
|
||||
export function sftpExists(sftp: SFTPWrapper, path: string): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
sftp.stat(path, (err) => {
|
||||
resolve(!err)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a path is a directory on the SFTP server.
|
||||
*/
|
||||
export function sftpIsDirectory(sftp: SFTPWrapper, path: string): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
sftp.stat(path, (err, stats) => {
|
||||
if (err) {
|
||||
resolve(false)
|
||||
} else {
|
||||
resolve(getFileType(stats) === 'directory')
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user