Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
4f29765
feat(tiktok): add TikTok integration
Jul 8, 2026
909144b
fix(tiktok): add avatarFile output to Get User Info
Jul 8, 2026
f3f8215
fix(tiktok): lower upload memory cap, drop redundant avatar string ou…
Jul 8, 2026
71f3fac
chore(ci): bump API validation route-count baseline for TikTok publis…
Jul 8, 2026
d8608aa
chore(tiktok): drop unused avatar_url_100 from default user fields
Jul 8, 2026
b177848
fix(tiktok): stop returning raw 'credential' subBlock id from tools.c…
Jul 8, 2026
c856f33
fix(tiktok): send empty JSON body on Query Creator Info POST
Jul 8, 2026
e52669a
fix(tiktok): stop dropping valid zero values in optional numeric fields
Jul 8, 2026
68bb622
fix(tiktok): accept newline-separated video IDs in Query Videos
Jul 8, 2026
83841a3
feat(tiktok): add app-level webhook ingress and triggers
Jul 9, 2026
1e2e927
fix(tiktok): only count actually queued webhook executions
Jul 9, 2026
84bd3f6
chore(tiktok): bump API validation baseline for staging merge
Jul 9, 2026
cb1a766
Merge branch 'staging' into feature/tiktok-integration
BillLeoutsakosvl346 Jul 9, 2026
d3b624a
Merge branch 'staging' into feature/tiktok-integration
icecrasher321 Jul 9, 2026
165fc4b
cleanup code
icecrasher321 Jul 9, 2026
a8b6081
fix type issues
icecrasher321 Jul 9, 2026
1416219
misc code cleanup
icecrasher321 Jul 9, 2026
694a33f
remove photos and add upload for videos
Jul 10, 2026
562ba12
move shared video output properties to types.ts so docs generation re…
Jul 10, 2026
e857ece
hide TikTok from toolbar and docs until the integration is ready to ship
Jul 10, 2026
d491684
Merge branch 'staging' into feature/tiktok-integration
BillLeoutsakosvl346 Jul 10, 2026
2521ba8
fix(ci): ratchet API validation baseline to 924 after staging merge
Jul 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions apps/docs/components/icons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1274,6 +1274,31 @@ export function xAIIcon(props: SVGProps<SVGSVGElement>) {
)
}

export function TikTokIcon(props: SVGProps<SVGSVGElement>) {
return (
<svg
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 520.48 520.48'
width='1em'
height='1em'
{...props}
>
<path
fill='#ff004f'
d='m392.19,206.7v49.13c-8.6-.84-19.74-2.78-32.09-7.31-16.13-5.91-28.13-13.99-35.98-20.25v99.32l-.19-.31c.14,1.96.19,3.97.19,5.99,0,49.33-40.13,89.48-89.48,89.48s-89.48-40.15-89.48-89.48,40.13-89.5,89.48-89.5c4.82,0,9.57.39,14.2,1.13v48.43c-4.45-1.6-9.22-2.45-14.2-2.45-23.36,0-42.38,19-42.38,42.38s19.02,42.38,42.38,42.38,42.38-19.02,42.38-42.38c0-.88-.02-1.75-.08-2.63v-193.01h49.11c.18,4.16.35,8.34.53,12.51.33,8.19,3.25,16.05,8.32,22.49,5.97,7.57,14.76,16.36,27.13,23.38,11.57,6.56,22.45,9.38,30.15,10.7Z'
/>
<path
fill='#00f7ef'
d='m375.32,166.81v49.13c-8.6-.84-19.74-2.78-32.09-7.31-16.13-5.91-28.13-13.99-35.98-20.25v99.32l-.19-.31c.14,1.96.19,3.97.19,5.99,0,49.33-40.13,89.48-89.48,89.48s-89.48-40.15-89.48-89.48,40.13-89.5,89.48-89.5c4.82,0,9.57.39,14.2,1.13v48.43c-4.45-1.6-9.22-2.45-14.2-2.45-23.36,0-42.38,19-42.38,42.38s19.02,42.38,42.38,42.38,42.38-19.02,42.38-42.38c0-.88-.02-1.75-.08-2.63V97.74h49.11c.18,4.16.35,8.34.53,12.51.33,8.19,3.25,16.05,8.33,22.49,5.97,7.57,14.76,16.36,27.13,23.38,11.57,6.56,22.45,9.38,30.15,10.7Z'
/>
<path
fill='#fff'
d='m386.06,188.29v49.13c-8.6-.84-19.74-2.78-32.09-7.31-16.13-5.91-28.13-13.99-35.98-20.25v99.32l-.19-.31c.14,1.96.19,3.97.19,5.99,0,49.33-40.13,89.48-89.48,89.48s-89.48-40.15-89.48-89.48,40.13-89.5,89.48-89.5c4.82,0,9.57.39,14.2,1.13v48.43c-4.45-1.6-9.22-2.45-14.2-2.45-23.36,0-42.38,19-42.38,42.38s19.02,42.38,42.38,42.38,42.38-19.02,42.38-42.38c0-.88-.02-1.75-.08-2.63V119.22h49.11c.18,4.16.35,8.34.53,12.51.33,8.19,3.25,16.05,8.32,22.49,5.97,7.57,14.76,16.36,27.13,23.38,11.57,6.56,22.45,9.38,30.15,10.7Z'
/>
</svg>
)
}

export function xIcon(props: SVGProps<SVGSVGElement>) {
return (
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 50 50' width='1em' height='1em' {...props}>
Expand Down
25 changes: 19 additions & 6 deletions apps/sim/app/api/tools/jupyter/upload/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
buildJupyterAuthHeaders,
encodeJupyterPath,
normalizeJupyterServerUrl,
parseJupyterContentModel,
UnsafeJupyterPathError,
} from '@/tools/jupyter/utils'

Expand Down Expand Up @@ -128,17 +129,29 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
)
}

const uploaded = await response.json()
const uploaded = parseJupyterContentModel(await response.json())
if (!uploaded) {
logger.error(`[${requestId}] Jupyter returned an invalid upload response`)
return NextResponse.json(
{ success: false, error: 'Jupyter returned an invalid upload response' },
{ status: 502 }
)
}

const uploadedName = uploaded.name ?? fileName
const uploadedPath = uploaded.path ?? destinationPath
const uploadedSize = uploaded.size ?? fileBuffer.length
const lastModified = uploaded.lastModified ?? null

logger.info(`[${requestId}] File uploaded to Jupyter: ${uploaded.path}`)
logger.info(`[${requestId}] File uploaded to Jupyter: ${uploadedPath}`)

return NextResponse.json({
success: true,
output: {
name: uploaded.name ?? fileName,
path: uploaded.path ?? destinationPath,
size: uploaded.size ?? fileBuffer.length,
lastModified: uploaded.last_modified ?? null,
name: uploadedName,
path: uploadedPath,
size: uploadedSize,
lastModified,
},
})
} catch (error) {
Expand Down
287 changes: 287 additions & 0 deletions apps/sim/app/api/tools/tiktok/publish-video/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,287 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { tiktokPublishVideoContract } from '@/lib/api/contracts/tiktok-tools'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { generateRequestId } from '@/lib/core/utils/request'
import { isPayloadSizeLimitError, readResponseTextWithLimit } from '@/lib/core/utils/stream-limits'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import {
getFileExtension,
getMimeTypeFromExtension,
processSingleFileToUserFile,
} from '@/lib/uploads/utils/file-utils'
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
import { assertToolFileAccess } from '@/app/api/files/authorization'
import type { UserFile } from '@/executor/types'
import { tiktokPublishInitApiDataSchema } from '@/tools/tiktok/api-schemas'
import { readTikTokApiResponse } from '@/tools/tiktok/utils'

export const dynamic = 'force-dynamic'

const logger = createLogger('TikTokPublishVideoAPI')

const TIKTOK_VIDEO_MIME_TYPES = new Set(['video/mp4', 'video/quicktime', 'video/webm'])

/** TikTok requires each chunk between 5MB and 64MB; the final chunk absorbs the remainder (up to ~2x this size, well under the 128MB cap). Capped at 1000 chunks total, which this default comfortably satisfies up to TikTok's 4GB video size limit. */
const DEFAULT_CHUNK_SIZE = 10_000_000
const TIKTOK_ERROR_RESPONSE_MAX_BYTES = 64 * 1024

/** Maximum size this route will buffer in memory for a single file-upload request. TikTok's
* own limit is 4GB, but relaying that much through this server's memory per request isn't
* safe under concurrent load. Enforced before downloading the file so an oversized upload
* fails fast with a clean 413 instead of materializing hundreds of MB to multiple GB
* in-process. */
const TIKTOK_MAX_VIDEO_BYTES = 250 * 1024 * 1024

function computeChunkPlan(totalBytes: number): { chunkSize: number; totalChunkCount: number } {
if (totalBytes <= DEFAULT_CHUNK_SIZE) {
return { chunkSize: totalBytes, totalChunkCount: 1 }
}
const totalChunkCount = Math.floor(totalBytes / DEFAULT_CHUNK_SIZE)
return { chunkSize: DEFAULT_CHUNK_SIZE, totalChunkCount }
Comment thread
cursor[bot] marked this conversation as resolved.
}

function resolveVideoMimeType(fileName: string, fileType: string | undefined): string | null {
if (fileType && TIKTOK_VIDEO_MIME_TYPES.has(fileType)) return fileType
const fromExtension = getMimeTypeFromExtension(getFileExtension(fileName))
return TIKTOK_VIDEO_MIME_TYPES.has(fromExtension) ? fromExtension : null
}

async function validateDirectPostSettings(
accessToken: string,
postInfo: { privacy_level: string; brand_content_toggle: boolean },
requestId: string
): Promise<string | null> {
if (postInfo.brand_content_toggle && postInfo.privacy_level === 'SELF_ONLY') {
return 'Branded content cannot use Only Me privacy.'
}

const response = await fetch('https://open.tiktokapis.com/v2/post/publish/creator_info/query/', {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json; charset=UTF-8',
},
body: '{}',
})
const data = await response.json()
if (!response.ok || (data.error?.code && data.error.code !== 'ok')) {
logger.warn(`[${requestId}] TikTok creator-info preflight failed`, {
status: response.status,
code: data.error?.code,
})
return data.error?.message || 'TikTok creator information could not be verified.'
}

const privacyOptions: unknown = data.data?.privacy_level_options
if (
!Array.isArray(privacyOptions) ||
!privacyOptions.some((option) => option === postInfo.privacy_level)
) {
return `The selected privacy level (${postInfo.privacy_level}) is not currently available for this TikTok account. Run Query Creator Info and choose one of the returned options.`
}

return null
}

async function uploadChunks(
uploadUrl: string,
buffer: Buffer,
mimeType: string,
requestId: string
): Promise<void> {
const totalBytes = buffer.length
const { chunkSize, totalChunkCount } = computeChunkPlan(totalBytes)

for (let i = 0; i < totalChunkCount; i++) {
const start = i * chunkSize
const isLastChunk = i === totalChunkCount - 1
const end = isLastChunk ? totalBytes - 1 : start + chunkSize - 1
const chunk = buffer.subarray(start, end + 1)

const response = await fetch(uploadUrl, {
method: 'PUT',
headers: {
'Content-Type': mimeType,
'Content-Length': String(chunk.length),
'Content-Range': `bytes ${start}-${end}/${totalBytes}`,
},
body: new Uint8Array(chunk),
})

if (!response.ok) {
const errorText = await readResponseTextWithLimit(response, {
maxBytes: TIKTOK_ERROR_RESPONSE_MAX_BYTES,
label: 'TikTok upload error response',
}).catch(() => 'Error response exceeded the allowed size')
logger.error(`[${requestId}] TikTok chunk upload failed`, {
chunkIndex: i,
status: response.status,
errorText,
})
throw new Error(
`TikTok rejected video chunk ${i + 1}/${totalChunkCount}: ${response.status} ${errorText || response.statusText}`
)
}
}
}

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 TikTok publish-video attempt: ${authResult.error}`)
return NextResponse.json(
{ success: false, error: authResult.error || 'Authentication required' },
{ status: 401 }
)
}

const parsed = await parseRequest(tiktokPublishVideoContract, request, {})
if (!parsed.success) return parsed.response
const data = parsed.data.body

let userFile: UserFile
try {
userFile = processSingleFileToUserFile(data.file, requestId, logger)
} catch (error) {
return NextResponse.json(
{ success: false, error: getErrorMessage(error, 'Failed to process file') },
{ status: 400 }
)
}

const denied = await assertToolFileAccess(userFile.key, authResult.userId, requestId, logger)
if (denied) return denied

if (data.mode === 'direct') {
const settingsError = await validateDirectPostSettings(
data.accessToken,
data.postInfo,
requestId
)
if (settingsError) {
return NextResponse.json({ success: false, error: settingsError }, { status: 400 })
}
}

const mimeType = resolveVideoMimeType(userFile.name, userFile.type)
if (!mimeType) {
return NextResponse.json(
{
success: false,
error: 'Unsupported video type. TikTok accepts MP4, MOV/QuickTime, or WebM files.',
},
{ status: 400 }
)
}

logger.info(`[${requestId}] Downloading video from storage`, {
fileName: userFile.name,
size: userFile.size,
})

const fileBuffer = await downloadFileFromStorage(userFile, requestId, logger, {
maxBytes: TIKTOK_MAX_VIDEO_BYTES,
})
if (fileBuffer.length === 0) {
return NextResponse.json(
{ success: false, error: 'The video file is empty.' },
{ status: 400 }
)
}
const { chunkSize, totalChunkCount } = computeChunkPlan(fileBuffer.length)

const initUrl =
data.mode === 'draft'
? 'https://open.tiktokapis.com/v2/post/publish/inbox/video/init/'
: 'https://open.tiktokapis.com/v2/post/publish/video/init/'

const initBody: Record<string, unknown> = {
source_info: {
source: 'FILE_UPLOAD',
video_size: fileBuffer.length,
chunk_size: chunkSize,
total_chunk_count: totalChunkCount,
},
}
if (data.mode === 'direct') {
initBody.post_info = data.postInfo
}

logger.info(`[${requestId}] Initializing TikTok video ${data.mode}`, {
videoSize: fileBuffer.length,
chunkSize,
totalChunkCount,
})

const initResponse = await fetch(initUrl, {
method: 'POST',
headers: {
Authorization: `Bearer ${data.accessToken}`,
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(initBody),
})

const { data: initData, error: initError } = await readTikTokApiResponse(
initResponse,
tiktokPublishInitApiDataSchema
)

if (initError) {
logger.error(`[${requestId}] TikTok init failed`, { error: initError })
return NextResponse.json(
{ success: false, error: initError.message || 'Failed to initialize TikTok upload' },
{ status: initResponse.status >= 400 ? initResponse.status : 502 }
)
}

const publishId = initData?.publish_id
const uploadUrl = initData?.upload_url

if (!publishId || !uploadUrl) {
return NextResponse.json(
{ success: false, error: 'TikTok did not return a publish ID and upload URL' },
{ status: 502 }
)
}

try {
await uploadChunks(uploadUrl, fileBuffer, mimeType, requestId)
} catch (error) {
return NextResponse.json(
{ success: false, error: getErrorMessage(error, 'Failed to upload video to TikTok') },
{ status: 502 }
)
}

logger.info(`[${requestId}] TikTok video upload complete`, { publishId })

return NextResponse.json({ success: true, output: { publishId } })
} catch (error) {
if (isPayloadSizeLimitError(error)) {
logger.warn(`[${requestId}] Rejected oversized TikTok video upload`, {
maxBytes: error.maxBytes,
observedBytes: error.observedBytes,
})
const maxMb = Math.floor(TIKTOK_MAX_VIDEO_BYTES / (1024 * 1024))
return NextResponse.json(
{
success: false,
error: `Video exceeds the ${maxMb}MB limit for file uploads.`,
},
{ status: 413 }
)
}
logger.error(`[${requestId}] Error publishing video to TikTok:`, error)
return NextResponse.json(
{ success: false, error: getErrorMessage(error, 'Internal server error') },
{ status: 500 }
)
}
})
Loading
Loading