Files
SealShare/app/Services/PasswordGeneratorService.php
T
Andreas Reinhold / reiniandClaude Opus 5 504971ad7f 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>
2026-09-16 11:00:11 +02:00

198 lines
7.2 KiB
PHP

<?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();
}
}