Files
SealShare/app/Livewire/FileUploader.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

209 lines
7.1 KiB
PHP

<?php
namespace App\Livewire;
use App\Models\Setting;
use App\Models\Share;
use App\Services\PasswordGeneratorService;
use App\Services\ShareService;
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* The upload page. The browser encrypts each file chunk by chunk and sends the chunks to
* UploadChunkController (resources/js/share-uploader.js); this component registers the files
* into a pending share, lists them and completes the share with its options.
*/
#[Layout('layouts.app')]
class FileUploader extends Component
{
/** The pending share this page uploads into: created with the first file, one per page load. */
#[Locked]
public ?string $pendingToken = null;
public bool $usePassword = false;
public string $password = '';
public string $password_confirmation = '';
public string $expiration = '7d';
public ?int $maxDownloads = null;
public function mount(): void
{
$this->expiration = Setting::get('default_expiration', '7d') ?: '7d';
}
/**
* Register the files a visitor chose and hand the browser what it encrypts and sends them
* with. A file an admin limit refuses gets `null` in its place and the reason under `files`.
*
* @param array<int, array{name?: mixed, size?: mixed, path?: mixed}> $files
* @return array<int, array{id: int, url: string, key: string, noncePrefix: string, chunkSize: int, chunkCount: int}|null>
*/
public function registerFiles(array $files, ShareService $shareService): array
{
$this->resetErrorBag('files');
$targets = [];
foreach ($files as $file) {
try {
$shareFile = $shareService->registerFile(
$this->pendingShare(),
(string) ($file['name'] ?? ''),
(int) ($file['size'] ?? -1),
isset($file['path']) ? (string) $file['path'] : null,
);
} catch (ValidationException $e) {
if (! $this->getErrorBag()->has('files')) {
$this->addError('files', $e->errors()['files'][0]);
}
$targets[] = null;
continue;
}
if ($this->pendingToken !== $shareFile->share->token) {
$this->pendingToken = $shareFile->share->token;
session()->push('pending_shares', $this->pendingToken);
}
$header = $shareService->readHeader($shareFile);
$targets[] = [
'id' => $shareFile->id,
'url' => Str::beforeLast(route('upload.chunk', ['shareFile' => $shareFile, 'index' => 0]), '/'),
'key' => $shareFile->share->encryption_key,
'noncePrefix' => bin2hex($header['noncePrefix']),
'chunkSize' => $header['chunkSize'],
'chunkCount' => $header['chunkCount'],
];
}
return $targets;
}
/**
* Take files out of the pending share, whether or not their upload finished.
*
* @param array<int, mixed> $fileIds
*/
public function removeFiles(array $fileIds, ShareService $shareService): void
{
$files = $this->pendingShare()?->files()->whereIn('id', array_map('intval', $fileIds))->get() ?? [];
foreach ($files as $file) {
$shareService->removeFile($file);
}
$this->resetErrorBag('files');
}
/**
* Fill in a generated password as protection is switched on, when the admin chose "Prefilled".
* A password already in the field stays.
*/
public function updatedUsePassword(bool $value): void
{
$passwordGenerator = app(PasswordGeneratorService::class);
if ($value && $this->password === '' && $passwordGenerator->mode() === 'prefill') {
$this->password = $passwordGenerator->generate();
}
}
public function generatePassword(PasswordGeneratorService $passwordGenerator): void
{
if ($passwordGenerator->mode() === 'off') {
return;
}
$this->password = $passwordGenerator->generate();
$this->resetErrorBag('password');
}
public function createShare(ShareService $shareService): void
{
$rules = [];
if (! Setting::get('allow_never_expire', false)) {
$rules['expiration'] = ['required', 'string', Rule::in(array_keys(Share::EXPIRATIONS))];
}
if ($this->usePassword) {
$rules['password'] = ['required', 'string', 'min:8'];
}
if ($rules !== []) {
$this->validate($rules, [
'expiration.required' => __('An expiration time is required.'),
]);
}
$pendingShare = $this->pendingShare();
if ($pendingShare === null) {
$this->addError('files', __('Please select at least one file to upload.'));
return;
}
$share = $shareService->completeShare($pendingShare, [
'password' => $this->usePassword ? $this->password : null,
'expires_at' => isset(Share::EXPIRATIONS[$this->expiration])
? now()->add(CarbonInterval::make(Share::EXPIRATIONS[$this->expiration]['interval']))
: null,
'max_downloads' => $this->maxDownloads ?: null,
]);
session()->put('pending_shares', array_values(array_diff(session('pending_shares', []), [$share->token])));
// The page the upload leads to offers the password once more, next to the link; it is
// never stored in the clear, so this flash is the only way it gets there.
if ($this->usePassword) {
session()->flash('share_password', [
'token' => $share->token,
'password' => Crypt::encryptString($this->password),
]);
}
$this->redirect(route('share.created', $share), navigate: true);
}
public function render(): mixed
{
$shareService = app(ShareService::class);
$pendingFiles = $this->pendingShare()?->files()->orderBy('id')->get() ?? collect();
return view('livewire.file-uploader', [
'pendingFiles' => $pendingFiles,
'allFilesUploaded' => $pendingFiles->isNotEmpty() && $pendingFiles->every(fn ($file): bool => $file->completed_at !== null),
'isStorageFull' => $shareService->isStorageFull(),
'allowNeverExpire' => (bool) Setting::get('allow_never_expire', false),
'passwordGeneratorMode' => app(PasswordGeneratorService::class)->mode(),
]);
}
/**
* This page's pending share, while it is still pending and this session started it.
*/
private function pendingShare(): ?Share
{
if ($this->pendingToken === null || ! in_array($this->pendingToken, session('pending_shares', []), true)) {
return null;
}
return Share::query()->where('token', $this->pendingToken)->whereNull('completed_at')->first();
}
}