Unrestricted Open-source alternative to AI video platforms — Free AI image & video generation studio with 600+ models (Flux, Midjourney, Kling, Sora, Veo). No content filters. Self-hosted, MIT licensed.
JavaScript ai-art-generatorai-image-generationai-video-generationfal-ai-alternativegenerative-aiimage-to-videoinvideo-alternativekling-ailipsynclitellm-alternativemidjourney-alternativemuapiopen-sourceopenrouter-alternativeseedance2sora-alternativetext-to-imagetext-to-videouncensoredwan-video
Fix unauthenticated S3 upload proxy and presigned credential leakage (Fixes #310)
jaiprasad04f013270957f7
diff --git a/app/api/app/[[...path]]/route.js b/app/api/app/[[...path]]/route.jsindex 59b398d8..098b4d15 100644--- a/app/api/app/[[...path]]/route.js+++ b/app/api/app/[[...path]]/route.js@@ -3,10 +3,13 @@ import { NextResponse } from 'next/server';const MUAPI_BASE = 'https://api.muapi.ai';function getApiKey(request) {- // Only accept x-api-key header. Cookie-based auth is removed for security:- // cookies without HttpOnly flag can be stolen by XSS (CWE-522).+ const authHeader = request.headers.get('Authorization');+ if (authHeader && authHeader.startsWith('Bearer ')) {+ const token = authHeader.substring(7).trim();+ if (token) return token;+ }const headerKey = request.headers.get('x-api-key');- return headerKey || null;+ return (headerKey && headerKey.trim()) || null;}function cleanHeaders(request) {@@ -14,6 +17,7 @@ function cleanHeaders(request) {headers.delete('host');headers.delete('connection');headers.delete('cookie'); // CRITICAL: Stop forwarding browser cookies to MuAPI to avoid auth conflicts+ headers.delete('authorization');return headers;}@@ -25,12 +29,16 @@ export async function GET(request, { params }) {// Handle alias: get_upload_file -> get_file_upload_urlconst effectivePath = path === 'get_upload_file' ? 'get_file_upload_url' : path;+ const apiKey = getApiKey(request);+ if (effectivePath === 'get_file_upload_url' && !apiKey) {+ return NextResponse.json({ error: 'Unauthorized: Missing API key' }, { status: 401 });+ }+const { search } = new URL(request.url);const targetUrl = `${MUAPI_BASE}/app/${effectivePath}${search}`;const headers = cleanHeaders(request);- const apiKey = getApiKey(request);if (apiKey) headers.set('x-api-key', apiKey);try {diff --git a/app/api/upload-binary/route.js b/app/api/upload-binary/route.jsindex eaa5dba8..4ef61dbb 100644--- a/app/api/upload-binary/route.js+++ b/app/api/upload-binary/route.js@@ -1,8 +1,13 @@import { NextResponse } from 'next/server';-import { validateUploadProxyTarget } from '../../../src/lib/uploadProxyTarget';+import { validateUploadProxyTarget, getApiKeyFromRequest, isBlockedFileType } from '../../../src/lib/uploadProxyTarget';export async function POST(request) {try {+ const apiKey = getApiKeyFromRequest(request);+ if (!apiKey) {+ return NextResponse.json({ error: 'Unauthorized: Missing API key' }, { status: 401 });+ }+const formData = await request.formData();// Extract the original S3 target URL we injected earlier@@ -20,12 +25,33 @@ export async function POST(request) {);}+ // Validate file content type and extension to prevent dangerous uploads (e.g. HTML, SVG, executables)+ const fileContentType = formData.get('Content-Type') || formData.get('content-type') || '';+ const keyName = formData.get('key') || '';++ for (const [key, value] of formData.entries()) {+ if (value && typeof value === 'object' && typeof value.name === 'string') {+ if (isBlockedFileType(value.name, value.type || fileContentType)) {+ return NextResponse.json(+ { error: 'Invalid file type', reason: 'blocked_file_type' },+ { status: 400 }+ );+ }+ }+ }++ if (isBlockedFileType(keyName, fileContentType)) {+ return NextResponse.json(+ { error: 'Invalid file type', reason: 'blocked_file_type' },+ { status: 400 }+ );+ }+// Reconstruct the FormData for S3 (excluding our internal proxy marker)const s3FormData = new FormData();// S3 is very sensitive to field ordering. We must ensure 'file' is likely last// or at least that all signature fields come before what S3 expects.- // The original library code appends 'file' last, so iterating should preserve that.for (const [key, value] of formData.entries()) {if (key !== 'x-proxy-target-url') {s3FormData.append(key, value);@@ -33,7 +59,6 @@ export async function POST(request) {}// Perform the server-to-server POST to S3- // This bypasses browser CORS/Preflight security entirelyconst s3Response = await fetch(validatedTarget.url, {method: 'POST',body: s3FormData,@@ -51,3 +76,4 @@ export async function POST(request) {return NextResponse.json({ error: error.message }, { status: 500 });}}+diff --git a/app/api/v1/get_upload_url/route.js b/app/api/v1/get_upload_url/route.jsindex 21e60c27..07e2084e 100644--- a/app/api/v1/get_upload_url/route.js+++ b/app/api/v1/get_upload_url/route.js@@ -3,9 +3,13 @@ import { NextResponse } from 'next/server';const MUAPI_BASE = 'https://api.muapi.ai';function getApiKey(request) {+ const authHeader = request.headers.get('Authorization');+ if (authHeader && authHeader.startsWith('Bearer ')) {+ const token = authHeader.substring(7).trim();+ if (token) return token;+ }const headerKey = request.headers.get('x-api-key');- if (headerKey) return headerKey;- // Cookie-based auth removed for security (CWE-522)+ if (headerKey && headerKey.trim()) return headerKey.trim();return null;}@@ -14,16 +18,21 @@ function cleanHeaders(request) {headers.delete('host');headers.delete('connection');headers.delete('cookie');+ headers.delete('authorization');return headers;}export async function GET(request) {+ const apiKey = getApiKey(request);+ if (!apiKey) {+ return NextResponse.json({ error: 'Unauthorized: Missing API key' }, { status: 401 });+ }+const { search } = new URL(request.url);const targetUrl = `${MUAPI_BASE}/app/get_file_upload_url${search}`;const headers = cleanHeaders(request);- const apiKey = getApiKey(request);- if (apiKey) headers.set('x-api-key', apiKey);+ headers.set('x-api-key', apiKey);try {const response = await fetch(targetUrl, {@@ -38,3 +47,4 @@ export async function GET(request) {return NextResponse.json({ error: error.message }, { status: 500 });}}+diff --git a/app/api/v1/upload-binary/route.js b/app/api/v1/upload-binary/route.jsindex c01d5f11..694d258c 100644--- a/app/api/v1/upload-binary/route.js+++ b/app/api/v1/upload-binary/route.js@@ -1,8 +1,13 @@import { NextResponse } from 'next/server';-import { validateUploadProxyTarget } from '../../../../src/lib/uploadProxyTarget';+import { validateUploadProxyTarget, getApiKeyFromRequest, isBlockedFileType } from '../../../../src/lib/uploadProxyTarget';export async function POST(request) {try {+ const apiKey = getApiKeyFromRequest(request);+ if (!apiKey) {+ return NextResponse.json({ error: 'Unauthorized: Missing API key' }, { status: 401 });+ }+const formData = await request.formData();// Extract the original S3 target URL@@ -20,6 +25,28 @@ export async function POST(request) {);}+ // Validate file content type and extension to prevent dangerous uploads (e.g. HTML, SVG, executables)+ const fileContentType = formData.get('Content-Type') || formData.get('content-type') || '';+ const keyName = formData.get('key') || '';++ for (const [key, value] of formData.entries()) {+ if (value && typeof value === 'object' && typeof value.name === 'string') {+ if (isBlockedFileType(value.name, value.type || fileContentType)) {+ return NextResponse.json(+ { error: 'Invalid file type', reason: 'blocked_file_type' },+ { status: 400 }+ );+ }+ }+ }++ if (isBlockedFileType(keyName, fileContentType)) {+ return NextResponse.json(+ { error: 'Invalid file type', reason: 'blocked_file_type' },+ { status: 400 }+ );+ }+const s3FormData = new FormData();for (const [key, value] of formData.entries()) {if (key !== 'x-proxy-target-url') {@@ -44,3 +71,4 @@ export async function POST(request) {return NextResponse.json({ error: error.message }, { status: 500 });}}+diff --git a/src/lib/uploadProxyTarget.js b/src/lib/uploadProxyTarget.jsindex b7b38331..4c0c950a 100644--- a/src/lib/uploadProxyTarget.js+++ b/src/lib/uploadProxyTarget.js@@ -88,6 +88,57 @@ function isAllowedS3Host(hostname) {return false;}+export function getApiKeyFromRequest(request) {+ if (!request || !request.headers) return null;+ const authHeader = request.headers.get('Authorization');+ if (authHeader && authHeader.startsWith('Bearer ')) {+ const token = authHeader.substring(7).trim();+ if (token) return token;+ }+ const headerKey = request.headers.get('x-api-key');+ if (headerKey && headerKey.trim()) {+ return headerKey.trim();+ }+ return null;+}++const BLOCKED_EXTENSIONS = new Set([+ 'html', 'htm', 'xhtml', 'svg', 'php', 'phtml', 'php3', 'php4', 'php5', 'phps',+ 'exe', 'bat', 'cmd', 'sh', 'bash', 'js', 'cgi', 'pl', 'py', 'jar', 'vbs', 'scr', 'msi'+]);++const BLOCKED_MIME_TYPES = new Set([+ 'text/html',+ 'image/svg+xml',+ 'application/xhtml+xml',+ 'application/x-httpd-php',+ 'application/x-msdownload',+ 'application/x-executable',+ 'application/x-sh',+ 'application/x-shellscript',+ 'application/javascript',+ 'text/javascript'+]);++export function isBlockedFileType(filename = '', contentType = '') {+ if (contentType) {+ const normalizedMime = contentType.toLowerCase().split(';')[0].trim();+ if (BLOCKED_MIME_TYPES.has(normalizedMime)) {+ return true;+ }+ }+ if (filename) {+ const parts = filename.toLowerCase().split('.');+ if (parts.length > 1) {+ const ext = parts[parts.length - 1].trim();+ if (BLOCKED_EXTENSIONS.has(ext)) {+ return true;+ }+ }+ }+ return false;+}+export function validateUploadProxyTarget(rawTarget, { env = process.env } = {}) {if (typeof rawTarget !== 'string' || rawTarget.trim() === '') {return { ok: false, reason: 'missing_target' };@@ -116,3 +167,4 @@ export function validateUploadProxyTarget(rawTarget, { env = process.env } = {})return { ok: true, url: url.toString() };}+