From 7da881bb788516b036fa2ea3db983f4520b1a2f2 Mon Sep 17 00:00:00 2001 From: Aneurin Barker Snook Date: Fri, 4 Sep 2026 18:19:48 +0100 Subject: [PATCH] Add a config toggle to turn off new user registration APP_ALLOW_REGISTRATION (default true) gates the only "sign up" this app has -- the account-creation side effect of POST /api/auth/magic-link. When false, an unknown address is silently ignored (find-only, no findOrCreateByEmail) while an existing address still gets its sign-in link as normal; the response is identical either way (202, same message), so there's still no enumeration signal. - Config::allowRegistration, read from APP_ALLOW_REGISTRATION. - AuthController::requestLoginLink takes the flag; only looks up (doesn't create) when it's off. - docker-compose.yml / .env.example / README document the new var. - ApiTestCase::reconfigure() rebuilds the app against changed env (same database) for tests that need a non-default Config; two new AuthTest cases cover both halves (blocks a new address, doesn't block an existing one). 59 tests pass. Verified against the rebuilt container: with the flag on (default), a new address gets a link and an account; switched off via the same env var, a brand-new address gets the same 202 but no email and no user row, while an address that already had an account still receives its link. Co-Authored-By: Claude Sonnet 5 --- .env.example | 5 +++++ README.md | 8 +++++-- docker-compose.yml | 3 +++ src/Http/Controllers/AuthController.php | 18 ++++++++++------ src/Support/Config.php | 5 ++++- src/bootstrap.php | 2 +- tests/ApiTestCase.php | 12 +++++++++++ tests/AuthTest.php | 28 +++++++++++++++++++++++++ 8 files changed, 71 insertions(+), 10 deletions(-) diff --git a/.env.example b/.env.example index 0081d58..82c9e54 100644 --- a/.env.example +++ b/.env.example @@ -19,6 +19,11 @@ JWT_SECRET= # How long an issued token stays valid, in seconds (default: 86400 = 24h). JWT_TTL=86400 +# When false, POST /api/auth/magic-link only signs existing users in -- an +# unknown address is silently ignored (same response either way) rather than +# creating a new account. Closes sign-ups without touching existing users. +APP_ALLOW_REGISTRATION=true + # Base URL the app is reached at. Verification magic links point here, e.g. # /verify-email?token=... The Docker image serves the SPA and the API # together on http://localhost:8080; a host `npm run dev` serves it on :5173. diff --git a/README.md b/README.md index 2a103a9..a8818d2 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,7 @@ environment). See [.env.example](.env.example). | `DATABASE_PATH` | `storage/database.sqlite` | SQLite file location | | `JWT_SECRET` | auto-generated into `storage/secret.key` | Token signing key | | `JWT_TTL` | `86400` | Token lifetime in seconds | +| `APP_ALLOW_REGISTRATION` | `true` | When `false`, a magic link is only ever sent to an existing address — an unknown one is silently ignored, so no new accounts get created | | `APP_URL` | `http://localhost:8080` | Base URL used to build magic links (`http://localhost:5173` for a host `npm run dev`) | | `MAIL_TRANSPORT` | `mail` | `mail` (PHP `mail()`), `smtp`, or `log` (append to a file) | | `MAIL_FROM` / `MAIL_FROM_NAME` | `no-reply@todo.test` / `Projects` | Envelope sender | @@ -156,8 +157,11 @@ Request: `{ "email": "ada@example.com" }`. Emails a one-time sign-in link (`/verify-email?token=…`, 15-minute expiry) and always returns `202` with the same message. If the address has no account yet, one is created (unverified) right here — that's the only "sign -up" there is. A link is only actually (re-)sent if this address hasn't been -emailed one in the last 60 seconds. `422` if the address is malformed. +up" there is — unless `APP_ALLOW_REGISTRATION=false`, in which case an unknown +address is silently ignored (still `202`, nothing sent) and only an address +that already has an account can sign in. A link is only actually (re-)sent if +this address hasn't been emailed one in the last 60 seconds. `422` if the +address is malformed. ```json { "message": "Check your email for a link to sign in." } diff --git a/docker-compose.yml b/docker-compose.yml index 178aaed..7225547 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -14,6 +14,9 @@ services: # Leave blank to auto-generate a secret into the storage volume on first run. JWT_SECRET: "${JWT_SECRET:-}" JWT_TTL: "${JWT_TTL:-86400}" + # Set to false to stop new accounts being created (existing users can + # still sign in). + APP_ALLOW_REGISTRATION: "${APP_ALLOW_REGISTRATION:-true}" # The SPA and the API are both served from this container. APP_URL: "${APP_URL:-http://localhost:8080}" # Deliver to the Mailpit catcher below; read mail at http://localhost:8025. diff --git a/src/Http/Controllers/AuthController.php b/src/Http/Controllers/AuthController.php index dee5bdb..3a85f28 100644 --- a/src/Http/Controllers/AuthController.php +++ b/src/Http/Controllers/AuthController.php @@ -25,6 +25,7 @@ final class AuthController extends Controller private readonly UserRepository $users, private readonly SessionPayload $session, private readonly EmailVerifier $verifier, + private readonly bool $allowRegistration, ) { } @@ -32,10 +33,13 @@ final class AuthController extends Controller * POST /api/auth/magic-link (public) * * Emails a one-time sign-in link for the given address, creating the - * account first if it doesn't exist yet. Always responds the same way; a - * link is only actually (re-)sent when one hasn't gone out in the last - * minute. Opening the link creates the session and, the first time, marks - * the address verified. + * account first if it doesn't exist yet -- unless registration is turned + * off (APP_ALLOW_REGISTRATION=false), in which case an unknown address is + * silently ignored and only existing users can still sign in. Always + * responds the same way either way, so registered addresses can't be + * enumerated. A link is only actually (re-)sent when one hasn't gone out + * in the last minute. Opening the link creates the session and, the first + * time, marks the address verified. */ public function requestLoginLink(Request $request, Response $response): Response { @@ -46,9 +50,11 @@ final class AuthController extends Controller throw new ValidationException(['email' => ['Enter a valid email address.']]); } - $user = $this->users->findOrCreateByEmail($email); + $user = $this->allowRegistration + ? $this->users->findOrCreateByEmail($email) + : $this->users->findByEmail($email); - if (!$this->recentlyEmailed($user)) { + if ($user !== null && !$this->recentlyEmailed($user)) { try { $this->verifier->sendLoginLink($user); } catch (MailException $e) { diff --git a/src/Support/Config.php b/src/Support/Config.php index a61b8f8..c5e986a 100644 --- a/src/Support/Config.php +++ b/src/Support/Config.php @@ -15,6 +15,8 @@ final class Config public readonly string $jwtSecret, public readonly int $jwtTtl, public readonly bool $displayErrors, + /** When false, POST /auth/magic-link only signs existing users in -- it never creates a new account. */ + public readonly bool $allowRegistration, /** Base URL of the frontend, used to build magic links. */ public readonly string $appUrl, public readonly MailConfig $mail, @@ -40,6 +42,7 @@ final class Config $jwtSecret = self::env('JWT_SECRET') ?? self::resolveSecret($storagePath . '/secret.key'); $jwtTtl = (int) (self::env('JWT_TTL') ?? '86400'); $displayErrors = filter_var(self::env('APP_DEBUG', 'false'), FILTER_VALIDATE_BOOL); + $allowRegistration = filter_var(self::env('APP_ALLOW_REGISTRATION', 'true'), FILTER_VALIDATE_BOOL); $appUrl = rtrim(self::env('APP_URL', 'http://localhost:5173'), '/'); @@ -60,7 +63,7 @@ final class Config smtpEncryption: strtolower(self::env('MAIL_SMTP_ENCRYPTION', 'tls')), ); - return new self($databasePath, $jwtSecret, $jwtTtl, $displayErrors, $appUrl, $mail); + return new self($databasePath, $jwtSecret, $jwtTtl, $displayErrors, $allowRegistration, $appUrl, $mail); } private static function env(string $key, ?string $default = null): ?string diff --git a/src/bootstrap.php b/src/bootstrap.php index 23d0c5f..ad0ffd3 100644 --- a/src/bootstrap.php +++ b/src/bootstrap.php @@ -56,7 +56,7 @@ $mailer = $config->mail->transport === 'log' : new PhpMailerMailer($config->mail); $verifier = new EmailVerifier($verificationTokens, $users, $mailer, $config->appUrl); -$authController = new AuthController($users, $session, $verifier); +$authController = new AuthController($users, $session, $verifier, $config->allowRegistration); $emailController = new EmailVerificationController($users, $verificationTokens, $verifier, $session); $projectController = new ProjectController($projects, $cardStatuses); $cardController = new CardController($projects, $cards, $cardStatuses); diff --git a/tests/ApiTestCase.php b/tests/ApiTestCase.php index 3017d6c..5e81c67 100644 --- a/tests/ApiTestCase.php +++ b/tests/ApiTestCase.php @@ -70,6 +70,18 @@ abstract class ApiTestCase extends TestCase } } + /** + * Change config env vars and rebuild the app against them (same database). + * For settings Config::load() only reads once at boot, e.g. APP_ALLOW_REGISTRATION. + * + * @param array $vars + */ + protected function reconfigure(array $vars): void + { + $this->setEnv($vars); + $this->app = require dirname(__DIR__) . '/src/bootstrap.php'; + } + /** A connection to the test database, for seeding rows directly. */ protected function db(): PDO { diff --git a/tests/AuthTest.php b/tests/AuthTest.php index 341a59d..b6d79d9 100644 --- a/tests/AuthTest.php +++ b/tests/AuthTest.php @@ -79,4 +79,32 @@ final class AuthTest extends ApiTestCase self::assertSame(200, $response->getStatusCode()); self::assertSame('linus@example.com', $this->decode($response)['user']['email']); } + + public function test_registration_can_be_turned_off_for_a_new_address(): void + { + $this->reconfigure(['APP_ALLOW_REGISTRATION' => 'false']); + + $response = $this->request('POST', '/api/auth/magic-link', ['email' => 'nobody@example.com']); + + // Same response either way -- no enumeration signal. + self::assertSame(202, $response->getStatusCode()); + self::assertSame([], $this->sentEmails()); + self::assertSame(0, (int) $this->db()->query('SELECT COUNT(*) FROM users')->fetchColumn()); + } + + public function test_turning_off_registration_does_not_block_an_existing_user(): void + { + // Sign up while registration is still open. + $this->request('POST', '/api/auth/magic-link', ['email' => 'ada@example.com']); + $this->request('POST', '/api/auth/verify-email', ['token' => $this->tokenFromEmail()]); + $this->db()->prepare('UPDATE users SET verification_email_sent_at = NULL WHERE email = :e') + ->execute(['e' => 'ada@example.com']); + + $this->reconfigure(['APP_ALLOW_REGISTRATION' => 'false']); + + $response = $this->request('POST', '/api/auth/magic-link', ['email' => 'ada@example.com']); + + self::assertSame(202, $response->getStatusCode()); + self::assertSame('ada@example.com', $this->lastEmail()['to']); + } }