Files
feuerwerk/api/lib/OriginalName.php
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

93 lines
3.8 KiB
PHP
Raw Permalink 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 name a file had when it was uploaded, kept beside it as `{file}.json`.
*
* A stored file is named after the hash of its bytes, which says nothing to a human: the image
* picker could only caption a file it already knew as an asset, and a picked one became "Texture 2".
* The sidecar gives every file a caption and every asset made from it a sensible name.
*
* It is deliberately not part of the file itself and never authoritative: a missing, unreadable or
* empty sidecar simply means "no name known", which is what every file uploaded before this
* existed looks like.
*
* **The last upload wins** (user's decision 2026-09-13): re-uploading the same bytes under a new
* name renames what the picker shows. An upload that carries no name at all (a pasted image has
* none) leaves an existing sidecar alone rather than erasing it.
*/
final class OriginalName
{
/** Long enough for any real file name; the cap is against a crafted one, not against users. */
private const MAX_LENGTH = 120;
/**
* The name as it is safe to store: no path, no control characters, valid UTF-8, bounded.
* Returns '' for anything that is left with nothing – the caller then stores no sidecar.
*/
public static function sanitize(string $raw): string
{
// Checked first: the /u flag below makes preg_replace return null on invalid bytes, which
// would turn "bad encoding" into "empty" by accident rather than on purpose.
if (!mb_check_encoding($raw, 'UTF-8')) {
return '';
}
// A Windows client sends backslashes, which basename() does not treat as separators here.
$name = basename(str_replace('\\', '/', $raw));
$name = trim((string) preg_replace('/[\x00-\x1F\x7F]/u', '', $name));
if ($name === '' || $name === '.' || $name === '..') {
return '';
}
return mb_strlen($name) > self::MAX_LENGTH ? mb_substr($name, 0, self::MAX_LENGTH) : $name;
}
/**
* The stored name, or '' when nothing is known about this file – which is the normal case for
* everything uploaded before sidecars existed.
*
* The absence is checked rather than suppressed with `@`: index.php installs an error handler
* that turns every warning into an exception, and it does not consult `error_reporting()`, so
* `@` does not silence it. A missing sidecar would otherwise fail the whole listing.
*/
public static function read(string $dir, string $file): string
{
$path = $dir . '/' . $file . '.json';
if (!is_file($path)) {
return '';
}
$raw = file_get_contents($path);
if ($raw === false) {
return '';
}
$data = json_decode($raw, true);
return is_array($data) && is_string($data['name'] ?? null) ? self::sanitize($data['name']) : '';
}
/** Writes the sidecar; an empty name writes nothing and removes nothing. */
public static function write(string $dir, string $file, string $name): void
{
$clean = self::sanitize($name);
if ($clean === '') {
return;
}
$json = json_encode(['name' => $clean], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($json === false) {
return;
}
try {
AtomicFile::write($dir . '/' . $file . '.json', $json, AtomicFile::SERVED, 'name file');
} catch (RuntimeException) {
// A nameless file is a small loss; failing the upload over it would be worse.
}
}
/** Removing a file that has no sidecar is the normal case, not a failure. */
public static function delete(string $dir, string $file): void
{
$path = $dir . '/' . $file . '.json';
if (is_file($path)) {
unlink($path);
}
}
}