@@ -2,6 +2,7 @@ import { db } from '@sim/db'
22import { document , knowledgeBase , workspaceFile } from '@sim/db/schema'
33import { createLogger } from '@sim/logger'
44import { and , eq , isNull , like , or } from 'drizzle-orm'
5+ import { NextResponse } from 'next/server'
56import { getFileMetadata } from '@/lib/uploads'
67import type { StorageContext } from '@/lib/uploads/config'
78import { BLOB_CHAT_CONFIG , S3_CHAT_CONFIG } from '@/lib/uploads/config'
@@ -587,6 +588,36 @@ async function authorizeFileAccess(
587588 }
588589}
589590
591+ /**
592+ * Guard helper for tool routes that download user files from storage.
593+ *
594+ * Validates that `key` is a non-empty string, that `userId` is present, and
595+ * that the authenticated user owns the file. Returns a 404 `NextResponse` on
596+ * any failure so callers can `return` it immediately; returns `null` when
597+ * access is granted.
598+ */
599+ export async function assertToolFileAccess (
600+ key : unknown ,
601+ userId : string | undefined ,
602+ requestId : string ,
603+ routeLogger : ReturnType < typeof createLogger >
604+ ) : Promise < NextResponse | null > {
605+ if ( typeof key !== 'string' || key . length === 0 ) {
606+ routeLogger . warn ( `[${ requestId } ] File access check rejected: missing key` )
607+ return NextResponse . json ( { success : false , error : 'File not found' } , { status : 404 } )
608+ }
609+ if ( ! userId ) {
610+ routeLogger . warn ( `[${ requestId } ] File access check requires userId but none available` )
611+ return NextResponse . json ( { success : false , error : 'File not found' } , { status : 404 } )
612+ }
613+ const hasAccess = await verifyFileAccess ( key , userId )
614+ if ( ! hasAccess ) {
615+ routeLogger . warn ( `[${ requestId } ] File access denied for user` , { userId, key } )
616+ return NextResponse . json ( { success : false , error : 'File not found' } , { status : 404 } )
617+ }
618+ return null
619+ }
620+
590621/**
591622 * Get chat storage configuration based on current storage provider
592623 */
0 commit comments