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>
121 lines
4.4 KiB
PHP
121 lines
4.4 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
/**
|
||
* Logins, kept as one file per session in `data/sessions/`, named after the SHA-256 of the token
|
||
* the browser holds in its cookie – so the file on disk cannot be replayed as a token.
|
||
*
|
||
* Deliberately not PHP's own session handler: those expire after `session.gc_maxlifetime`
|
||
* (24 minutes by default), and a login here has to outlive a deployment and a night, since
|
||
* `npm run build` replaces the editor under the very tab that is signed in.
|
||
*/
|
||
final class SessionStore
|
||
{
|
||
/** How long a login lasts without being used; every request that finds it pushes it out again. */
|
||
public const LIFETIME_SECONDS = 30 * 24 * 60 * 60;
|
||
|
||
public const COOKIE = 'game_maker_session';
|
||
|
||
public function __construct(private readonly string $dir) {}
|
||
|
||
/** Starts a session for `$username` and returns the token for the cookie. */
|
||
public function create(string $username): string
|
||
{
|
||
$this->sweep();
|
||
$token = bin2hex(random_bytes(32));
|
||
$this->write($token, ['username' => $username, 'createdAt' => time(), 'seenAt' => time()]);
|
||
return $token;
|
||
}
|
||
|
||
/** The user behind a token, or null when it is unknown or has expired. */
|
||
public function user(string $token): ?string
|
||
{
|
||
$path = $this->path($token);
|
||
if ($path === null || !is_file($path)) {
|
||
return null;
|
||
}
|
||
$raw = file_get_contents($path);
|
||
$data = $raw === false ? null : json_decode($raw, true);
|
||
if (!is_array($data) || !is_string($data['username'] ?? null) || !is_int($data['seenAt'] ?? null)) {
|
||
return null;
|
||
}
|
||
if (time() - $data['seenAt'] > self::LIFETIME_SECONDS) {
|
||
@unlink($path);
|
||
return null;
|
||
}
|
||
// Touched at most once an hour: every request rewriting the file would cost a write per
|
||
// autosave, and the lifetime is measured in weeks.
|
||
if (time() - $data['seenAt'] > 3600) {
|
||
$data['seenAt'] = time();
|
||
$this->write($token, $data);
|
||
}
|
||
return $data['username'];
|
||
}
|
||
|
||
public function destroy(string $token): void
|
||
{
|
||
$path = $this->path($token);
|
||
if ($path !== null) {
|
||
@unlink($path);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Ends every login of `$username` but the one behind `$keep` – what a password change does, so
|
||
* that a session started with the old password cannot outlive it. Returns how many were ended.
|
||
*/
|
||
public function destroyAllFor(string $username, string $keep = ''): int
|
||
{
|
||
$keepPath = $keep === '' ? null : $this->path($keep);
|
||
$ended = 0;
|
||
foreach (glob($this->dir . '/*.json') ?: [] as $file) {
|
||
if ($file === $keepPath) {
|
||
continue;
|
||
}
|
||
$raw = file_get_contents($file);
|
||
$data = $raw === false ? null : json_decode($raw, true);
|
||
if (is_array($data) && strcasecmp((string) ($data['username'] ?? ''), $username) === 0) {
|
||
@unlink($file);
|
||
$ended++;
|
||
}
|
||
}
|
||
return $ended;
|
||
}
|
||
|
||
/** Throws out what has timed out, so the directory does not grow with every login. */
|
||
private function sweep(): void
|
||
{
|
||
foreach (glob($this->dir . '/*.json') ?: [] as $file) {
|
||
if (time() - (int) @filemtime($file) > self::LIFETIME_SECONDS) {
|
||
@unlink($file);
|
||
}
|
||
}
|
||
}
|
||
|
||
private function path(string $token): ?string
|
||
{
|
||
if (!preg_match('/^[a-f0-9]{64}$/', $token)) {
|
||
return null;
|
||
}
|
||
return $this->dir . '/' . hash('sha256', $token) . '.json';
|
||
}
|
||
|
||
private function write(string $token, array $data): void
|
||
{
|
||
if (!is_dir($this->dir) && !mkdir($this->dir, 0775, true) && !is_dir($this->dir)) {
|
||
throw new RuntimeException("Cannot create session directory {$this->dir}");
|
||
}
|
||
$path = $this->path($token);
|
||
if ($path === null) {
|
||
throw new RuntimeException('Invalid session token');
|
||
}
|
||
$json = json_encode($data, JSON_UNESCAPED_SLASHES);
|
||
if ($json === false) {
|
||
throw new RuntimeException('Cannot encode session');
|
||
}
|
||
// Replaced rather than rewritten in place: a request reading it meanwhile would find it
|
||
// empty, and an empty session is a signed-out one.
|
||
AtomicFile::write($path, $json, AtomicFile::HIDDEN, 'session file');
|
||
}
|
||
}
|