Files
feuerwerk/api/lib/UserStore.php
T
adminandClaude Opus 5.5 14972d057f
game-maker / gate (push) Successful in 3m53s
game-maker / suite (push) Successful in 11m55s
Refactoring round 8: hide data files, safe saves, Esc as Cancel (#85)
Recurring cleanup round over the code since round 7 (bc688f3). The
issue now also asks to fix bugs and small inconsistencies found on the
way, so unlike the rounds before, this one changes behaviour in a few
places. Duplicated code in api went from 23 clones with 228 lines to
none (jscpd, at least 50 tokens). In src it stays at 22 clones with
271 lines, the same before and after.

Bugs:
- nginx served project and snapshot files as they were, so anyone who
  knew a project id could read it without signing in. Every file the
  API writes now goes through AtomicFile (temp file, mode, rename).
  Projects, snapshots, releases, accounts and sessions are 0640, and
  nginx answers 403 for them.
- Any signed-in account could delete a shared image, font or sound,
  which projects of other accounts may wear. Deleting one is now for
  administrators only. The editor never deleted a file, so the
  client's delete is gone.
- Two saves of one project could run at once. The lock file was
  removed after each save, so a waiting save and the next one locked
  different files. The lock file now stays, and deleting a project
  takes the lock as well.
- Bytes that are no picture got a 500 instead of a 422, because the
  error handler also threw for warnings silenced with @.
- A session file was rewritten in place. A request reading it at that
  moment found it empty and was signed out. It is replaced atomically.
- Delete did nothing for a shape picked in the vector art list. Delete
  now goes through removeSelection, one case per kind of selection,
  and a kind without a case fails the type check.

Inconsistencies:
- Escape on a question does what its Cancel does. Cancel on "Delete
  project?" and "Restore snapshot?" leads back to the picker or the
  list like the other questions did, and so does deleting a project.
- Editor texts use American spelling throughout, like the port names:
  48 British spellings in 45 lines (colour, centre, initialised).
- objectName and groupName replace eleven copies of "own name, else
  the asset's" and three of "Group". One copy fell back to the object
  id instead of "?".

Duplicates, dead code, comments:
- routeFiles serves images, fonts and sounds instead of three copies.
  HashedFileStore holds what the three stores shared: keeping a file
  under its hash with its name, listing and deleting. The stores keep
  only which bytes they take and what a record says.
- AtomicFile replaces nine copies of temp file plus rename.
- removeShapes is the one way the canvas, the inspector button and
  Delete take shapes out.
- GraphInterpreter.fire was called by tests only. The 54 calls use a
  helper in tests/helpers.ts now.
- FileStore.delete, HttpFileStore.delete and the PluginApi type were
  unused. A doc comment in actions.ts sat above the wrong function.

Checked and left as is:
- solidCells is used by tests only. It is the per-cell view before the
  merge into rectangles, the one place the largest-scale rule shows.
- An undo checker ran all 124 commands of the unit tests and compared
  the project before and after undo. The only differences are empty
  ports, groups and notes lists where there were none, which the file
  format drops anyway.

Docs:
- README: the check sum.
- Wiki, own commit: API (admin-only deletes, 422, file modes, lock
  file), Home (the "Not yet" list named three things that exist),
  Concepts, Keyboard, Vector art, Architecture and Development, and
  the 38 characters Gitea flagged as ambiguous on eight pages.
- .gitignore: the lock files, and pasted-*.png in any folder, which
  keeps the screenshot archive out.

Tests:
- ./check.sh: 195 files, 2817 tests, exit 0 (+2 for the name helpers).
- PHP: accounts 52 in the web container and 53 in the CI image with
  the race test (+2), snapshots 15 (+1), releases 20.
- Full e2e run: ALL PASSED, 1586 checks (+6 in 12, 47, 49 and 50).
- Smokes jumprun, tetris, actor: 24, 19 and 21 checks. The example
  project files were restored byte for byte afterwards.
- The file stores of HEAD and of this commit give byte-identical
  output for the live folders and for store, list and delete in a
  throwaway folder.
- Counter-checks, all fail as expected: a 500 for bad bytes fails 12,
  no admin check fails 49, removing the lock file again loses saves
  in 3 of 3 runs (151 to 170 of 321), Delete ignoring shapes fails 47,
  Escape that only closes fails 50, and dropping the shape case fails
  the type check (TS2366).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 18:12:55 +02:00

222 lines
8.0 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
/**
* The accounts, as one JSON file: `data/users.json` holding `{username, password, role, createdAt}`
* per user, where `password` is a hash from `password_hash` – the plain one is never stored.
*
* An entry without `role` is a `user` (#180): the weaker of the two is what a missing field means,
* so a hand-written file never hands out rights by accident. `createdAt` is missing on the accounts
* from before #179 and stays empty for them.
*
* Accounts are made from the command line (`tools/make-user.php`) or by an administrator through
* the `users` routes (#179); nobody can sign up over the wire.
*/
final class UserStore
{
/**
* The shortest password an account may be given. The sign-in form knows the same number
* (`loginRules.ts`) so it can say so without asking, but this is the one that decides: a
* client is free to send anything.
*/
public const MIN_PASSWORD_LENGTH = 8;
public const ROLES = ['admin', 'user'];
public function __construct(private readonly string $file) {}
public static function isValidName(string $name): bool
{
return (bool) preg_match('/^[a-z0-9][a-z0-9._-]{1,31}$/i', $name);
}
public static function isValidPassword(string $password): bool
{
return strlen($password) >= self::MIN_PASSWORD_LENGTH;
}
public static function isValidRole(string $role): bool
{
return in_array($role, self::ROLES, true);
}
/** The name as stored, or null when the pair does not match an account. */
public function verify(string $username, string $password): ?string
{
$user = $this->find($username);
if ($user === null || !password_verify($password, $user['password'])) {
return null;
}
return $user['username'];
}
public function exists(string $username): bool
{
return $this->find($username) !== null;
}
/** `user` for an account that does not exist, the same as for one without a role. */
public function role(string $username): string
{
return $this->find($username)['role'] ?? 'user';
}
/**
* Every account as the API may show it – never the hash.
*
* @return list<array{username:string,role:string,createdAt:string}>
*/
public function accounts(): array
{
return array_map(
static fn(array $u): array => [
'username' => $u['username'],
'role' => $u['role'],
'createdAt' => $u['createdAt'],
],
$this->all(),
);
}
public function adminCount(): int
{
return count(array_filter($this->all(), static fn(array $u): bool => $u['role'] === 'admin'));
}
/**
* Adds the account or replaces the password of one that is already there. Without `$role` a new
* account is a `user` and an existing one keeps what it has, so resetting a password from the
* command line never demotes an administrator.
*/
public function put(string $username, string $password, ?string $role = null): void
{
if (!self::isValidName($username)) {
throw new InvalidArgumentException("Invalid user name: {$username}");
}
if ($role !== null && !self::isValidRole($role)) {
throw new InvalidArgumentException("Invalid role: {$role}");
}
$existing = $this->find($username);
$users = $this->without($username);
$users[] = [
'username' => $existing['username'] ?? $username,
'password' => password_hash($password, PASSWORD_DEFAULT),
'role' => $role ?? $existing['role'] ?? 'user',
'createdAt' => $existing !== null ? $existing['createdAt'] : gmdate('c'),
];
$this->write($users);
}
/** @return bool False when there is no such account. */
public function setRole(string $username, string $role): bool
{
if (!self::isValidRole($role)) {
throw new InvalidArgumentException("Invalid role: {$role}");
}
return $this->change($username, static fn(array $u): array => ['role' => $role] + $u);
}
/**
* Gives an account a new name. Only the name: the projects that carry the old one as `owner`
* and the sessions that do are the caller's to move (see `Store::transfer`).
*
* @return bool False when there is no such account.
* @throws InvalidArgumentException when the new name is invalid or taken by another account.
*/
public function rename(string $from, string $to): bool
{
if (!self::isValidName($to)) {
throw new InvalidArgumentException("Invalid user name: {$to}");
}
$other = $this->find($to);
// Only a change of case is the same account; any other match is somebody else's name.
if ($other !== null && strcasecmp($other['username'], $from) !== 0) {
throw new InvalidArgumentException("The name {$to} is taken");
}
return $this->change($from, static fn(array $u): array => ['username' => $to] + $u);
}
/** @return bool False when there is no such account. */
public function remove(string $username): bool
{
if ($this->find($username) === null) {
return false;
}
$this->write($this->without($username));
return true;
}
/** @param callable(array):array $edit */
private function change(string $username, callable $edit): bool
{
$user = $this->find($username);
if ($user === null) {
return false;
}
$users = $this->without($username);
$users[] = $edit($user);
$this->write($users);
return true;
}
/** @return list<array{username:string,password:string,role:string,createdAt:string}> */
private function without(string $username): array
{
return array_values(
array_filter($this->all(), static fn(array $u): bool => strcasecmp($u['username'], $username) !== 0),
);
}
/** @return array{username:string,password:string,role:string,createdAt:string}|null */
private function find(string $username): ?array
{
foreach ($this->all() as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return $user;
}
}
return null;
}
/** @return list<array{username:string,password:string,role:string,createdAt:string}> */
private function all(): array
{
if (!is_file($this->file)) {
return [];
}
$raw = file_get_contents($this->file);
$data = $raw === false ? null : json_decode($raw, true);
if (!is_array($data) || !is_array($data['users'] ?? null)) {
return [];
}
$users = [];
foreach ($data['users'] as $user) {
if (is_array($user) && is_string($user['username'] ?? null) && is_string($user['password'] ?? null)) {
$role = $user['role'] ?? null;
$users[] = [
'username' => $user['username'],
'password' => $user['password'],
'role' => is_string($role) && self::isValidRole($role) ? $role : 'user',
'createdAt' => is_string($user['createdAt'] ?? null) ? $user['createdAt'] : '',
];
}
}
return $users;
}
/** @param list<array{username:string,password:string,role:string,createdAt:string}> $users */
private function write(array $users): void
{
usort($users, static fn(array $a, array $b): int => strcmp($a['username'], $b['username']));
$dir = dirname($this->file);
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
throw new RuntimeException("Cannot create data directory {$dir}");
}
$json = json_encode(['users' => $users], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
if ($json === false) {
throw new RuntimeException('Cannot encode users');
}
AtomicFile::write($this->file, $json, AtomicFile::HIDDEN, 'users file');
}
}