Files
SealShare/app/Http/Controllers/DownloadController.php
T
surtic86andClaude Opus 5 4530298398
docker / test (8.5) (push) Successful in 3m10s
linter / quality (push) Successful in 1m5s
tests / ci (8.5) (push) Successful in 3m9s
docker / build-and-push (push) Successful in 21m5s
docker / release (push) Skipped
Cut over-engineering found by a repo-wide audit
- Config: auth, services, logging, queue and database only repeated the
  framework's own files and are gone; the others keep only the keys that
  differ (app version, cache serializable_classes, session cookie name,
  Markdown mail theme, the shares disk, three Octane values, Livewire's
  pagination theme and payload guards).
- Email verification is removed: User never implemented MustVerifyEmail,
  so it was never enforced, and SealShare has a single admin and no
  registration. CreateNewUser goes with it.
- FileEncryptionService::encryptFile() and generateSalt() were only used
  by tests; tests build files with encryptTestFile() in tests/Pest.php.
- The expiration options are defined once, as Share::EXPIRATIONS. "30 Days"
  now lasts 30 days instead of a calendar month, and Admin settings only
  save a default expiration that is one of the options.
- One-caller helpers are inlined, the uploader reads chunk responses with
  XHR's responseType, and starter-kit leftovers are removed.
- Docker: PHP reads the PHP_* limits from the environment itself
  (${VAR:-default} in uploads.ini); both entrypoints stop writing the ini.
  docker-compose.yml shares the app and scheduler variables through one
  anchor. The dev image installs gd for the screenshot publisher and fake
  test images.
- Development runs in Docker only: the composer dev script, concurrently,
  laravel/pail, laravel/sail, autoprefixer and the shell-quote override
  are gone.
- phpunit.xml forces the test environment with <server> entries, so tests
  run in the dev container no longer use its real database.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 23:14:33 +02:00

142 lines
4.6 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Share;
use App\Models\ShareFile;
use App\Services\FileEncryptionService;
use App\Services\ShareService;
use GuzzleHttp\Psr7\PumpStream;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\StreamedResponse;
use ZipStream\CompressionMethod;
use ZipStream\ZipStream;
class DownloadController extends Controller
{
public function __construct(
private FileEncryptionService $encryptionService,
private ShareService $shareService,
) {}
/**
* Download all files as a ZIP archive, streamed file by file as it is decrypted: stored without
* compression, with ZIP64 for files over 4 GB, and never held in memory or written to disk.
*/
public function download(Request $request, Share $share): StreamedResponse
{
abort_if(! $share->isCompleted() || $share->isExpired(), 404);
$share->load('files');
$key = $this->resolveDecryptionKey($share);
// Counted before the body streams: the session is saved by then.
abort_unless($this->shareService->claimDownload($share, $request->session()), 404);
return new StreamedResponse(function () use ($share, $key): void {
$zip = new ZipStream(
defaultCompressionMethod: CompressionMethod::STORE,
defaultEnableZeroHeader: true,
sendHttpHeaders: false,
flushOutput: true,
);
foreach ($share->files as $file) {
$chunks = $this->encryptionService->decryptedChunks(
Storage::disk('shares')->path($share->token.'/'.basename($file->stored_path)),
$key,
);
$zip->addFileFromPsr7Stream(fileName: $this->archiveName($file), stream: new PumpStream(function () use ($chunks): string|false {
while ($chunks->valid() && $chunks->current() === '') {
$chunks->next();
}
if (! $chunks->valid()) {
return false;
}
$chunk = $chunks->current();
$chunks->next();
return $chunk;
}));
}
$zip->finish();
}, 200, [
'Content-Type' => 'application/zip',
'Content-Disposition' => HeaderUtils::makeDisposition('attachment', 'share-'.$share->token.'.zip'),
]);
}
/**
* Download a single file.
*/
public function downloadFile(Request $request, Share $share, ShareFile $shareFile): StreamedResponse
{
abort_if(! $share->isCompleted() || $share->isExpired(), 404);
abort_if($shareFile->share_id !== $share->id, 404);
$key = $this->resolveDecryptionKey($share);
abort_unless($this->shareService->claimDownload($share, $request->session()), 404);
$encryptedPath = Storage::disk('shares')->path($share->token.'/'.basename($shareFile->stored_path));
$mimeType = $shareFile->mime_type ?? 'application/octet-stream';
$headers = [
'Content-Type' => $mimeType,
'Content-Disposition' => HeaderUtils::makeDisposition(
'attachment',
$shareFile->original_name,
'download',
),
];
if ($shareFile->file_size !== null) {
$headers['Content-Length'] = $shareFile->file_size;
}
return new StreamedResponse(function () use ($encryptedPath, $key): void {
foreach ($this->encryptionService->decryptedChunks($encryptedPath, $key) as $chunk) {
echo $chunk;
flush();
}
}, 200, $headers);
}
/**
* A file's path inside the archive: its folder path when it came from a dropped folder, never
* one that could reach outside the archive.
*/
private function archiveName(ShareFile $file): string
{
$filename = str_replace('\\', '/', $file->relative_path ?: $file->original_name);
if (str_starts_with($filename, '/') || str_contains($filename, '..')) {
return basename($filename);
}
return $filename;
}
/**
* Resolve the decryption key from session or share.
*/
private function resolveDecryptionKey(Share $share): string
{
if ($share->isPasswordProtected()) {
$key = session('share_key_'.$share->token);
abort_if(! $key, 403, 'Password required');
return $key;
}
return $this->shareService->getDecryptionKey($share);
}
}