Generate share passwords and offer them again beside the new link

Uploaders no longer have to make up a share password. With "Password
protect" on, the upload page has Generate and Copy under the field, and
the page the upload leads to offers the password once more beside the
link: masked, with the same copy button at the end of the field as the
link's. The password also derives the share's encryption key and only
its hash is stored, so a lost one means files nobody can open.

- PasswordGeneratorService draws from Random\Randomizer's secure engine.
  Characters are drawn uniformly and redrawn until every chosen set
  appears; passphrases come from EFF's large word list (CC BY 3.0 US,
  credited in the README), without its four hyphenated words.
- Admin settings gain a "Share Passwords" card: mode (off, on request,
  prefilled as protection is switched on), kind (characters: length
  12–64, the sets, look-alikes left out; passphrase: 4–10 words and a
  separator), and an example with its estimated entropy that follows the
  form before saving. Fields the chosen mode or kind hides are excluded
  from validation and keep their saved value. The default is on
  request, 20 letters and numbers without look-alikes.
- FileUploader flashes the password encrypted with the share's token;
  ShareCreated shows it only when the token matches, so a reload or any
  other visitor sees nothing. Crypt covers installs without
  SESSION_ENCRYPT, which the Docker setup does not set.
- The symbol set leaves out what chat apps turn into formatting and
  what breaks inside quotes, so a pasted password arrives unchanged.
- app.css imports group.css for <x-group>; .ai/rules/views.md records
  that <x-group> drops data-test and other attributes.
- Tests cover the generator, the admin card's saving, validation and
  example, prefill and generate on the upload page, the flash, and in
  Chromium Generate and Copy on the upload page and the masked copy on
  the share page. The admin settings page now has six headed sections.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Andreas Reinhold / reini
2026-09-16 11:00:11 +02:00
co-authored by Claude Opus 5
parent a88a052d9a
commit 504971ad7f
20 changed files with 8672 additions and 6 deletions
+119 -1
View File
@@ -3,8 +3,10 @@
namespace App\Livewire\Admin;
use App\Models\Setting;
use App\Services\PasswordGeneratorService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Layout;
use Livewire\Component;
@@ -35,6 +37,23 @@ class AdminSettings extends Component
public bool $allowNeverExpire = false;
/** How the upload page offers generated share passwords: `off`, `button` or `prefill`. */
public string $passwordGeneratorMode = 'button';
/** `characters` or `passphrase`. */
public string $passwordGeneratorType = 'characters';
public int $passwordLength = 20;
/** @var list<string> */
public array $passwordCharacterSets = [];
public bool $passwordAvoidAmbiguous = true;
public int $passphraseWords = 6;
public string $passphraseSeparator = 'hyphen';
public string $siteTitle = '';
public string $siteDescription = '';
@@ -61,6 +80,15 @@ class AdminSettings extends Component
$this->allowNeverExpire = (bool) Setting::get('allow_never_expire', false);
$this->siteTitle = Setting::get('site_title', '') ?? '';
$this->siteDescription = Setting::get('site_description', '') ?? '';
$passwordOptions = app(PasswordGeneratorService::class)->options();
$this->passwordGeneratorMode = $passwordOptions['mode'];
$this->passwordGeneratorType = $passwordOptions['type'];
$this->passwordLength = $passwordOptions['length'];
$this->passwordCharacterSets = $passwordOptions['characterSets'];
$this->passwordAvoidAmbiguous = $passwordOptions['avoidAmbiguous'];
$this->passphraseWords = $passwordOptions['words'];
$this->passphraseSeparator = $passwordOptions['separator'];
}
public static function phpMaxUploadMb(): int
@@ -88,7 +116,7 @@ class AdminSettings extends Component
{
$phpMaxMb = self::phpMaxUploadMb();
$this->validate([
$validated = $this->validate([
'colorProfile' => ['required', 'string', Rule::in(array_keys(Scheme::profiles()))],
'maxFileSize' => ['required', 'integer', 'min:1', 'max:'.$phpMaxMb],
'maxStorageQuota' => ['required', 'integer', 'min:1'],
@@ -97,8 +125,10 @@ class AdminSettings extends Component
'siteTitle' => ['nullable', 'string', 'max:255'],
'siteDescription' => ['nullable', 'string', 'max:1000'],
'siteLogo' => ['nullable', 'file', 'mimes:png,jpg,jpeg,gif,webp', 'max:2048'],
...$this->passwordGeneratorRules(),
], [
'maxFileSize.max' => __('Cannot exceed the PHP limit of :max MB. Increase upload_max_filesize and post_max_size in your PHP configuration.', ['max' => $phpMaxMb]),
...$this->passwordGeneratorMessages(),
]);
if ($this->systemPassword) {
@@ -116,6 +146,8 @@ class AdminSettings extends Component
Setting::set('site_title', $this->siteTitle ?: null);
Setting::set('site_description', $this->siteDescription ?: null);
$this->savePasswordGeneratorSettings($validated);
if ($this->siteLogo && is_object($this->siteLogo)) {
$existingLogo = Setting::get('site_logo');
if ($existingLogo) {
@@ -132,6 +164,87 @@ class AdminSettings extends Component
$this->success(__('Settings saved successfully.'));
}
/**
* The generator's rules. A field the chosen mode or type hides is excluded, so it never blocks
* saving and keeps the value saved before.
*
* @return array<string, array<int, mixed>>
*/
protected function passwordGeneratorRules(): array
{
$characters = ['exclude_if:passwordGeneratorMode,off', 'exclude_unless:passwordGeneratorType,characters'];
$passphrase = ['exclude_if:passwordGeneratorMode,off', 'exclude_unless:passwordGeneratorType,passphrase'];
return [
'passwordGeneratorMode' => ['required', 'string', Rule::in(PasswordGeneratorService::MODES)],
'passwordGeneratorType' => ['exclude_if:passwordGeneratorMode,off', 'required', 'string', Rule::in(PasswordGeneratorService::TYPES)],
'passwordLength' => [...$characters, 'required', 'integer', 'min:'.PasswordGeneratorService::MIN_LENGTH, 'max:'.PasswordGeneratorService::MAX_LENGTH],
'passwordCharacterSets' => [...$characters, 'required', 'array'],
'passwordCharacterSets.*' => [...$characters, 'string', Rule::in(array_keys(PasswordGeneratorService::CHARACTER_SETS))],
'passwordAvoidAmbiguous' => [...$characters, 'boolean'],
'passphraseWords' => [...$passphrase, 'required', 'integer', 'min:'.PasswordGeneratorService::MIN_WORDS, 'max:'.PasswordGeneratorService::MAX_WORDS],
'passphraseSeparator' => [...$passphrase, 'required', 'string', Rule::in(array_keys(PasswordGeneratorService::SEPARATORS))],
];
}
/**
* @return array<string, string>
*/
protected function passwordGeneratorMessages(): array
{
return [
'passwordCharacterSets.required' => __('Choose at least one kind of character.'),
];
}
/**
* Store the generator settings that passed validation; excluded ones keep their saved value.
*
* @param array<string, mixed> $validated
*/
protected function savePasswordGeneratorSettings(array $validated): void
{
Setting::set('password_generator_mode', $validated['passwordGeneratorMode']);
if (array_key_exists('passwordGeneratorType', $validated)) {
Setting::set('password_generator_type', $validated['passwordGeneratorType']);
}
if (array_key_exists('passwordLength', $validated)) {
Setting::set('password_generator_length', $validated['passwordLength']);
Setting::set('password_generator_character_sets', implode(',', $validated['passwordCharacterSets']));
Setting::set('password_generator_avoid_ambiguous', $validated['passwordAvoidAmbiguous'] ? '1' : '0');
}
if (array_key_exists('passphraseWords', $validated)) {
Setting::set('password_generator_words', $validated['passphraseWords']);
Setting::set('password_generator_separator', $validated['passphraseSeparator']);
}
}
/**
* The form's generator options while they are valid, for the example; `null` otherwise.
*
* @return array{type: string, length: int, characterSets: list<string>, avoidAmbiguous: bool, words: int, separator: string}|null
*/
protected function passwordPreviewOptions(): ?array
{
$values = $this->only(['passwordGeneratorMode', 'passwordGeneratorType', 'passwordLength', 'passwordCharacterSets', 'passwordAvoidAmbiguous', 'passphraseWords', 'passphraseSeparator']);
if ($this->passwordGeneratorMode === 'off' || Validator::make($values, $this->passwordGeneratorRules())->fails()) {
return null;
}
return [
'type' => $this->passwordGeneratorType,
'length' => $this->passwordLength,
'characterSets' => array_values($this->passwordCharacterSets),
'avoidAmbiguous' => $this->passwordAvoidAmbiguous,
'words' => $this->passphraseWords,
'separator' => $this->passphraseSeparator,
];
}
public function removeLogo(): void
{
$existingLogo = Setting::get('site_logo');
@@ -157,10 +270,15 @@ class AdminSettings extends Component
public function render(): mixed
{
$passwordGenerator = app(PasswordGeneratorService::class);
$passwordPreviewOptions = $this->passwordPreviewOptions();
return view('livewire.admin.admin-settings', [
'hasSystemPassword' => (bool) Setting::get('system_password'),
'currentLogo' => Setting::get('site_logo'),
'phpMaxUploadMb' => self::phpMaxUploadMb(),
'passwordExample' => $passwordPreviewOptions ? $passwordGenerator->generate($passwordPreviewOptions) : null,
'passwordEntropy' => $passwordPreviewOptions ? $passwordGenerator->entropyBits($passwordPreviewOptions) : null,
]);
}
}
+35
View File
@@ -3,7 +3,9 @@
namespace App\Livewire;
use App\Models\Setting;
use App\Services\PasswordGeneratorService;
use App\Services\ShareService;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Layout;
@@ -101,6 +103,29 @@ class FileUploader extends Component
}
}
/**
* 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 removeFile(int $index): void
{
unset($this->files[$index], $this->relativePaths[$index]);
@@ -184,6 +209,15 @@ class FileUploader extends Component
'max_downloads' => $this->maxDownloads ?: null,
]);
// 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);
}
@@ -197,6 +231,7 @@ class FileUploader extends Component
'siteDescription' => Setting::get('site_description'),
'siteLogo' => Setting::get('site_logo'),
'allowNeverExpire' => (bool) Setting::get('allow_never_expire', false),
'passwordGeneratorMode' => app(PasswordGeneratorService::class)->mode(),
]);
}
}
+12
View File
@@ -5,7 +5,9 @@ namespace App\Livewire;
use App\Models\Setting;
use App\Models\Share;
use App\Services\QrCodeService;
use Illuminate\Support\Facades\Crypt;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Locked;
use Livewire\Component;
#[Layout('layouts.app')]
@@ -13,9 +15,19 @@ class ShareCreated extends Component
{
public Share $share;
/** The share's password, offered once to the uploader who just set it; `null` on any other visit. */
#[Locked]
public ?string $password = null;
public function mount(Share $share): void
{
$this->share = $share;
$flashedPassword = session('share_password');
if (is_array($flashedPassword) && ($flashedPassword['token'] ?? null) === $share->token) {
$this->password = Crypt::decryptString($flashedPassword['password']);
}
}
public function render(): mixed
+197
View File
@@ -0,0 +1,197 @@
<?php
namespace App\Services;
use App\Models\Setting;
use InvalidArgumentException;
use Random\Randomizer;
/**
* Random share passwords, drawn the way Admin settings say.
*
* Every draw comes from `Random\Randomizer`'s default engine, which is the operating system's
* CSPRNG. Passphrases come from EFF's large word list (CC BY 3.0 US), without its four hyphenated
* words so a separator always splits a passphrase into its words.
*/
class PasswordGeneratorService
{
/** Off: uploaders type their own. Button: a Generate button fills one in. Prefill: filled in as protection is switched on. */
public const MODES = ['off', 'button', 'prefill'];
public const TYPES = ['characters', 'passphrase'];
/**
* The characters each set draws from. The symbols leave out what chat apps turn into formatting
* (`* _ ~ \``) and what breaks once pasted into quotes or markup (`' " \ < >`).
*
* @var array<string, string>
*/
public const CHARACTER_SETS = [
'uppercase' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'lowercase' => 'abcdefghijklmnopqrstuvwxyz',
'numbers' => '0123456789',
'symbols' => '!#$%&()+,-./:;=?@[]{}',
];
/** Characters that read alike in many typefaces. */
public const AMBIGUOUS_CHARACTERS = '0O1lI';
/** @var array<string, string> */
public const SEPARATORS = [
'hyphen' => '-',
'dot' => '.',
'underscore' => '_',
'space' => ' ',
];
public const MIN_LENGTH = 12;
public const MAX_LENGTH = 64;
public const MIN_WORDS = 4;
public const MAX_WORDS = 10;
/**
* @var array{mode: string, type: string, length: int, characterSets: list<string>, avoidAmbiguous: bool, words: int, separator: string}
*/
public const DEFAULTS = [
'mode' => 'button',
'type' => 'characters',
'length' => 20,
'characterSets' => ['uppercase', 'lowercase', 'numbers'],
'avoidAmbiguous' => true,
'words' => 6,
'separator' => 'hyphen',
];
/** @var list<string>|null */
private ?array $wordList = null;
/**
* How the upload page offers generated passwords.
*/
public function mode(): string
{
$mode = Setting::get('password_generator_mode');
return in_array($mode, self::MODES, true) ? $mode : self::DEFAULTS['mode'];
}
/**
* The saved generator settings, with the default for anything missing or no longer allowed.
*
* @return array{mode: string, type: string, length: int, characterSets: list<string>, avoidAmbiguous: bool, words: int, separator: string}
*/
public function options(): array
{
$type = Setting::get('password_generator_type');
$length = (int) Setting::get('password_generator_length', self::DEFAULTS['length']);
$words = (int) Setting::get('password_generator_words', self::DEFAULTS['words']);
$separator = Setting::get('password_generator_separator');
$characterSets = array_values(array_intersect(
array_keys(self::CHARACTER_SETS),
explode(',', (string) Setting::get('password_generator_character_sets')),
));
return [
'mode' => $this->mode(),
'type' => in_array($type, self::TYPES, true) ? $type : self::DEFAULTS['type'],
'length' => $length >= self::MIN_LENGTH && $length <= self::MAX_LENGTH ? $length : self::DEFAULTS['length'],
'characterSets' => $characterSets ?: self::DEFAULTS['characterSets'],
'avoidAmbiguous' => (bool) Setting::get('password_generator_avoid_ambiguous', self::DEFAULTS['avoidAmbiguous'] ? '1' : '0'),
'words' => $words >= self::MIN_WORDS && $words <= self::MAX_WORDS ? $words : self::DEFAULTS['words'],
'separator' => is_string($separator) && array_key_exists($separator, self::SEPARATORS) ? $separator : self::DEFAULTS['separator'],
];
}
/**
* Generate a password from the given options, or from the saved settings.
*
* @param array{type: string, length: int, characterSets: list<string>, avoidAmbiguous: bool, words: int, separator: string}|null $options
*/
public function generate(?array $options = null): string
{
$options ??= $this->options();
return $options['type'] === 'passphrase'
? $this->passphrase($options['words'], self::SEPARATORS[$options['separator']])
: $this->characters($options['length'], $options['characterSets'], $options['avoidAmbiguous']);
}
/**
* Draw characters uniformly from the chosen sets, drawing again until every set shows up at
* least once. Redrawing keeps each valid password equally likely, where placing one character
* of each set first would not.
*
* @param list<string> $characterSets
*/
public function characters(int $length, array $characterSets, bool $avoidAmbiguous): string
{
$alphabets = $this->alphabets($characterSets, $avoidAmbiguous);
if ($alphabets === [] || $length < count($alphabets)) {
throw new InvalidArgumentException('A password needs at least one character set and room for each of them.');
}
$randomizer = new Randomizer;
do {
$password = $randomizer->getBytesFromString(implode('', $alphabets), $length);
} while (array_filter($alphabets, fn (string $alphabet): bool => strpbrk($password, $alphabet) === false) !== []);
return $password;
}
/**
* Draw words from the word list, each independently of the others.
*/
public function passphrase(int $words, string $separator): string
{
$wordList = $this->wordList();
$randomizer = new Randomizer;
return implode($separator, array_map(
fn (): string => $wordList[$randomizer->getInt(0, count($wordList) - 1)],
range(1, max(1, $words)),
));
}
/**
* Roughly how many bits of entropy a password from these options carries.
*
* @param array{type: string, length: int, characterSets: list<string>, avoidAmbiguous: bool, words: int} $options
*/
public function entropyBits(array $options): int
{
if ($options['type'] === 'passphrase') {
return (int) floor($options['words'] * log(count($this->wordList()), 2));
}
$alphabetSize = strlen(implode('', $this->alphabets($options['characterSets'], $options['avoidAmbiguous'])));
return $alphabetSize > 0 ? (int) floor($options['length'] * log($alphabetSize, 2)) : 0;
}
/**
* @return list<string>
*/
public function wordList(): array
{
return $this->wordList ??= file(resource_path('wordlists/eff-large-wordlist.txt'), FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}
/**
* The characters of each chosen set, without the look-alikes when asked.
*
* @param list<string> $characterSets
* @return array<string, string>
*/
private function alphabets(array $characterSets, bool $avoidAmbiguous): array
{
return collect(self::CHARACTER_SETS)
->only($characterSets)
->map(fn (string $alphabet): string => $avoidAmbiguous ? str_replace(str_split(self::AMBIGUOUS_CHARACTERS), '', $alphabet) : $alphabet)
->all();
}
}