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

This commit is contained in:
wehub-resource-sync
2026-07-13 13:20:55 +08:00
commit d25d482dc2
13754 changed files with 4996608 additions and 0 deletions
@@ -0,0 +1,90 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import { sshCheckCommandExistsContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { createSSHConnection, escapeShellArg, executeSSHCommand } from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHCheckCommandExistsAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH check command exists attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshCheckCommandExistsContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(
`[${requestId}] Checking if command '${params.commandName}' exists on ${params.host}:${params.port}`
)
const client = await createSSHConnection({
host: params.host,
port: params.port,
username: params.username,
password: params.password,
privateKey: params.privateKey,
passphrase: params.passphrase,
})
try {
const escapedCommand = escapeShellArg(params.commandName)
const result = await executeSSHCommand(
client,
`command -v '${escapedCommand}' 2>/dev/null || which '${escapedCommand}' 2>/dev/null`
)
const exists = result.exitCode === 0 && result.stdout.trim().length > 0
const path = exists ? result.stdout.trim() : undefined
let version: string | undefined
if (exists) {
try {
const versionResult = await executeSSHCommand(
client,
`'${escapedCommand}' --version 2>&1 | head -1 || '${escapedCommand}' -v 2>&1 | head -1`
)
if (versionResult.exitCode === 0 && versionResult.stdout.trim()) {
version = versionResult.stdout.trim()
}
} catch {
// Version check failed, that's okay
}
}
logger.info(
`[${requestId}] Command '${params.commandName}' ${exists ? 'exists' : 'does not exist'}`
)
return NextResponse.json({
exists,
path,
version,
message: exists
? `Command '${params.commandName}' found at ${path}`
: `Command '${params.commandName}' not found`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH check command exists failed:`, error)
return NextResponse.json(
{ error: `SSH check command exists failed: ${errorMessage}` },
{ status: 500 }
)
}
})
@@ -0,0 +1,118 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import type { Client, SFTPWrapper, Stats } from 'ssh2'
import { sshCheckFileExistsContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import {
createSSHConnection,
getFileType,
parsePermissions,
sanitizePath,
} from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHCheckFileExistsAPI')
function getSFTP(client: Client): Promise<SFTPWrapper> {
return new Promise((resolve, reject) => {
client.sftp((err, sftp) => {
if (err) {
reject(err)
} else {
resolve(sftp)
}
})
})
}
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH check file exists attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshCheckFileExistsContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(
`[${requestId}] Checking if path exists: ${params.path} on ${params.host}:${params.port}`
)
const client = await createSSHConnection({
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 filePath = sanitizePath(params.path)
const stats = await new Promise<Stats | null>((resolve) => {
sftp.stat(filePath, (err, stats) => {
if (err) {
resolve(null)
} else {
resolve(stats)
}
})
})
if (!stats) {
logger.info(`[${requestId}] Path does not exist: ${filePath}`)
return NextResponse.json({
exists: false,
type: 'not_found',
message: `Path does not exist: ${filePath}`,
})
}
const fileType = getFileType(stats)
// Check if the type matches the expected type
if (params.type !== 'any' && fileType !== params.type) {
logger.info(`[${requestId}] Path exists but is not a ${params.type}: ${filePath}`)
return NextResponse.json({
exists: false,
type: fileType,
size: stats.size,
permissions: parsePermissions(stats.mode),
modified: new Date((stats.mtime || 0) * 1000).toISOString(),
message: `Path exists but is a ${fileType}, not a ${params.type}`,
})
}
logger.info(`[${requestId}] Path exists: ${filePath} (${fileType})`)
return NextResponse.json({
exists: true,
type: fileType,
size: stats.size,
permissions: parsePermissions(stats.mode),
modified: new Date((stats.mtime || 0) * 1000).toISOString(),
message: `Path exists: ${filePath} (${fileType})`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH check file exists failed:`, error)
return NextResponse.json(
{ error: `SSH check file exists failed: ${errorMessage}` },
{ status: 500 }
)
}
})
@@ -0,0 +1,91 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import { sshCreateDirectoryContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import {
createSSHConnection,
escapeShellArg,
executeSSHCommand,
sanitizePath,
} from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHCreateDirectoryAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH create directory attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshCreateDirectoryContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(`[${requestId}] Creating directory ${params.path} on ${params.host}:${params.port}`)
const client = await createSSHConnection({
host: params.host,
port: params.port,
username: params.username,
password: params.password,
privateKey: params.privateKey,
passphrase: params.passphrase,
})
try {
const dirPath = sanitizePath(params.path)
const escapedPath = escapeShellArg(dirPath)
const checkResult = await executeSSHCommand(
client,
`test -d '${escapedPath}' && echo "exists"`
)
const alreadyExists = checkResult.stdout.trim() === 'exists'
if (alreadyExists) {
logger.info(`[${requestId}] Directory already exists: ${dirPath}`)
return NextResponse.json({
created: false,
path: dirPath,
alreadyExists: true,
message: `Directory already exists: ${dirPath}`,
})
}
const mkdirFlag = params.recursive ? '-p' : ''
const command = `mkdir ${mkdirFlag} -m ${params.permissions} '${escapedPath}'`
const result = await executeSSHCommand(client, command)
if (result.exitCode !== 0) {
throw new Error(result.stderr || 'Failed to create directory')
}
logger.info(`[${requestId}] Directory created successfully: ${dirPath}`)
return NextResponse.json({
created: true,
path: dirPath,
alreadyExists: false,
message: `Directory created successfully: ${dirPath}`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH create directory failed:`, error)
return NextResponse.json(
{ error: `SSH create directory failed: ${errorMessage}` },
{ status: 500 }
)
}
})
@@ -0,0 +1,84 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import { sshDeleteFileContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import {
createSSHConnection,
escapeShellArg,
executeSSHCommand,
sanitizePath,
} from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHDeleteFileAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH delete file attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshDeleteFileContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(`[${requestId}] Deleting ${params.path} on ${params.host}:${params.port}`)
const client = await createSSHConnection({
host: params.host,
port: params.port,
username: params.username,
password: params.password,
privateKey: params.privateKey,
passphrase: params.passphrase,
})
try {
const filePath = sanitizePath(params.path)
const escapedPath = escapeShellArg(filePath)
const checkResult = await executeSSHCommand(
client,
`test -e '${escapedPath}' && echo "exists"`
)
if (checkResult.stdout.trim() !== 'exists') {
return NextResponse.json({ error: `Path does not exist: ${filePath}` }, { status: 404 })
}
let command: string
if (params.recursive) {
command = params.force ? `rm -rf '${escapedPath}'` : `rm -r '${escapedPath}'`
} else {
command = params.force ? `rm -f '${escapedPath}'` : `rm '${escapedPath}'`
}
const result = await executeSSHCommand(client, command)
if (result.exitCode !== 0) {
throw new Error(result.stderr || 'Failed to delete path')
}
logger.info(`[${requestId}] Path deleted successfully: ${filePath}`)
return NextResponse.json({
deleted: true,
path: filePath,
message: `Successfully deleted: ${filePath}`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH delete file failed:`, error)
return NextResponse.json({ error: `SSH delete file failed: ${errorMessage}` }, { status: 500 })
}
})
@@ -0,0 +1,131 @@
import path from 'path'
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import type { Client, SFTPWrapper } from 'ssh2'
import { sshDownloadFileContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { getFileExtension, getMimeTypeFromExtension } from '@/lib/uploads/utils/file-utils'
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHDownloadFileAPI')
function getSFTP(client: Client): Promise<SFTPWrapper> {
return new Promise((resolve, reject) => {
client.sftp((err, sftp) => {
if (err) {
reject(err)
} else {
resolve(sftp)
}
})
})
}
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH download file attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshDownloadFileContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(
`[${requestId}] Downloading file from ${params.host}:${params.port}${params.remotePath}`
)
const client = await createSSHConnection({
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)
// Check if file exists
const stats = await new Promise<{ size: number }>((resolve, reject) => {
sftp.stat(remotePath, (err, stats) => {
if (err) {
reject(new Error(`File not found: ${remotePath}`))
} else {
resolve(stats)
}
})
})
// Check file size limit (50MB to prevent memory exhaustion)
const maxSize = 50 * 1024 * 1024
if (stats.size > maxSize) {
const sizeMB = (stats.size / (1024 * 1024)).toFixed(2)
return NextResponse.json(
{ error: `File size (${sizeMB}MB) exceeds download limit of 50MB` },
{ status: 400 }
)
}
// Read file content
const content = await new Promise<Buffer>((resolve, reject) => {
const chunks: Buffer[] = []
const readStream = sftp.createReadStream(remotePath)
readStream.on('data', (chunk: Buffer) => {
chunks.push(chunk)
})
readStream.on('end', () => {
resolve(Buffer.concat(chunks))
})
readStream.on('error', reject)
})
const fileName = path.basename(remotePath)
const extension = getFileExtension(fileName)
const mimeType = getMimeTypeFromExtension(extension)
// Encode content as base64 for binary safety
const base64Content = content.toString('base64')
logger.info(`[${requestId}] File downloaded successfully from ${remotePath}`)
return NextResponse.json({
downloaded: true,
file: {
name: fileName,
mimeType,
data: base64Content,
size: stats.size,
},
content: base64Content,
fileName: fileName,
remotePath: remotePath,
size: stats.size,
message: `File downloaded successfully from ${remotePath}`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH file download failed:`, error)
return NextResponse.json(
{ error: `SSH file download failed: ${errorMessage}` },
{ status: 500 }
)
}
})
@@ -0,0 +1,73 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import { sshExecuteCommandContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import {
createSSHConnection,
escapeShellArg,
executeSSHCommand,
sanitizeCommand,
} from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHExecuteCommandAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH execute command attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshExecuteCommandContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(`[${requestId}] Executing SSH command on ${params.host}:${params.port}`)
const client = await createSSHConnection({
host: params.host,
port: params.port,
username: params.username,
password: params.password,
privateKey: params.privateKey,
passphrase: params.passphrase,
})
try {
let command = sanitizeCommand(params.command)
if (params.workingDirectory) {
const escapedWorkDir = escapeShellArg(params.workingDirectory)
command = `cd '${escapedWorkDir}' && ${command}`
}
const result = await executeSSHCommand(client, command)
logger.info(`[${requestId}] Command executed successfully with exit code ${result.exitCode}`)
return NextResponse.json({
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
success: result.exitCode === 0,
message: `Command executed with exit code ${result.exitCode}`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH command execution failed:`, error)
return NextResponse.json(
{ error: `SSH command execution failed: ${errorMessage}` },
{ status: 500 }
)
}
})
@@ -0,0 +1,85 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import { sshExecuteScriptContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { createSSHConnection, escapeShellArg, executeSSHCommand } from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHExecuteScriptAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH execute script attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshExecuteScriptContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(`[${requestId}] Executing SSH script on ${params.host}:${params.port}`)
const client = await createSSHConnection({
host: params.host,
port: params.port,
username: params.username,
password: params.password,
privateKey: params.privateKey,
passphrase: params.passphrase,
})
try {
const scriptPath = `/tmp/sim_script_${requestId}.sh`
const escapedScriptPath = escapeShellArg(scriptPath)
const escapedInterpreter = escapeShellArg(params.interpreter)
const heredocDelimiter = `SIMEOF_${generateId().replace(/-/g, '')}`
let command = `cat > '${escapedScriptPath}' << '${heredocDelimiter}'
${params.script}
${heredocDelimiter}
chmod +x '${escapedScriptPath}'`
if (params.workingDirectory) {
const escapedWorkDir = escapeShellArg(params.workingDirectory)
command += `
cd '${escapedWorkDir}'`
}
command += `
'${escapedInterpreter}' '${escapedScriptPath}'
exit_code=$?
rm -f '${escapedScriptPath}'
exit $exit_code`
const result = await executeSSHCommand(client, command)
logger.info(`[${requestId}] Script executed successfully with exit code ${result.exitCode}`)
return NextResponse.json({
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
success: result.exitCode === 0,
scriptPath: scriptPath,
message: `Script executed with exit code ${result.exitCode}`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH script execution failed:`, error)
return NextResponse.json(
{ error: `SSH script execution failed: ${errorMessage}` },
{ status: 500 }
)
}
})
@@ -0,0 +1,111 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import { sshGetSystemInfoContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { createSSHConnection, executeSSHCommand } from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHGetSystemInfoAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH get system info attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshGetSystemInfoContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(`[${requestId}] Getting system info from ${params.host}:${params.port}`)
const client = await createSSHConnection({
host: params.host,
port: params.port,
username: params.username,
password: params.password,
privateKey: params.privateKey,
passphrase: params.passphrase,
})
try {
// Get hostname
const hostnameResult = await executeSSHCommand(client, 'hostname')
const hostname = hostnameResult.stdout.trim()
// Get OS info
const osResult = await executeSSHCommand(client, 'uname -s')
const os = osResult.stdout.trim()
// Get architecture
const archResult = await executeSSHCommand(client, 'uname -m')
const architecture = archResult.stdout.trim()
// Get uptime in seconds
const uptimeResult = await executeSSHCommand(
client,
"cat /proc/uptime 2>/dev/null | awk '{print int($1)}' || sysctl -n kern.boottime 2>/dev/null | awk '{print int(($(date +%s)) - $4)}'"
)
const uptime = Number.parseInt(uptimeResult.stdout.trim()) || 0
// Get memory info
const memoryResult = await executeSSHCommand(
client,
"free -b 2>/dev/null | awk '/Mem:/ {print $2, $7, $3}' || vm_stat 2>/dev/null | awk '/Pages free|Pages active|Pages speculative|Pages wired|page size/ {gsub(/[^0-9]/, \"\"); print}'"
)
const memParts = memoryResult.stdout.trim().split(/\s+/)
let memory = { total: 0, free: 0, used: 0 }
if (memParts.length >= 3) {
memory = {
total: Number.parseInt(memParts[0]) || 0,
free: Number.parseInt(memParts[1]) || 0,
used: Number.parseInt(memParts[2]) || 0,
}
}
// Get disk space
const diskResult = await executeSSHCommand(
client,
"df -B1 / 2>/dev/null | awk 'NR==2 {print $2, $4, $3}' || df -k / 2>/dev/null | awk 'NR==2 {print $2*1024, $4*1024, $3*1024}'"
)
const diskParts = diskResult.stdout.trim().split(/\s+/)
let diskSpace = { total: 0, free: 0, used: 0 }
if (diskParts.length >= 3) {
diskSpace = {
total: Number.parseInt(diskParts[0]) || 0,
free: Number.parseInt(diskParts[1]) || 0,
used: Number.parseInt(diskParts[2]) || 0,
}
}
logger.info(`[${requestId}] System info retrieved successfully`)
return NextResponse.json({
hostname,
os,
architecture,
uptime,
memory,
diskSpace,
message: `System info retrieved for ${hostname}`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH get system info failed:`, error)
return NextResponse.json(
{ error: `SSH get system info failed: ${errorMessage}` },
{ status: 500 }
)
}
})
@@ -0,0 +1,115 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import type { Client, FileEntry, SFTPWrapper } from 'ssh2'
import { sshListDirectoryContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import {
createSSHConnection,
getFileType,
parsePermissions,
sanitizePath,
} from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHListDirectoryAPI')
function getSFTP(client: Client): Promise<SFTPWrapper> {
return new Promise((resolve, reject) => {
client.sftp((err, sftp) => {
if (err) {
reject(err)
} else {
resolve(sftp)
}
})
})
}
interface FileInfo {
name: string
type: 'file' | 'directory' | 'symlink' | 'other'
size: number
permissions: string
modified: string
}
async function listDir(sftp: SFTPWrapper, dirPath: string): Promise<FileEntry[]> {
return new Promise((resolve, reject) => {
sftp.readdir(dirPath, (err, list) => {
if (err) {
reject(err)
} else {
resolve(list)
}
})
})
}
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH list directory attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshListDirectoryContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(`[${requestId}] Listing directory ${params.path} on ${params.host}:${params.port}`)
const client = await createSSHConnection({
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 dirPath = sanitizePath(params.path)
const list = await listDir(sftp, dirPath)
const entries: FileInfo[] = list.map((entry) => ({
name: entry.filename,
type: getFileType(entry.attrs),
size: entry.attrs.size,
permissions: parsePermissions(entry.attrs.mode),
modified: new Date((entry.attrs.mtime || 0) * 1000).toISOString(),
}))
const totalFiles = entries.filter((e) => e.type === 'file').length
const totalDirectories = entries.filter((e) => e.type === 'directory').length
logger.info(
`[${requestId}] Directory listed successfully: ${totalFiles} files, ${totalDirectories} directories`
)
return NextResponse.json({
entries,
totalFiles,
totalDirectories,
message: `Found ${totalFiles} files and ${totalDirectories} directories`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH list directory failed:`, error)
return NextResponse.json(
{ error: `SSH list directory failed: ${errorMessage}` },
{ status: 500 }
)
}
})
@@ -0,0 +1,101 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import { sshMoveRenameContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import {
createSSHConnection,
escapeShellArg,
executeSSHCommand,
sanitizePath,
} from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHMoveRenameAPI')
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH move/rename attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshMoveRenameContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(
`[${requestId}] Moving ${params.sourcePath} to ${params.destinationPath} on ${params.host}:${params.port}`
)
const client = await createSSHConnection({
host: params.host,
port: params.port,
username: params.username,
password: params.password,
privateKey: params.privateKey,
passphrase: params.passphrase,
})
try {
const sourcePath = sanitizePath(params.sourcePath)
const destPath = sanitizePath(params.destinationPath)
const escapedSource = escapeShellArg(sourcePath)
const escapedDest = escapeShellArg(destPath)
const sourceCheck = await executeSSHCommand(
client,
`test -e '${escapedSource}' && echo "exists"`
)
if (sourceCheck.stdout.trim() !== 'exists') {
return NextResponse.json(
{ error: `Source path does not exist: ${sourcePath}` },
{ status: 404 }
)
}
if (!params.overwrite) {
const destCheck = await executeSSHCommand(
client,
`test -e '${escapedDest}' && echo "exists"`
)
if (destCheck.stdout.trim() === 'exists') {
return NextResponse.json(
{ error: `Destination already exists and overwrite is disabled: ${destPath}` },
{ status: 409 }
)
}
}
const command = params.overwrite
? `mv -f '${escapedSource}' '${escapedDest}'`
: `mv '${escapedSource}' '${escapedDest}'`
const result = await executeSSHCommand(client, command)
if (result.exitCode !== 0) {
throw new Error(result.stderr || 'Failed to move/rename')
}
logger.info(`[${requestId}] Successfully moved ${sourcePath} to ${destPath}`)
return NextResponse.json({
success: true,
sourcePath,
destinationPath: destPath,
message: `Successfully moved ${sourcePath} to ${destPath}`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH move/rename failed:`, error)
return NextResponse.json({ error: `SSH move/rename failed: ${errorMessage}` }, { status: 500 })
}
})
@@ -0,0 +1,123 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import type { Client, SFTPWrapper } from 'ssh2'
import { sshReadFileContentContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHReadFileContentAPI')
function getSFTP(client: Client): Promise<SFTPWrapper> {
return new Promise((resolve, reject) => {
client.sftp((err, sftp) => {
if (err) {
reject(err)
} else {
resolve(sftp)
}
})
})
}
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH read file content attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshReadFileContentContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(
`[${requestId}] Reading file content from ${params.path} on ${params.host}:${params.port}`
)
const client = await createSSHConnection({
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 filePath = sanitizePath(params.path)
const maxBytes = params.maxSize * 1024 * 1024 // Convert MB to bytes
const stats = await new Promise<{ size: number }>((resolve, reject) => {
sftp.stat(filePath, (err, stats) => {
if (err) {
reject(new Error(`File not found: ${filePath}`))
} else {
resolve(stats)
}
})
})
if (stats.size > maxBytes) {
return NextResponse.json(
{ error: `File size (${stats.size} bytes) exceeds maximum allowed (${maxBytes} bytes)` },
{ status: 400 }
)
}
const content = await new Promise<string>((resolve, reject) => {
const chunks: Buffer[] = []
let totalBytes = 0
const readStream = sftp.createReadStream(filePath)
readStream.on('data', (chunk: Buffer) => {
totalBytes += chunk.length
if (totalBytes > maxBytes) {
readStream.destroy()
reject(new Error(`File exceeds maximum allowed size of ${params.maxSize}MB`))
return
}
chunks.push(chunk)
})
readStream.on('end', () => {
const buffer = Buffer.concat(chunks)
resolve(buffer.toString(params.encoding as BufferEncoding))
})
readStream.on('error', reject)
})
const lines = content.split('\n').length
logger.info(
`[${requestId}] File content read successfully: ${stats.size} bytes, ${lines} lines`
)
return NextResponse.json({
content,
size: stats.size,
lines,
path: filePath,
message: `File read successfully: ${stats.size} bytes, ${lines} lines`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH read file content failed:`, error)
return NextResponse.json(
{ error: `SSH read file content failed: ${errorMessage}` },
{ status: 500 }
)
}
})
@@ -0,0 +1,111 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import type { Client, SFTPWrapper } from 'ssh2'
import { sshUploadFileContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHUploadFileAPI')
function getSFTP(client: Client): Promise<SFTPWrapper> {
return new Promise((resolve, reject) => {
client.sftp((err, sftp) => {
if (err) {
reject(err)
} else {
resolve(sftp)
}
})
})
}
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH upload file attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshUploadFileContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(
`[${requestId}] Uploading file to ${params.host}:${params.port}${params.remotePath}`
)
const client = await createSSHConnection({
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)
if (!params.overwrite) {
const exists = await new Promise<boolean>((resolve) => {
sftp.stat(remotePath, (err) => {
resolve(!err)
})
})
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(remotePath, {
mode: params.permissions ? Number.parseInt(params.permissions, 8) : 0o644,
})
writeStream.on('error', reject)
writeStream.on('close', () => resolve())
writeStream.end(content)
})
logger.info(`[${requestId}] File uploaded successfully to ${remotePath}`)
return NextResponse.json({
uploaded: true,
remotePath: remotePath,
size: content.length,
message: `File uploaded successfully to ${remotePath}`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH file upload failed:`, error)
return NextResponse.json({ error: `SSH file upload failed: ${errorMessage}` }, { status: 500 })
}
})
+402
View File
@@ -0,0 +1,402 @@
import { createLogger } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { type Attributes, Client, type ConnectConfig } from 'ssh2'
import { validateDatabaseHost } from '@/lib/core/security/input-validation.server'
const logger = createLogger('SSHUtils')
// File type constants from POSIX
const S_IFMT = 0o170000 // bit mask for the file type bit field
const S_IFDIR = 0o040000 // directory
const S_IFREG = 0o100000 // regular file
const S_IFLNK = 0o120000 // symbolic link
export interface SSHConnectionConfig {
host: string
port: number
username: string
password?: string | null
privateKey?: string | null
passphrase?: string | null
timeout?: number
keepaliveInterval?: number
readyTimeout?: number
}
export interface SSHCommandResult {
stdout: string
stderr: string
exitCode: number
}
/**
* Format SSH error with helpful troubleshooting context
*/
function formatSSHError(err: Error, config: { host: string; port: number }): Error {
const errorMessage = err.message.toLowerCase()
const host = config.host
const port = config.port
if (errorMessage.includes('econnrefused') || errorMessage.includes('connection refused')) {
return new Error(
`Connection refused to ${host}:${port}. ` +
`Please verify: (1) SSH server is running on the target machine, ` +
`(2) Port ${port} is correct (default SSH port is 22), ` +
`(3) Firewall allows connections to port ${port}.`
)
}
if (errorMessage.includes('econnreset') || errorMessage.includes('connection reset')) {
return new Error(
`Connection reset by ${host}:${port}. ` +
`This usually means: (1) Wrong port number (SSH default is 22), ` +
`(2) Server rejected the connection, ` +
`(3) Network/firewall interrupted the connection. ` +
`Verify your SSH server configuration and port number.`
)
}
if (errorMessage.includes('etimedout') || errorMessage.includes('timeout')) {
return new Error(
`Connection timed out to ${host}:${port}. ` +
`Please verify: (1) Host "${host}" is reachable, ` +
`(2) No firewall is blocking the connection, ` +
`(3) The SSH 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 for user on ${host}:${port}. ` +
`Please verify: (1) Username is correct, ` +
`(2) Password or private key is valid, ` +
`(3) User has SSH 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. ` +
`The key should start with "-----BEGIN" and end 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 to this server or the server's key has changed.`
)
}
return new Error(`SSH connection to ${host}:${port} failed: ${err.message}`)
}
/**
* Create an SSH connection using the provided configuration
*
* Uses ssh2 library defaults which align with OpenSSH standards:
* - readyTimeout: 20000ms (20 seconds)
* - keepaliveInterval: 0 (disabled, same as OpenSSH ServerAliveInterval)
* - keepaliveCountMax: 3 (same as OpenSSH ServerAliveCountMax)
*/
export async function createSSHConnection(config: SSHConnectionConfig): 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(formatSSHError(err, { host, port }))
})
try {
client.connect(connectConfig)
} catch (err) {
reject(formatSSHError(toError(err), { host, port }))
}
})
}
const MAX_OUTPUT_BYTES = 16 * 1024 * 1024
/**
* Execute a command on the SSH connection
*/
export function executeSSHCommand(client: Client, command: string): Promise<SSHCommandResult> {
return new Promise((resolve, reject) => {
client.exec(command, (err, stream) => {
if (err) {
reject(err)
return
}
let stdout = ''
let stderr = ''
let stdoutBytes = 0
let stderrBytes = 0
let stdoutTruncated = false
let stderrTruncated = false
stream.on('close', (code: number) => {
resolve({
stdout: stdoutTruncated
? `${stdout.trim()}\n[output truncated: exceeded 16MB limit]`
: stdout.trim(),
stderr: stderrTruncated
? `${stderr.trim()}\n[stderr truncated: exceeded 16MB limit]`
: stderr.trim(),
exitCode: code ?? -1,
})
})
stream.on('data', (data: Buffer) => {
const remaining = MAX_OUTPUT_BYTES - stdoutBytes
if (remaining <= 0) {
stdoutTruncated = true
return
}
const chunk = data.subarray(0, remaining)
stdout += chunk.toString()
stdoutBytes += chunk.length
if (data.length > remaining) stdoutTruncated = true
})
stream.stderr.on('data', (data: Buffer) => {
const remaining = MAX_OUTPUT_BYTES - stderrBytes
if (remaining <= 0) {
stderrTruncated = true
return
}
const chunk = data.subarray(0, remaining)
stderr += chunk.toString()
stderrBytes += chunk.length
if (data.length > remaining) stderrTruncated = true
})
})
})
}
/**
* Sanitize command input to prevent command injection
*
* Removes null bytes and other dangerous control characters while preserving
* legitimate shell syntax. Logs warnings for potentially dangerous patterns.
*
* Note: This function does not block complex shell commands (pipes, redirects, etc.)
* as users legitimately need these features for remote command execution.
*
* @param command - The command to sanitize
* @returns The sanitized command string
*
* @example
* ```typescript
* const safeCommand = sanitizeCommand(userInput)
* // Use safeCommand for SSH execution
* ```
*/
export function sanitizeCommand(command: string): string {
let sanitized = command.replace(/\0/g, '')
sanitized = sanitized.replace(/[\x0B\x0C]/g, '')
sanitized = sanitized.trim()
const dangerousPatterns = [
{ pattern: /\$\(.*\)/, name: 'command substitution $()' },
{ pattern: /`.*`/, name: 'backtick command substitution' },
{ pattern: /;\s*rm\s+-rf/i, name: 'destructive rm -rf command' },
{ pattern: /;\s*dd\s+/i, name: 'dd command (disk operations)' },
{ pattern: /mkfs/i, name: 'filesystem formatting command' },
{ pattern: />\s*\/dev\/sd[a-z]/i, name: 'direct disk write' },
]
for (const { pattern, name } of dangerousPatterns) {
if (pattern.test(sanitized)) {
logger.warn(`Command contains ${name}`, {
command: sanitized.substring(0, 100) + (sanitized.length > 100 ? '...' : ''),
})
}
}
return sanitized
}
/**
* Sanitize and validate file path to prevent path traversal attacks
*
* This function validates that a file path does not contain:
* - Null bytes
* - Path traversal sequences (.. or ../)
* - URL-encoded path traversal attempts
*
* @param path - The file path to sanitize and validate
* @returns The sanitized path if valid
* @throws Error if path traversal is detected
*
* @example
* ```typescript
* try {
* const safePath = sanitizePath(userInput)
* // Use safePath safely
* } catch (error) {
* // Handle invalid path
* }
* ```
*/
export function sanitizePath(path: string): string {
let sanitized = path.replace(/\0/g, '')
sanitized = sanitized.trim()
if (sanitized.includes('%00')) {
logger.warn('Path contains URL-encoded null bytes', {
path: path.substring(0, 100),
})
throw new Error('Path contains invalid characters')
}
const pathTraversalPatterns = [
'../', // Standard Unix path traversal
'..\\', // Windows path traversal
'/../', // Mid-path traversal
'\\..\\', // Windows mid-path traversal
'%2e%2e%2f', // Fully encoded ../
'%2e%2e/', // Partially encoded ../
'%2e%2e%5c', // Fully encoded ..\
'%2e%2e\\', // Partially encoded ..\
'..%2f', // .. with encoded /
'..%5c', // .. with encoded \
'%252e%252e', // Double URL encoded ..
'..%252f', // .. with double encoded /
'..%255c', // .. with double encoded \
]
const lowerPath = sanitized.toLowerCase()
for (const pattern of pathTraversalPatterns) {
if (lowerPath.includes(pattern.toLowerCase())) {
logger.warn('Path traversal attempt detected', {
pattern,
path: path.substring(0, 100),
})
throw new Error('Path contains invalid path traversal sequences')
}
}
const segments = sanitized.split(/[/\\]/)
for (const segment of segments) {
if (segment === '..') {
logger.warn('Path traversal attempt detected (.. as path segment)', {
path: path.substring(0, 100),
})
throw new Error('Path contains invalid path traversal sequences')
}
}
return sanitized
}
/**
* Escape a string for safe use in single-quoted shell arguments
* This is standard practice for shell command construction.
* e.g., "/tmp/test'file" becomes "/tmp/test'\''file"
*
* The pattern 'foo'\''bar' works because:
* - First ' ends the current single-quoted string
* - \' inserts a literal single quote (escaped outside quotes)
* - Next ' starts a new single-quoted string
*/
export function escapeShellArg(arg: string): string {
return arg.replace(/'/g, "'\\''")
}
/**
* Validate that authentication credentials are provided
*/
export function validateAuth(params: { password?: string; privateKey?: string }): {
isValid: boolean
error?: string
} {
if (!params.password && !params.privateKey) {
return {
isValid: false,
error: 'Either password or privateKey must be provided for authentication',
}
}
return { isValid: true }
}
/**
* Parse file permissions from octal string
*/
export function parsePermissions(mode: number): string {
return `0${(mode & 0o777).toString(8)}`
}
/**
* Get file type from attributes mode bits
*/
export function getFileType(attrs: Attributes): 'file' | 'directory' | 'symlink' | 'other' {
const mode = attrs.mode
const fileType = mode & S_IFMT
if (fileType === S_IFDIR) return 'directory'
if (fileType === S_IFREG) return 'file'
if (fileType === S_IFLNK) return 'symlink'
return 'other'
}
@@ -0,0 +1,134 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import type { Client, SFTPWrapper } from 'ssh2'
import { sshWriteFileContentContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
const logger = createLogger('SSHWriteFileContentAPI')
function getSFTP(client: Client): Promise<SFTPWrapper> {
return new Promise((resolve, reject) => {
client.sftp((err, sftp) => {
if (err) {
reject(err)
} else {
resolve(sftp)
}
})
})
}
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const auth = await checkInternalAuth(request)
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized SSH write file content attempt`)
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(sshWriteFileContentContract, request, {})
if (!parsed.success) return parsed.response
const params = parsed.data.body
logger.info(
`[${requestId}] Writing file content to ${params.path} on ${params.host}:${params.port} (mode: ${params.mode})`
)
const client = await createSSHConnection({
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 filePath = sanitizePath(params.path)
// Check if file exists for 'create' mode
if (params.mode === 'create') {
const exists = await new Promise<boolean>((resolve) => {
sftp.stat(filePath, (err) => {
resolve(!err)
})
})
if (exists) {
return NextResponse.json(
{ error: `File already exists and mode is 'create': ${filePath}` },
{ status: 409 }
)
}
}
// Handle append mode by reading existing content first
let finalContent = params.content
if (params.mode === 'append') {
const existingContent = await new Promise<string>((resolve) => {
const chunks: Buffer[] = []
const readStream = sftp.createReadStream(filePath)
readStream.on('data', (chunk: Buffer) => {
chunks.push(chunk)
})
readStream.on('end', () => {
resolve(Buffer.concat(chunks).toString('utf-8'))
})
readStream.on('error', () => {
resolve('')
})
})
finalContent = existingContent + params.content
}
// Write file
const fileMode = params.permissions ? Number.parseInt(params.permissions, 8) : 0o644
await new Promise<void>((resolve, reject) => {
const writeStream = sftp.createWriteStream(filePath, { mode: fileMode })
writeStream.on('error', reject)
writeStream.on('close', () => resolve())
writeStream.end(Buffer.from(finalContent, 'utf-8'))
})
// Get final file size
const stats = await new Promise<{ size: number }>((resolve, reject) => {
sftp.stat(filePath, (err, stats) => {
if (err) reject(err)
else resolve(stats)
})
})
logger.info(`[${requestId}] File written successfully: ${stats.size} bytes`)
return NextResponse.json({
written: true,
path: filePath,
size: stats.size,
message: `File written successfully: ${stats.size} bytes`,
})
} finally {
client.end()
}
} catch (error) {
const errorMessage = getErrorMessage(error, 'Unknown error occurred')
logger.error(`[${requestId}] SSH write file content failed:`, error)
return NextResponse.json(
{ error: `SSH write file content failed: ${errorMessage}` },
{ status: 500 }
)
}
})