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,103 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { importSkillContract } from '@/lib/api/contracts'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
|
||||
const logger = createLogger('SkillsImportAPI')
|
||||
|
||||
const FETCH_TIMEOUT_MS = 15_000
|
||||
|
||||
/**
|
||||
* Converts a standard GitHub file URL to its raw.githubusercontent.com equivalent.
|
||||
*
|
||||
* Supported formats:
|
||||
* github.com/{owner}/{repo}/blob/{branch}/{path}
|
||||
* raw.githubusercontent.com/{owner}/{repo}/{branch}/{path} (passthrough)
|
||||
*/
|
||||
function toRawGitHubUrl(url: string): string {
|
||||
const parsed = new URL(url)
|
||||
|
||||
if (parsed.hostname === 'raw.githubusercontent.com') {
|
||||
return url
|
||||
}
|
||||
|
||||
if (parsed.hostname !== 'github.com') {
|
||||
throw new Error('Only GitHub URLs are supported')
|
||||
}
|
||||
|
||||
const segments = parsed.pathname.split('/').filter(Boolean)
|
||||
if (segments.length < 5 || segments[2] !== 'blob') {
|
||||
throw new Error(
|
||||
'Invalid GitHub URL format. Expected: https://github.com/{owner}/{repo}/blob/{branch}/{path}'
|
||||
)
|
||||
}
|
||||
|
||||
const [owner, repo, , branch, ...pathParts] = segments
|
||||
return `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/${pathParts.join('/')}`
|
||||
}
|
||||
|
||||
/** POST - Fetch a SKILL.md from a GitHub URL and return its raw content */
|
||||
export const POST = withRouteHandler(async (req: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const authResult = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized skill import attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const validation = await parseRequest(importSkillContract, req, {})
|
||||
if (!validation.success) return validation.response
|
||||
const { url } = validation.data.body
|
||||
|
||||
let rawUrl: string
|
||||
try {
|
||||
rawUrl = toRawGitHubUrl(url)
|
||||
} catch (err) {
|
||||
const message = getErrorMessage(err, 'Invalid URL')
|
||||
return NextResponse.json({ error: message }, { status: 400 })
|
||||
}
|
||||
|
||||
const response = await fetch(rawUrl, {
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
headers: { Accept: 'text/plain' },
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
logger.warn(`[${requestId}] GitHub fetch failed`, {
|
||||
status: response.status,
|
||||
url: rawUrl,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: `Failed to fetch file (HTTP ${response.status}). Is the repository public?` },
|
||||
{ status: 502 }
|
||||
)
|
||||
}
|
||||
|
||||
const contentLength = response.headers.get('content-length')
|
||||
if (contentLength && Number.parseInt(contentLength, 10) > 100_000) {
|
||||
return NextResponse.json({ error: 'File is too large (max 100KB)' }, { status: 400 })
|
||||
}
|
||||
|
||||
const content = await response.text()
|
||||
|
||||
if (content.length > 100_000) {
|
||||
return NextResponse.json({ error: 'File is too large (max 100KB)' }, { status: 400 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ content })
|
||||
} catch (error) {
|
||||
if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {
|
||||
logger.warn(`[${requestId}] GitHub fetch timed out`)
|
||||
return NextResponse.json({ error: 'Request timed out' }, { status: 504 })
|
||||
}
|
||||
|
||||
logger.error(`[${requestId}] Error importing skill`, error)
|
||||
return NextResponse.json({ error: 'Failed to import skill' }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,202 @@
|
||||
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import {
|
||||
deleteSkillQuerySchema,
|
||||
listSkillsQuerySchema,
|
||||
upsertSkillsContract,
|
||||
} from '@/lib/api/contracts'
|
||||
import { parseRequest, validationErrorResponse } from '@/lib/api/server'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { captureServerEvent } from '@/lib/posthog/server'
|
||||
import { isBuiltinSkillId } from '@/lib/workflows/skills/builtin-skills'
|
||||
import { deleteSkill, listSkills, upsertSkills } from '@/lib/workflows/skills/operations'
|
||||
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
|
||||
|
||||
const logger = createLogger('SkillsAPI')
|
||||
|
||||
/** GET - Fetch all skills for a workspace */
|
||||
export const GET = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized skills access attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const userId = authResult.userId
|
||||
const query = listSkillsQuerySchema.safeParse(
|
||||
Object.fromEntries(request.nextUrl.searchParams.entries())
|
||||
)
|
||||
if (!query.success) {
|
||||
logger.warn(`[${requestId}] Invalid skills query`, { errors: query.error.issues })
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid request data', details: query.error.issues },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
const { workspaceId } = query.data
|
||||
|
||||
const userPermission = await getUserEntityPermissions(userId, 'workspace', workspaceId)
|
||||
if (!userPermission) {
|
||||
logger.warn(`[${requestId}] User ${userId} does not have access to workspace ${workspaceId}`)
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
||||
}
|
||||
|
||||
const result = await listSkills({ workspaceId })
|
||||
const data = result.map((s) => ({ ...s, readOnly: isBuiltinSkillId(s.id) }))
|
||||
|
||||
return NextResponse.json({ data }, { status: 200 })
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error fetching skills:`, error)
|
||||
return NextResponse.json({ error: 'Failed to fetch skills' }, { status: 500 })
|
||||
}
|
||||
})
|
||||
|
||||
/** POST - Create or update skills */
|
||||
export const POST = withRouteHandler(async (req: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const authResult = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized skills update attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const userId = authResult.userId
|
||||
|
||||
const parsed = await parseRequest(
|
||||
upsertSkillsContract,
|
||||
req,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid skills data`, { errors: error.issues })
|
||||
return validationErrorResponse(error, 'Invalid request data')
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { skills, workspaceId, source } = parsed.data.body
|
||||
|
||||
const userPermission = await getUserEntityPermissions(userId, 'workspace', workspaceId)
|
||||
if (!userPermission || (userPermission !== 'admin' && userPermission !== 'write')) {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} does not have write permission for workspace ${workspaceId}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Write permission required' }, { status: 403 })
|
||||
}
|
||||
|
||||
try {
|
||||
const { skills: resultSkills, touched } = await upsertSkills({
|
||||
skills,
|
||||
workspaceId,
|
||||
userId,
|
||||
requestId,
|
||||
})
|
||||
|
||||
for (const { id, name, operation } of touched) {
|
||||
const isUpdate = operation === 'updated'
|
||||
recordAudit({
|
||||
workspaceId,
|
||||
actorId: userId,
|
||||
actorName: authResult.userName ?? undefined,
|
||||
actorEmail: authResult.userEmail ?? undefined,
|
||||
action: isUpdate ? AuditAction.SKILL_UPDATED : AuditAction.SKILL_CREATED,
|
||||
resourceType: AuditResourceType.SKILL,
|
||||
resourceId: id,
|
||||
resourceName: name,
|
||||
description: `${isUpdate ? 'Updated' : 'Created'} skill "${name}"`,
|
||||
metadata: { source },
|
||||
})
|
||||
captureServerEvent(
|
||||
userId,
|
||||
isUpdate ? 'skill_updated' : 'skill_created',
|
||||
{ skill_id: id, skill_name: name, workspace_id: workspaceId, source },
|
||||
{ groups: { workspace: workspaceId } }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, data: resultSkills })
|
||||
} catch (upsertError) {
|
||||
if (upsertError instanceof Error && upsertError.message.includes('already exists')) {
|
||||
return NextResponse.json({ error: upsertError.message }, { status: 409 })
|
||||
}
|
||||
throw upsertError
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error updating skills`, error)
|
||||
return NextResponse.json({ error: 'Failed to update skills' }, { status: 500 })
|
||||
}
|
||||
})
|
||||
|
||||
/** DELETE - Delete a skill by ID */
|
||||
export const DELETE = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized skill deletion attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const userId = authResult.userId
|
||||
const query = deleteSkillQuerySchema.safeParse(
|
||||
Object.fromEntries(request.nextUrl.searchParams.entries())
|
||||
)
|
||||
if (!query.success) {
|
||||
logger.warn(`[${requestId}] Invalid skill deletion query`, { errors: query.error.issues })
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid request data', details: query.error.issues },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
const { id: skillId, workspaceId, source } = query.data
|
||||
|
||||
const userPermission = await getUserEntityPermissions(userId, 'workspace', workspaceId)
|
||||
if (!userPermission || (userPermission !== 'admin' && userPermission !== 'write')) {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} does not have write permission for workspace ${workspaceId}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Write permission required' }, { status: 403 })
|
||||
}
|
||||
|
||||
const deleted = await deleteSkill({ skillId, workspaceId })
|
||||
if (!deleted) {
|
||||
logger.warn(`[${requestId}] Skill not found: ${skillId}`)
|
||||
return NextResponse.json({ error: 'Skill not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
recordAudit({
|
||||
workspaceId,
|
||||
actorId: authResult.userId,
|
||||
actorName: authResult.userName ?? undefined,
|
||||
actorEmail: authResult.userEmail ?? undefined,
|
||||
action: AuditAction.SKILL_DELETED,
|
||||
resourceType: AuditResourceType.SKILL,
|
||||
resourceId: skillId,
|
||||
description: `Deleted skill`,
|
||||
metadata: { source },
|
||||
})
|
||||
|
||||
captureServerEvent(
|
||||
userId,
|
||||
'skill_deleted',
|
||||
{ skill_id: skillId, workspace_id: workspaceId, source },
|
||||
{ groups: { workspace: workspaceId } }
|
||||
)
|
||||
|
||||
logger.info(`[${requestId}] Deleted skill: ${skillId}`)
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error deleting skill:`, error)
|
||||
return NextResponse.json({ error: 'Failed to delete skill' }, { status: 500 })
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user