This commit is contained in:
Your Name
2026-10-23 11:17:58 +08:00
parent f78f46b28a
commit 86476920cf
10 changed files with 709 additions and 94 deletions
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace app\common\service;
/**
* Turn an already-authorized mandatory attachment list into Dify local_file references.
* Turn an already-authorized attachment list into Dify local_file references.
*
* Trust options are SERVER configuration, never request parameters. Local origins are
* exact scheme/host/port aliases of this application's public/uploads directory;
@@ -20,12 +20,17 @@ final class DifyRequiredAttachmentUpload
/**
* Options: local_origin/local_origins, storage_origins, public_root, temp_root,
* max_file_bytes, on_upload(array{index:int,total:int,status:string}), resolved_hosts
* max_file_bytes, ca_file (optional trusted CA bundle),
* on_upload(array{index:int,total:int,status:string,reason?:string}), resolved_hosts
* (exact hostname => nonempty public IP list). Pins take precedence over the optional
* server-owned resolve_host callable, then native DNS for unpinned hosts only.
* No file ID cache survives this call, including between different Dify users.
* skip_missing defaults to true: only confirmed absent local files or completed
* HTTP 404/410 downloads are skipped. Other source/transport errors still fail.
* Successful files and uploaded_indices have matching order; skipped metadata
* contains only the original one-based input index, attachment kind and reason.
*
* @return array{ok:bool,files?:array,error_code?:string,error?:string}
* @return array{ok:bool,files?:array,uploaded_indices?:array,skipped?:array,error_code?:string,error?:string}
*/
public static function prepare(
string $chatEndpoint,
@@ -37,6 +42,7 @@ final class DifyRequiredAttachmentUpload
array $options = []
): array {
$temporary = [];
$skipped = [];
$index = 0;
$total = 0;
$deadline = microtime(true) + max(0, $timeout);
@@ -44,8 +50,8 @@ final class DifyRequiredAttachmentUpload
self::check($deadline, $shouldAbort);
$options = self::options($options);
$plan = self::plan($files);
$total = count($plan);
if ($plan === []) return ['ok' => true, 'files' => [], 'attachment_transport' => 'uploaded_files'];
$total = count($files);
if ($plan === []) return ['ok' => true, 'files' => [], 'uploaded_indices' => [], 'skipped' => [], 'attachment_transport' => 'uploaded_files'];
if ($timeout < 1 || $timeout > 300 || $user === '' || strlen($user) > 1024
|| trim($apiKey) === '' || strpbrk($apiKey . $user, "\r\n\0") !== false) {
self::fail('CONFIG_INVALID');
@@ -63,6 +69,7 @@ final class DifyRequiredAttachmentUpload
// Validate the whole manifest before the first upload. Never truncate it.
foreach ($plan as &$item) {
self::check($deadline, $shouldAbort);
$origin = self::origin($item['parts']);
if (isset($localOrigins[$origin])) {
$item['path'] = self::localPath($publicRoot, $item['parts']['path'] ?? '/');
@@ -72,39 +79,58 @@ final class DifyRequiredAttachmentUpload
}
unset($item);
$prepared = [];
$uploadedIndices = [];
$cache = [];
foreach ($plan as $position => $item) {
$index = $position + 1;
foreach ($plan as $item) {
$index = $item['index'];
self::check($deadline, $shouldAbort);
self::notify($options, $index, $total, 'uploading');
$cacheKey = hash('sha256', $item['type'] . "\0" . $item['url']);
if (!isset($cache[$cacheKey])) {
if (array_key_exists('path', $item) && $item['path'] === null) $cache[$cacheKey] = null;
if (!array_key_exists($cacheKey, $cache) || $cache[$cacheKey] !== null) {
self::notify($options, $index, $total, 'uploading');
}
if (!array_key_exists($cacheKey, $cache)) {
$path = @tempnam($tempRoot, 'required-');
if ($path === false) self::fail('REQUIRED_FILES_PREPARE_FAILED');
$temporary[] = $path;
if (!self::inside($tempRoot, (string) realpath($path))) self::fail('REQUIRED_FILES_PREPARE_FAILED');
@chmod($path, 0600);
$exists = true;
if (isset($item['path'])) {
self::copyLocal($item['path'], $path, $maxBytes, $deadline, $shouldAbort);
} else {
self::download($item['url'], $item['parts'], $path, $maxBytes, $deadline, $shouldAbort, $options);
$exists = self::download($item['url'], $item['parts'], $path, $maxBytes, $deadline, $shouldAbort, $options);
}
self::check($deadline, $shouldAbort);
$mime = @(new \finfo(FILEINFO_MIME_TYPE))->file($path) ?: 'application/octet-stream';
if (str_starts_with(strtolower($mime), 'video/')) self::fail('REQUIRED_FILES_INVALID');
$extension = strtolower(pathinfo(rawurldecode($item['parts']['path'] ?? ''), PATHINFO_EXTENSION));
if (!preg_match('/^[a-z0-9]{1,10}$/D', $extension)) {
$extension = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'application/pdf' => 'pdf',
'audio/wav' => 'wav', 'audio/mpeg' => 'mp3', 'text/plain' => 'txt'][$mime] ?? 'bin';
if (!$exists) {
$cache[$cacheKey] = null;
} else {
$mime = @(new \finfo(FILEINFO_MIME_TYPE))->file($path) ?: 'application/octet-stream';
if (str_starts_with(strtolower($mime), 'video/')) self::fail('REQUIRED_FILES_INVALID');
$extension = strtolower(pathinfo(rawurldecode($item['parts']['path'] ?? ''), PATHINFO_EXTENSION));
if (!preg_match('/^[a-z0-9]{1,10}$/D', $extension)) {
$extension = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'application/pdf' => 'pdf',
'audio/wav' => 'wav', 'audio/mpeg' => 'mp3', 'text/plain' => 'txt'][$mime] ?? 'bin';
}
$cache[$cacheKey] = self::upload($endpoint, $apiKey, $user, $path, $mime,
'attachment-' . $index . '.' . $extension, $deadline, $shouldAbort, $options['ca_file']);
}
$cache[$cacheKey] = self::upload($endpoint, $apiKey, $user, $path, $mime,
'attachment-' . $index . '.' . $extension, $deadline, $shouldAbort);
}
if ($cache[$cacheKey] === null) {
if (!$options['skip_missing']) self::fail(array_key_exists('path', $item)
? 'REQUIRED_FILES_SOURCE_UNAVAILABLE' : 'REQUIRED_FILES_DOWNLOAD_FAILED');
$skipped[] = ['index' => $index, 'kind' => $item['type'], 'reason' => 'not_found'];
self::notify($options, $index, $total, 'skipped', 'not_found');
self::check($deadline, $shouldAbort);
continue;
}
$prepared[] = ['type' => $item['type'], 'transfer_method' => 'local_file', 'upload_file_id' => $cache[$cacheKey]];
$uploadedIndices[] = $index;
self::notify($options, $index, $total, 'uploaded');
}
self::check($deadline, $shouldAbort);
return ['ok' => true, 'files' => $prepared, 'attachment_transport' => 'uploaded_files'];
return ['ok' => true, 'files' => $prepared, 'uploaded_indices' => $uploadedIndices,
'skipped' => $skipped, 'attachment_transport' => 'uploaded_files'];
} catch (\Throwable $error) {
// Never expose cURL response bodies, URLs, local paths, credentials or exception text.
$code = $error instanceof \RuntimeException ? $error->getMessage() : 'REQUIRED_FILES_PREPARE_FAILED';
@@ -122,11 +148,11 @@ final class DifyRequiredAttachmentUpload
'REQUIRED_FILES_PREPARE_FAILED' => '必需附件准备失败,本次未提交分析',
];
if (!isset($messages[$code])) $code = 'REQUIRED_FILES_PREPARE_FAILED';
if ($index > 0 && $total > 0) {
if ($index > 0 && $total > 0 && !in_array($index, array_column($skipped, 'index'), true)) {
try { self::notify($options, $index, $total, 'failed'); } catch (\Throwable $ignored) {}
}
return ['ok' => false, 'error_code' => $code, 'error' => $messages[$code],
'failed_index' => $index, 'attachment_count' => $total];
'failed_index' => $index, 'attachment_count' => $total, 'skipped' => $skipped];
} finally {
foreach ($temporary as $path) if (is_file($path)) @unlink($path);
}
@@ -140,6 +166,11 @@ final class DifyRequiredAttachmentUpload
catch (\Throwable $ignored) { $configured = []; }
}
$options = array_replace(is_array($configured) ? $configured : [], $options);
if (!array_key_exists('skip_missing', $options)) $options['skip_missing'] = true;
if (!is_bool($options['skip_missing'])) self::fail('CONFIG_INVALID');
$caFile = $options['ca_file'] ?? '';
if (!is_string($caFile) || ($caFile !== '' && (!is_file($caFile) || !is_readable($caFile)))) self::fail('CONFIG_INVALID');
$options['ca_file'] = $caFile;
$options['resolved_hosts'] = self::resolvedHosts(array_key_exists('resolved_hosts', $options)
? $options['resolved_hosts'] : []);
return $options;
@@ -172,7 +203,9 @@ final class DifyRequiredAttachmentUpload
private static function plan(array $files): array
{
$plan = [];
$index = 0;
foreach ($files as $file) {
++$index;
if (!is_array($file)) self::fail('REQUIRED_FILES_INVALID');
$type = strtolower((string) ($file['type'] ?? ''));
$mime = strtolower((string) ($file['mime_type'] ?? $file['mime'] ?? $file['content_type'] ?? ''));
@@ -182,7 +215,7 @@ final class DifyRequiredAttachmentUpload
if ($type === 'video' || str_starts_with($mime, 'video/') || in_array($extension, self::VIDEO_EXTENSIONS, true)) continue;
if (!in_array($type, ['image', 'document', 'audio'], true)
|| ($file['transfer_method'] ?? 'remote_url') !== 'remote_url' || !is_string($url)) self::fail('REQUIRED_FILES_INVALID');
$plan[] = ['type' => $type, 'url' => $url, 'parts' => self::url($url)];
$plan[] = ['index' => $index, 'type' => $type, 'url' => $url, 'parts' => self::url($url)];
}
return $plan;
}
@@ -239,20 +272,41 @@ final class DifyRequiredAttachmentUpload
return str_starts_with($path, $root);
}
private static function localPath(string $publicRoot, string $urlPath): string
private static function localPath(string $publicRoot, string $urlPath): ?string
{
if (preg_match('/%(?:2f|5c)/i', $urlPath)) self::fail('REQUIRED_FILES_INVALID');
$decoded = rawurldecode($urlPath);
if (!str_starts_with($decoded, '/uploads/') || preg_match('/[\x00-\x1f\x7f\\\\%:?#]/', $decoded)) self::fail('REQUIRED_FILES_INVALID');
foreach (explode('/', substr($decoded, 1)) as $segment) {
if (!str_starts_with($decoded, '/uploads/') || preg_match('/[\x00-\x1f\x7f\\\\%:?#<>"|*]/', $decoded)) self::fail('REQUIRED_FILES_INVALID');
$segments = explode('/', substr($decoded, 1));
foreach ($segments as $segment) {
if ($segment === '' || $segment === '.' || $segment === '..' || trim($segment) !== $segment
|| str_ends_with($segment, '.')) self::fail('REQUIRED_FILES_INVALID');
|| str_ends_with($segment, '.') || preg_match('/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i', $segment)) self::fail('REQUIRED_FILES_INVALID');
}
$uploads = realpath($publicRoot . '/uploads');
$real = realpath($publicRoot . $decoded);
if ($uploads === false || !self::inside($publicRoot, $uploads) || $real === false
|| !self::inside($uploads, $real) || !is_file($real) || !is_readable($real)) self::fail('REQUIRED_FILES_SOURCE_UNAVAILABLE');
return $real;
if ($uploads === false || !self::inside($publicRoot, $uploads) || !is_dir($uploads)) self::fail('REQUIRED_FILES_SOURCE_UNAVAILABLE');
$current = $uploads;
foreach (array_slice($segments, 1) as $position => $segment) {
$candidate = $current . DIRECTORY_SEPARATOR . $segment;
$real = realpath($candidate);
if ($real === false) {
// realpath(false) alone also means denied access or a broken symlink.
// A readable parent listing must confirm absence before skipping.
if (@lstat($candidate) !== false || is_link($candidate)) self::fail('REQUIRED_FILES_SOURCE_UNAVAILABLE');
$entries = @scandir($current);
if ($entries === false) self::fail('REQUIRED_FILES_SOURCE_UNAVAILABLE');
foreach ($entries as $entry) {
if ($entry === $segment || (PHP_OS_FAMILY === 'Windows' && strcasecmp($entry, $segment) === 0)) {
self::fail('REQUIRED_FILES_SOURCE_UNAVAILABLE');
}
}
return null;
}
if (!self::inside($uploads, $real)) self::fail('REQUIRED_FILES_SOURCE_UNAVAILABLE');
$last = $position === count($segments) - 2;
if (!is_readable($real) || ($last ? !is_file($real) : !is_dir($real))) self::fail('REQUIRED_FILES_SOURCE_UNAVAILABLE');
$current = $real;
}
return $current;
}
private static function tempRoot(string $root, string $publicRoot): string
@@ -286,7 +340,7 @@ final class DifyRequiredAttachmentUpload
}
}
private static function download(string $url, array $parts, string $path, int $maxBytes, float $deadline, ?callable $shouldAbort, array $options): void
private static function download(string $url, array $parts, string $path, int $maxBytes, float $deadline, ?callable $shouldAbort, array $options): bool
{
self::check($deadline, $shouldAbort);
$host = trim($parts['host'], '[]');
@@ -320,7 +374,7 @@ final class DifyRequiredAttachmentUpload
$bytes = 0;
$writeError = '';
try {
$curlOptions = self::curlOptions($url, $deadline, $shouldAbort);
$curlOptions = self::curlOptions($url, $deadline, $shouldAbort, $options['ca_file']);
$curlOptions[CURLOPT_RESOLVE] = [$host . ':' . $port . ':' . (str_contains($ip, ':') ? '[' . $ip . ']' : $ip)];
$curlOptions[CURLOPT_HEADERFUNCTION] = static function ($handle, string $line) use ($maxBytes, &$writeError): int {
if (preg_match('/^Content-Length:\s*(\d+)/i', $line, $match) && (float) $match[1] > $maxBytes) {
@@ -340,7 +394,10 @@ final class DifyRequiredAttachmentUpload
$result = self::execute($ch, $deadline, $shouldAbort);
if ($writeError !== '') self::fail($writeError);
if ($result['errno'] === CURLE_OPERATION_TIMEDOUT) self::fail('REQUIRED_FILES_TIMEOUT');
if ($result['errno'] !== CURLE_OK || $result['status'] !== 200 || $bytes === 0) self::fail('REQUIRED_FILES_DOWNLOAD_FAILED');
if ($result['errno'] !== CURLE_OK) self::fail('REQUIRED_FILES_DOWNLOAD_FAILED');
if (in_array($result['status'], [404, 410], true)) return false;
if ($result['status'] !== 200 || $bytes === 0) self::fail('REQUIRED_FILES_DOWNLOAD_FAILED');
return true;
} finally { curl_close($ch); fclose($output); }
}
@@ -369,7 +426,7 @@ final class DifyRequiredAttachmentUpload
&& ($remaining === 0 || (ord($packed[$bytes]) & (255 << (8 - $remaining))) === (ord($base[$bytes]) & (255 << (8 - $remaining))));
}
private static function upload(string $endpoint, string $apiKey, string $user, string $path, string $mime, string $name, float $deadline, ?callable $shouldAbort): string
private static function upload(string $endpoint, string $apiKey, string $user, string $path, string $mime, string $name, float $deadline, ?callable $shouldAbort, string $caFile): string
{
self::check($deadline, $shouldAbort);
$ch = curl_init();
@@ -377,7 +434,7 @@ final class DifyRequiredAttachmentUpload
$body = '';
$tooLarge = false;
try {
$options = self::curlOptions($endpoint, $deadline, $shouldAbort);
$options = self::curlOptions($endpoint, $deadline, $shouldAbort, $caFile);
$options[CURLOPT_POST] = true;
$options[CURLOPT_HTTPHEADER] = ['Authorization: Bearer ' . trim($apiKey), 'Accept: application/json', 'Expect:'];
$options[CURLOPT_POSTFIELDS] = ['user' => $user, 'file' => new \CURLFile($path, $mime, $name)];
@@ -397,7 +454,7 @@ final class DifyRequiredAttachmentUpload
} finally { curl_close($ch); }
}
private static function curlOptions(string $url, float $deadline, ?callable $shouldAbort): array
private static function curlOptions(string $url, float $deadline, ?callable $shouldAbort, string $caFile = ''): array
{
$remaining = max(1, (int) ceil(($deadline - microtime(true)) * 1000));
$options = [CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => false,
@@ -406,6 +463,7 @@ final class DifyRequiredAttachmentUpload
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_TIMEOUT_MS => $remaining, CURLOPT_CONNECTTIMEOUT_MS => min(10000, $remaining),
CURLOPT_NOSIGNAL => true, CURLOPT_NOPROGRESS => false];
if ($caFile !== '') $options[CURLOPT_CAINFO] = $caFile;
foreach (['CURLOPT_XFERINFOFUNCTION', 'CURLOPT_PROGRESSFUNCTION'] as $name) {
if (!defined($name)) continue;
$options[constant($name)] = static function (...$unused) use ($deadline, $shouldAbort): int {
@@ -447,9 +505,11 @@ final class DifyRequiredAttachmentUpload
if (microtime(true) >= $deadline) self::fail('REQUIRED_FILES_TIMEOUT');
}
private static function notify(array $options, int $index, int $total, string $status): void
private static function notify(array $options, int $index, int $total, string $status, ?string $reason = null): void
{
if (is_callable($options['on_upload'] ?? null)) ($options['on_upload'])(['index' => $index, 'total' => $total, 'status' => $status]);
$event = ['index' => $index, 'total' => $total, 'status' => $status];
if ($reason !== null) $event['reason'] = $reason;
if (is_callable($options['on_upload'] ?? null)) ($options['on_upload'])($event);
}
private static function fail(string $code): void { throw new \RuntimeException($code); }