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>
641 lines
25 KiB
PHP
641 lines
25 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
/**
|
||
* Game Maker API.
|
||
*
|
||
* Routing uses the `r` query parameter (e.g. `index.php?r=projects/abc123`) because the
|
||
* site's nginx configuration does not pass PATH_INFO to PHP.
|
||
*
|
||
* GET ?r=auth/session → {user, role} (both null while nobody is signed in)
|
||
* POST ?r=auth/login {username,password} → {user, role} | 401
|
||
* POST ?r=auth/logout → 204
|
||
* POST ?r=auth/password {currentPassword,newPassword} → 204 | 401 | 422
|
||
* (the only auth route that needs a session; ends the account's
|
||
* other logins, keeps the one asking)
|
||
*
|
||
* Everything below needs a signed-in user (401 otherwise), and projects belong to one: a project
|
||
* of somebody else answers like one that is not there – unless the one asking is an administrator
|
||
* (#179), who reads, saves and deletes it like their own; a save keeps its owner.
|
||
*
|
||
* Administrators only (403 for everybody else, #180):
|
||
*
|
||
* GET ?r=users → [{username,role,createdAt,projects:[{id,name,revision,updatedAt}]}]
|
||
* POST ?r=users {username,password,role} → 201 {username,role,createdAt} | 409 | 422
|
||
* PATCH ?r=users/{name} {username?,role?,password?} → {username,role,createdAt} | 404 | 409 | 422
|
||
* DELETE ?r=users/{name} → 204 | 404 | 409 (still owns projects) | 422
|
||
* (renaming or deleting signs the account out everywhere; a new
|
||
* password ends its other sessions)
|
||
*
|
||
* GET ?r=projects → [{id,name,revision,updatedAt}]
|
||
* POST ?r=projects {name} → {id,name,revision,updatedAt,project}
|
||
* GET ?r=projects/{id} → {id,name,revision,updatedAt,project}
|
||
* PUT ?r=projects/{id} {revision, project} → {revision,updatedAt} | 409 {error,revision}
|
||
* DELETE ?r=projects/{id} → 204 (its snapshots and its release go with it)
|
||
*
|
||
* GET ?r=projects/{id}/snapshots → [{id,name,revision,createdAt}], newest first
|
||
* POST ?r=projects/{id}/snapshots {name?} → 201 {id,name,revision,createdAt}
|
||
* DELETE ?r=projects/{id}/snapshots/{sid} → 204
|
||
* POST ?r=projects/{id}/snapshots/{sid}/restore {revision} → {revision,updatedAt,before} | 409
|
||
* (a snapshot copies the project as stored; restoring keeps the
|
||
* stand it replaces as the snapshot `before`, #231)
|
||
*
|
||
* GET ?r=projects/{id}/release → {token,revision,publishedAt} | null
|
||
* POST ?r=projects/{id}/release → {token,revision,publishedAt} (publishes the stored project)
|
||
* DELETE ?r=projects/{id}/release → 204 | 404
|
||
* (one link per project, kept when publishing again, #266)
|
||
*
|
||
* Released games are the one thing open to everybody, the token being the key:
|
||
*
|
||
* GET ?r=releases/{token} → {name,publishedAt,project} | 404
|
||
*
|
||
* GET ?r=textures → [{file,name,width,height,bytes,updatedAt}]
|
||
* POST ?r=textures&name=x.png raw image bytes → {file,name,width,height,bytes}
|
||
* DELETE ?r=textures/{file} → 204 (administrators only, 403 for everybody else)
|
||
*
|
||
* GET ?r=fonts → [{file,name,bytes,updatedAt}]
|
||
* POST ?r=fonts&name=x.ttf raw font bytes → {file,name,bytes}
|
||
* DELETE ?r=fonts/{file} → 204 (administrators only)
|
||
*
|
||
* GET ?r=sounds → [{file,name,bytes,updatedAt}]
|
||
* POST ?r=sounds&name=x.wav raw sound bytes → {file,name,bytes}
|
||
* DELETE ?r=sounds/{file} → 204 (administrators only)
|
||
*
|
||
* POST ?r=pixels raw cel bytes → {file,bytes} (pixel art, #130)
|
||
*
|
||
* GET ?r=plugins → [{file,bytes,updatedAt}], sorted by file name
|
||
* GET ?r=plugins/{file} → the module source as text/javascript
|
||
*
|
||
* `name` is the file's original name, kept beside it as `{file}.json` (see OriginalName) and
|
||
* empty when none is known. It is a caption, never a path: the stored file is always `{hash}.{ext}`.
|
||
*
|
||
* Stored images, fonts, sounds and cels are served straight from `data/textures/`, `data/fonts/`,
|
||
* `data/sounds/` and `data/pixels/` as static files; the API only writes them.
|
||
*/
|
||
|
||
require __DIR__ . '/lib/AccountRules.php';
|
||
require __DIR__ . '/lib/AtomicFile.php';
|
||
require __DIR__ . '/lib/Auth.php';
|
||
require __DIR__ . '/lib/HashedFileStore.php'; // before the font, sound and texture stores built on it
|
||
require __DIR__ . '/lib/FontStore.php';
|
||
require __DIR__ . '/lib/OriginalName.php';
|
||
require __DIR__ . '/lib/PixelStore.php';
|
||
require __DIR__ . '/lib/PluginStore.php';
|
||
require __DIR__ . '/lib/ReleaseStore.php';
|
||
require __DIR__ . '/lib/Response.php';
|
||
require __DIR__ . '/lib/SessionStore.php';
|
||
require __DIR__ . '/lib/SnapshotStore.php';
|
||
require __DIR__ . '/lib/SoundStore.php';
|
||
require __DIR__ . '/lib/Store.php';
|
||
require __DIR__ . '/lib/TextureStore.php';
|
||
require __DIR__ . '/lib/UserStore.php';
|
||
|
||
/** Has to clear the largest single upload below, which is a sound; the web server has its own say. */
|
||
const MAX_BODY_BYTES = 20 * 1024 * 1024;
|
||
|
||
/** Upload ceiling for a single image. The editor downscales larger pictures before sending. */
|
||
const MAX_TEXTURE_BYTES = 4 * 1024 * 1024;
|
||
|
||
/** Upload ceiling for a single font. A font cannot be shrunk on the way, so this is a plain limit. */
|
||
const MAX_FONT_BYTES = 4 * 1024 * 1024;
|
||
|
||
/** The same for a sound, four times as high: one music track is worth more than four typefaces. */
|
||
const MAX_SOUND_BYTES = 16 * 1024 * 1024;
|
||
|
||
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
|
||
// PHP calls the handler for a call silenced with `@` as well, only with less reported: that
|
||
// warning was expected and is answered where it happens (an unreadable image is a 422).
|
||
if ((error_reporting() & $severity) === 0) {
|
||
return false;
|
||
}
|
||
throw new ErrorException($message, 0, $severity, $file, $line);
|
||
});
|
||
|
||
/** @param list<string> $parts */
|
||
function routeAuth(array $parts, string $method, Auth $auth): never
|
||
{
|
||
$what = $parts[1] ?? '';
|
||
|
||
if ($what === 'session') {
|
||
if ($method !== 'GET') {
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
// Always 200, never 401: "nobody is signed in" is an answer, not a failure, and the
|
||
// login screen asks this before it can know either way.
|
||
$user = $auth->user();
|
||
Response::json(['user' => $user, 'role' => $user === null ? null : $auth->role($user)]);
|
||
}
|
||
|
||
if ($what === 'login') {
|
||
if ($method !== 'POST') {
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
$body = Response::body();
|
||
$user = $auth->logIn((string) ($body['username'] ?? ''), (string) ($body['password'] ?? ''));
|
||
if ($user === null) {
|
||
// One message for both halves: which of the two was wrong is the attacker's question.
|
||
Response::error('Wrong user name or password', 401);
|
||
}
|
||
Response::json(['user' => $user, 'role' => $auth->role($user)]);
|
||
}
|
||
|
||
if ($what === 'password') {
|
||
if ($method !== 'POST') {
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
// The one route under `auth/` that needs a session: it changes the password of whoever is
|
||
// signed in, so there has to be somebody.
|
||
$user = $auth->require();
|
||
$body = Response::body();
|
||
$new = (string) ($body['newPassword'] ?? '');
|
||
if (!UserStore::isValidPassword($new)) {
|
||
Response::error('The new password needs at least ' . UserStore::MIN_PASSWORD_LENGTH . ' characters', 422);
|
||
}
|
||
if (!$auth->changePassword($user, (string) ($body['currentPassword'] ?? ''), $new)) {
|
||
Response::error('Wrong password', 401);
|
||
}
|
||
Response::noContent();
|
||
}
|
||
|
||
if ($what === 'logout') {
|
||
if ($method !== 'POST') {
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
$auth->logOut();
|
||
Response::noContent();
|
||
}
|
||
|
||
Response::error('Not found', 404);
|
||
}
|
||
|
||
/** @param list<string> $parts */
|
||
function routeProjects(array $parts, string $method, string $owner, bool $seesAll): never
|
||
{
|
||
$store = new Store(dirname(__DIR__) . '/data/projects', $owner, $seesAll);
|
||
|
||
if (count($parts) === 1) {
|
||
if ($method === 'GET') {
|
||
Response::json($store->list());
|
||
}
|
||
if ($method === 'POST') {
|
||
$body = Response::body();
|
||
$name = trim((string) ($body['name'] ?? ''));
|
||
if ($name === '' || mb_strlen($name) > 120) {
|
||
Response::error('Project name must be 1–120 characters', 422);
|
||
}
|
||
Response::json($store->create($name), 201);
|
||
}
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
|
||
$id = $parts[1];
|
||
if (!Store::isValidId($id)) {
|
||
Response::error('Invalid project id', 400);
|
||
}
|
||
|
||
$snapshots = new SnapshotStore(dirname(__DIR__) . '/data/snapshots');
|
||
if (($parts[2] ?? null) === 'snapshots') {
|
||
routeSnapshots($parts, $method, $store, $snapshots, $id);
|
||
}
|
||
$releases = new ReleaseStore(dirname(__DIR__) . '/data/releases');
|
||
if (($parts[2] ?? null) === 'release' && count($parts) === 3) {
|
||
routeRelease($method, $store, $releases, $id);
|
||
}
|
||
if (count($parts) > 2) {
|
||
Response::error('Not found', 404);
|
||
}
|
||
|
||
if ($method === 'GET') {
|
||
$doc = $store->load($id);
|
||
if ($doc === null) {
|
||
Response::error('Project not found', 404);
|
||
}
|
||
Response::json($doc);
|
||
}
|
||
|
||
if ($method === 'PUT') {
|
||
$body = Response::body();
|
||
if (!isset($body['revision']) || !is_int($body['revision']) || !is_array($body['project'] ?? null)) {
|
||
Response::error('Body must contain integer "revision" and object "project"', 422);
|
||
}
|
||
try {
|
||
$result = $store->save($id, $body['revision'], $body['project']);
|
||
} catch (StaleRevisionException $e) {
|
||
Response::error('Project was modified elsewhere', 409, ['revision' => $e->currentRevision]);
|
||
}
|
||
if ($result === null) {
|
||
Response::error('Project not found', 404);
|
||
}
|
||
Response::json(['revision' => $result['revision'], 'updatedAt' => $result['updatedAt']]);
|
||
}
|
||
|
||
if ($method === 'DELETE') {
|
||
if (!$store->delete($id)) {
|
||
Response::error('Project not found', 404);
|
||
}
|
||
$snapshots->deleteAll($id);
|
||
$releases->takeDown($id);
|
||
Response::noContent();
|
||
}
|
||
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
|
||
/**
|
||
* The snapshots of one project (#231). Whoever may load the project may see, make, restore and
|
||
* delete its snapshots; for everybody else the project, and with it this route, is not there.
|
||
*
|
||
* @param list<string> $parts
|
||
*/
|
||
function routeSnapshots(array $parts, string $method, Store $store, SnapshotStore $snapshots, string $id): never
|
||
{
|
||
$doc = $store->load($id);
|
||
if ($doc === null) {
|
||
Response::error('Project not found', 404);
|
||
}
|
||
|
||
if (count($parts) === 3) {
|
||
if ($method === 'GET') {
|
||
Response::json($snapshots->list($id));
|
||
}
|
||
if ($method === 'POST') {
|
||
$name = snapshotName(Response::body());
|
||
Response::json($snapshots->create($id, $doc, $name === '' ? gmdate('Y-m-d H:i') . ' UTC' : $name), 201);
|
||
}
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
|
||
$snapshotId = $parts[3];
|
||
if (!Store::isValidId($snapshotId) || count($parts) > 5) {
|
||
Response::error('Not found', 404);
|
||
}
|
||
$snapshot = $snapshots->load($id, $snapshotId);
|
||
if ($snapshot === null) {
|
||
Response::error('Snapshot not found', 404);
|
||
}
|
||
|
||
if (count($parts) === 4) {
|
||
if ($method !== 'DELETE') {
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
$snapshots->delete($id, $snapshotId);
|
||
Response::noContent();
|
||
}
|
||
|
||
if ($parts[4] !== 'restore') {
|
||
Response::error('Not found', 404);
|
||
}
|
||
if ($method !== 'POST') {
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
$body = Response::body();
|
||
if (!isset($body['revision']) || !is_int($body['revision'])) {
|
||
Response::error('Body must contain integer "revision"', 422);
|
||
}
|
||
// The same guard a save has: a tab that is behind must not throw away what another one saved.
|
||
if ($body['revision'] !== $doc['revision']) {
|
||
Response::error('Project was modified elsewhere', 409, ['revision' => $doc['revision']]);
|
||
}
|
||
// The stand being replaced is kept first, so a restore can itself be taken back.
|
||
$before = $snapshots->create($id, $doc, mb_substr('Before restoring ' . $snapshot['name'], 0, 120));
|
||
try {
|
||
$result = $store->save($id, $doc['revision'], $snapshot['project']);
|
||
} catch (StaleRevisionException $e) {
|
||
$snapshots->delete($id, $before['id']);
|
||
Response::error('Project was modified elsewhere', 409, ['revision' => $e->currentRevision]);
|
||
}
|
||
if ($result === null) {
|
||
$snapshots->delete($id, $before['id']);
|
||
Response::error('Project not found', 404);
|
||
}
|
||
Response::json(['revision' => $result['revision'], 'updatedAt' => $result['updatedAt'], 'before' => $before]);
|
||
}
|
||
|
||
/**
|
||
* The released copy of one project (#266). Whoever may load the project may publish it, update it
|
||
* and take it down; publishing copies the project as stored, not what a tab has not saved yet.
|
||
*/
|
||
function routeRelease(string $method, Store $store, ReleaseStore $releases, string $id): never
|
||
{
|
||
$doc = $store->load($id);
|
||
if ($doc === null) {
|
||
Response::error('Project not found', 404);
|
||
}
|
||
if ($method === 'GET') {
|
||
Response::json($releases->of($id));
|
||
}
|
||
if ($method === 'POST') {
|
||
Response::json($releases->publish($doc));
|
||
}
|
||
if ($method === 'DELETE') {
|
||
if (!$releases->takeDown($id)) {
|
||
Response::error('Project is not released', 404);
|
||
}
|
||
Response::noContent();
|
||
}
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
|
||
/** The one route open without a sign-in: a released game, found by its token. */
|
||
function routeReleases(array $parts, string $method): never
|
||
{
|
||
if ($method !== 'GET' || count($parts) !== 2) {
|
||
Response::error('Not found', 404);
|
||
}
|
||
$release = (new ReleaseStore(dirname(__DIR__) . '/data/releases'))->load($parts[1]);
|
||
if ($release === null) {
|
||
Response::error('Game not found', 404);
|
||
}
|
||
// The copy goes out under the token, not the project's own id: that one is nobody's business.
|
||
$project = ['id' => $release['token']] + $release['project'];
|
||
Response::json(['name' => $release['name'], 'publishedAt' => $release['publishedAt'], 'project' => $project]);
|
||
}
|
||
|
||
function snapshotName(array $body): string
|
||
{
|
||
$name = trim((string) ($body['name'] ?? ''));
|
||
if (mb_strlen($name) > 120) {
|
||
Response::error('Snapshot name must be at most 120 characters', 422);
|
||
}
|
||
return $name;
|
||
}
|
||
|
||
/** @param list<string> $parts */
|
||
function routeUsers(array $parts, string $method, Auth $auth, UserStore $users): never
|
||
{
|
||
$actor = $auth->requireAdmin();
|
||
$projects = new Store(dirname(__DIR__) . '/data/projects', $actor, true);
|
||
$shown = static function (string $name) use ($users): array {
|
||
foreach ($users->accounts() as $account) {
|
||
if (strcasecmp($account['username'], $name) === 0) {
|
||
return $account;
|
||
}
|
||
}
|
||
throw new RuntimeException("Account {$name} vanished");
|
||
};
|
||
|
||
if (count($parts) === 1) {
|
||
if ($method === 'GET') {
|
||
Response::json(array_map(
|
||
static fn(array $a): array => $a + ['projects' => $projects->listOf($a['username'])],
|
||
$users->accounts(),
|
||
));
|
||
}
|
||
if ($method === 'POST') {
|
||
$body = Response::body();
|
||
$name = (string) ($body['username'] ?? '');
|
||
$password = (string) ($body['password'] ?? '');
|
||
$role = (string) ($body['role'] ?? 'user');
|
||
if (!UserStore::isValidName($name)) {
|
||
Response::error('A user name is 2–32 letters, digits, dots, dashes or underscores', 422);
|
||
}
|
||
if (!UserStore::isValidPassword($password)) {
|
||
Response::error('The password needs at least ' . UserStore::MIN_PASSWORD_LENGTH . ' characters', 422);
|
||
}
|
||
if (!UserStore::isValidRole($role)) {
|
||
Response::error('Unknown role', 422);
|
||
}
|
||
if ($users->exists($name)) {
|
||
Response::error("The name {$name} is taken", 409);
|
||
}
|
||
$users->put($name, $password, $role);
|
||
Response::json($shown($name), 201);
|
||
}
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
|
||
$target = $parts[1];
|
||
if (!$users->exists($target)) {
|
||
Response::error('User not found', 404);
|
||
}
|
||
$role = $users->role($target);
|
||
|
||
if ($method === 'PATCH') {
|
||
$body = Response::body();
|
||
$newName = array_key_exists('username', $body) ? (string) $body['username'] : null;
|
||
$newRole = array_key_exists('role', $body) ? (string) $body['role'] : null;
|
||
$password = array_key_exists('password', $body) ? (string) $body['password'] : null;
|
||
// Everything is checked before anything is written: half an edit is worse than none.
|
||
if ($newName !== null && $newName !== $target) {
|
||
$refusal = AccountRules::renameRefusal($actor, $target);
|
||
if ($refusal !== null) {
|
||
Response::error($refusal, 422);
|
||
}
|
||
if (!UserStore::isValidName($newName)) {
|
||
Response::error('A user name is 2–32 letters, digits, dots, dashes or underscores', 422);
|
||
}
|
||
if (strcasecmp($newName, $target) !== 0 && $users->exists($newName)) {
|
||
Response::error("The name {$newName} is taken", 409);
|
||
}
|
||
}
|
||
if ($newRole !== null) {
|
||
if (!UserStore::isValidRole($newRole)) {
|
||
Response::error('Unknown role', 422);
|
||
}
|
||
$refusal = AccountRules::roleRefusal($actor, $target, $role, $newRole, $users->adminCount());
|
||
if ($refusal !== null) {
|
||
Response::error($refusal, 422);
|
||
}
|
||
}
|
||
if ($password !== null && !UserStore::isValidPassword($password)) {
|
||
Response::error('The password needs at least ' . UserStore::MIN_PASSWORD_LENGTH . ' characters', 422);
|
||
}
|
||
|
||
if ($password !== null) {
|
||
$auth->resetPassword($target, $password);
|
||
}
|
||
if ($newRole !== null && $newRole !== $role) {
|
||
$users->setRole($target, $newRole);
|
||
}
|
||
$name = $shown($target)['username'];
|
||
if ($newName !== null && $newName !== $name) {
|
||
$users->rename($name, $newName);
|
||
$projects->transfer($name, $newName);
|
||
$auth->endSessionsOf($name);
|
||
$name = $newName;
|
||
}
|
||
Response::json($shown($name));
|
||
}
|
||
|
||
if ($method === 'DELETE') {
|
||
$refusal = AccountRules::deleteRefusal($actor, $target, $role, $users->adminCount());
|
||
if ($refusal !== null) {
|
||
Response::error($refusal, 422);
|
||
}
|
||
$refusal = AccountRules::ownerRefusal($target, count($projects->listOf($shown($target)['username'])));
|
||
if ($refusal !== null) {
|
||
Response::error($refusal, 409);
|
||
}
|
||
$users->remove($target);
|
||
$auth->endSessionsOf($target);
|
||
Response::noContent();
|
||
}
|
||
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
|
||
/**
|
||
* Images, fonts and sounds: shared between the accounts and stored under the hash of their bytes.
|
||
* Everybody signed in uploads and lists them. Deleting one is for administrators only, because a
|
||
* project of another account may be wearing it – the editor itself never deletes a file.
|
||
*
|
||
* @param list<string> $parts
|
||
* @param class-string<RuntimeException> $invalid what the store throws for bytes it cannot take
|
||
*/
|
||
function routeFiles(
|
||
array $parts,
|
||
string $method,
|
||
Auth $auth,
|
||
HashedFileStore $store,
|
||
int $maxBytes,
|
||
string $noun,
|
||
string $invalid,
|
||
): never {
|
||
if (count($parts) === 1) {
|
||
if ($method === 'GET') {
|
||
Response::json($store->list());
|
||
}
|
||
if ($method === 'POST') {
|
||
$bytes = Response::rawBody();
|
||
if (strlen($bytes) > $maxBytes) {
|
||
Response::error("{$noun} must be at most " . ($maxBytes / 1024 / 1024) . ' MB', 413);
|
||
}
|
||
try {
|
||
Response::json($store->store($bytes, (string) ($_GET['name'] ?? '')), 201);
|
||
} catch (RuntimeException $e) {
|
||
if (!$e instanceof $invalid) {
|
||
throw $e;
|
||
}
|
||
Response::error($e->getMessage(), 422);
|
||
}
|
||
}
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
|
||
if ($method === 'DELETE') {
|
||
$auth->requireAdmin();
|
||
if (!$store->delete($parts[1])) {
|
||
Response::error("{$noun} not found", 404);
|
||
}
|
||
Response::noContent();
|
||
}
|
||
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
|
||
/** @param list<string> $parts */
|
||
function routePixels(array $parts, string $method): never
|
||
{
|
||
if (count($parts) !== 1 || $method !== 'POST') {
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
$store = new PixelStore(dirname(__DIR__) . '/data/pixels');
|
||
$bytes = Response::rawBody();
|
||
if (strlen($bytes) > PixelStore::MAX_BYTES) {
|
||
Response::error('A cel is at most ' . PixelStore::MAX_BYTES . ' bytes', 413);
|
||
}
|
||
try {
|
||
Response::json($store->store($bytes), 201);
|
||
} catch (InvalidPixelsException $e) {
|
||
Response::error($e->getMessage(), 422);
|
||
}
|
||
}
|
||
|
||
/** @param list<string> $parts */
|
||
function routePlugins(array $parts, string $method): never
|
||
{
|
||
$store = new PluginStore(dirname(__DIR__) . '/data/plugins');
|
||
|
||
if (count($parts) === 1) {
|
||
if ($method !== 'GET') {
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
Response::json($store->list());
|
||
}
|
||
|
||
if ($method !== 'GET') {
|
||
Response::error('Method not allowed', 405);
|
||
}
|
||
|
||
$source = $store->read($parts[1]);
|
||
if ($source === null) {
|
||
Response::error('Plugin not found', 404);
|
||
}
|
||
// Every plugin file is handed out: the project says which of them the editor runs (#119),
|
||
// and the server has no way of knowing which project the asking tab has open.
|
||
header('Content-Type: text/javascript; charset=utf-8');
|
||
header('X-Content-Type-Options: nosniff');
|
||
// A replaced file has to be the one the next editor start runs.
|
||
header('Cache-Control: no-cache');
|
||
echo $source;
|
||
exit;
|
||
}
|
||
|
||
try {
|
||
if ((int) ($_SERVER['CONTENT_LENGTH'] ?? 0) > MAX_BODY_BYTES) {
|
||
Response::error('Request body too large', 413);
|
||
}
|
||
|
||
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
|
||
$route = trim((string) ($_GET['r'] ?? ''), '/');
|
||
$parts = $route === '' ? [] : explode('/', $route);
|
||
|
||
// Only a project reaches deeper than two parts: `projects/{id}/snapshots/{snapshotId}/restore`.
|
||
if (count($parts) < 1 || count($parts) > ($parts[0] === 'projects' ? 5 : 2)) {
|
||
Response::error('Not found', 404);
|
||
}
|
||
|
||
$users = new UserStore(dirname(__DIR__) . '/data/users.json');
|
||
$auth = new Auth($users, new SessionStore(dirname(__DIR__) . '/data/sessions'));
|
||
if ($parts[0] === 'auth') {
|
||
routeAuth($parts, $method, $auth);
|
||
}
|
||
if ($parts[0] === 'users') {
|
||
routeUsers($parts, $method, $auth, $users);
|
||
}
|
||
if ($parts[0] === 'releases') {
|
||
routeReleases($parts, $method);
|
||
}
|
||
// Images, fonts, sounds, cels and plugins are shared between accounts; being signed in is still the
|
||
// price of admission, so an uploaded file cannot be dropped in by a stranger.
|
||
$user = $auth->require();
|
||
$data = dirname(__DIR__) . '/data';
|
||
|
||
match ($parts[0]) {
|
||
'projects' => routeProjects($parts, $method, $user, $auth->role($user) === 'admin'),
|
||
'textures' => routeFiles(
|
||
$parts,
|
||
$method,
|
||
$auth,
|
||
new TextureStore("{$data}/textures"),
|
||
MAX_TEXTURE_BYTES,
|
||
'Image',
|
||
InvalidImageException::class,
|
||
),
|
||
'fonts' => routeFiles(
|
||
$parts,
|
||
$method,
|
||
$auth,
|
||
new FontStore("{$data}/fonts"),
|
||
MAX_FONT_BYTES,
|
||
'Font',
|
||
InvalidFontException::class,
|
||
),
|
||
'sounds' => routeFiles(
|
||
$parts,
|
||
$method,
|
||
$auth,
|
||
new SoundStore("{$data}/sounds"),
|
||
MAX_SOUND_BYTES,
|
||
'Sound',
|
||
InvalidSoundException::class,
|
||
),
|
||
'pixels' => routePixels($parts, $method),
|
||
'plugins' => routePlugins($parts, $method),
|
||
default => Response::error('Not found', 404),
|
||
};
|
||
} catch (Throwable $e) {
|
||
error_log('[game-maker api] ' . $e->getMessage());
|
||
Response::error('Internal server error', 500);
|
||
}
|