Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .ai/rules/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@ paths:

## The Discord callback has one order of outcomes, and an unverified email never links
`SignInWithDiscord::handle()` decides in this order and no other: a `social_accounts` row for the Discord id signs that user in; a signed-in user (linking from the profile) gets the row; a user whose email matches is linked and signed in only when Discord's raw payload says `verified: true`, else refused with the notice to log in with the password and link from the profile; otherwise a new user with a random 40-character password. An unverified email linking to an existing account is the account-takeover path, so the check is defensive: no raw payload reads as unverified. Only `identify` and `email` scopes; never guilds. The avatar is kept only from `https://cdn.discordapp.com/`. Both routes 404 while `services.discord.client_id` or `client_secret` is empty, and `DiscordAuthController::isConfigured()` is the one place that asks. `social_accounts` is a person table like `users`: never exported. Tests swap `Socialite::driver('discord')` for a mock whose `user()` returns a `Laravel\Socialite\Two\User` with `setRaw([... 'verified' => ...])`; re-mocking the facade in one test does not work, so one outcome per test.

## Every way to make an account asks RegistrationGate, and nothing else
Registration is invite only by default (config registration.mode, env DEMGEM_REGISTRATION). Support\Auth\RegistrationGate::allows() is the one place that reads the mode, the session token (registration.invite, written by the invite page for guests, cleared on accept) and the users table (the first user is the exception). Fortify's register view, CreateNewUser, and SignInWithDiscord's step 4 all ask it; a new door to an account must ask it too. The gate looks the token up on every call rather than remembering a flag, so a revoked invite closes the door with it.
5 changes: 5 additions & 0 deletions .env.docker.example
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,10 @@ DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
DISCORD_REDIRECT_URI="${APP_URL}/auth/discord/callback"

# Who may make an account. "invite", the default, opens the register page to
# whoever holds an invite link, plus the first person on an install with no users.
# "open" is a public register page.
DEMGEM_REGISTRATION=invite

# One ceiling on a campaign's files, in megabytes: cover, images, handout files. 0 turns it off.
CAMPAIGN_STORAGE_MB=500
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -85,5 +85,10 @@ DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
DISCORD_REDIRECT_URI="${APP_URL}/auth/discord/callback"

# Who may make an account. "invite", the default, opens the register page to
# whoever holds an invite link, plus the first person on an install with no users.
# "open" is a public register page.
DEMGEM_REGISTRATION=invite

# One ceiling on a campaign's files, in megabytes: cover, images, handout files. 0 turns it off.
CAMPAIGN_STORAGE_MB=500
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ Slice 26 adds **family trees**. A relationship may carry a kinship, parent, chil

Slice 27 adds **the 5e character sheet**, as a ruleset module. On a campaign on the SRD 5.2.1 rules a character's page carries a sheet: six ability scores, saving throw and skill proficiencies with expertise, hit points and hit dice, spell slots, armour class and speed, with every modifier, the proficiency bonus, every save and skill bonus, passive Perception and initiative computed from the scores and the level on every read and never stored. The character's player or a GM edits it, takes damage and healing on it, and presses "Long rest"; whoever may read the character reads it, and the party's pack from the ledger sits under it. The sheet lives in its own table behind `Ruleset::hasCharacterSheet()`, so a system-agnostic campaign never sees it, and it travels nested under its character in the export, the vault, and the API.

Slice 28 adds **invite-only registration**. The register page takes two people: whoever holds a valid invite link, and the first person to reach an install that has no users yet. Everyone else gets a closed door that says to ask their GM for a link, and the login page stops offering to make an account. An invite link is now the front door for a guest: it shows the campaign and the role, offers "Create an account" and "Log in", and both land back on the invite with a Join button. "Continue with Discord" for someone nobody has seen goes through the same gate. `DEMGEM_REGISTRATION=open` restores a public register page.

Your creatures travel in your export with the prose you wrote. A shipped creature never does — it is named in the file and nothing more, exactly as before. The CC BY notice follows the words rather than the table: a creature you wrote carries none, and a copy of a shipped one keeps the source and licence it came from, so the credit travels with the text.

## Local setup
Expand Down Expand Up @@ -105,7 +107,7 @@ docker compose run --rm --no-deps app php artisan key:generate --show
docker compose up -d
```

Open <http://localhost:8000> and register. The first account is an ordinary account: demgem has no instance administrator and does not need one.
Open <http://localhost:8000> and register. The first account is an ordinary account: demgem has no instance administrator and does not need one. It is also the only account the register page takes on its own; after it, every account arrives through an invite link, unless `DEMGEM_REGISTRATION=open`.

| Service | What it does |
|---|---|
Expand Down
12 changes: 9 additions & 3 deletions app/Actions/Auth/SignInWithDiscord.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,23 @@
* 3. A user with this email: linked and signed in, when Discord says the email is
* verified. Refused otherwise, because an unverified email is how an account is
* taken over.
* 4. Nobody: a new user, with a random password they never see.
* 4. Nobody: a new user, with a random password they never see. That is a
* registration, so it happens only when the caller says the register page
* would have taken this person too.
*/
class SignInWithDiscord
{
public const PROVIDER = SocialAccount::DISCORD;

public function handle(ProviderUser $discord, ?User $current = null): User
public function handle(ProviderUser $discord, ?User $current = null, bool $mayRegister = true): User
{
$providerId = (string) $discord->getId();

if ($providerId === '') {
throw new DiscordSignInRefused('Discord did not say who you are. Try again.');
}

return DB::transaction(function () use ($discord, $providerId, $current): User {
return DB::transaction(function () use ($discord, $providerId, $current, $mayRegister): User {
$linked = SocialAccount::query()
->where('provider', self::PROVIDER)
->where('provider_id', $providerId)
Expand Down Expand Up @@ -69,6 +71,10 @@ public function handle(ProviderUser $discord, ?User $current = null): User
return $existing;
}

if (! $mayRegister) {
throw new DiscordSignInRefused('demgem is invite only. Open the invite link your GM sent you, then continue with Discord from there.');
}

$user = User::create([
'name' => $this->nameFrom($discord),
'email' => $email,
Expand Down
12 changes: 12 additions & 0 deletions app/Actions/Fortify/CreateNewUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace App\Actions\Fortify;

use App\Models\User;
use App\Support\Auth\RegistrationGate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Expand All @@ -13,15 +15,25 @@ class CreateNewUser implements CreatesNewUsers
{
use PasswordValidationRules;

public function __construct(
private RegistrationGate $gate,
private Request $request,
) {}

/**
* Validate and create a newly registered user.
*
* A POST with no pending invite on an invite-only install is a script, not a
* form: a bare 403 and no row, the same answer the register page gave.
*
* @param array<string, string> $input
*
* @throws ValidationException
*/
public function create(array $input): User
{
abort_unless($this->gate->allows($this->request), 403, 'demgem is invite only.');

Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => [
Expand Down
5 changes: 3 additions & 2 deletions app/Http/Controllers/Auth/DiscordAuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use App\Actions\Auth\SignInWithDiscord;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Support\Auth\RegistrationGate;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
Expand Down Expand Up @@ -35,7 +36,7 @@ public function redirect(): RedirectResponse
return $driver->scopes(['identify', 'email'])->redirect();
}

public function callback(Request $request, SignInWithDiscord $signIn): RedirectResponse
public function callback(Request $request, SignInWithDiscord $signIn, RegistrationGate $gate): RedirectResponse
{
abort_unless(self::isConfigured(), 404);

Expand All @@ -54,7 +55,7 @@ public function callback(Request $request, SignInWithDiscord $signIn): RedirectR
$current = Auth::user();

try {
$user = $signIn->handle($discord, $current);
$user = $signIn->handle($discord, $current, mayRegister: $gate->allows($request));
} catch (DiscordSignInRefused $refused) {
return $current !== null
? redirect()->route('profile.edit')->with('status', $refused->getMessage())
Expand Down
16 changes: 14 additions & 2 deletions app/Http/Controllers/InviteController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,47 @@
use App\Actions\Invites\AcceptInvite;
use App\Exceptions\InvalidInviteException;
use App\Models\CampaignInvite;
use App\Support\Auth\RegistrationGate;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class InviteController extends Controller
{
public function show(Request $request, string $token): View|Response
/**
* Open to guests: the token in the URL is the credential. A guest is shown the
* campaign and the role, and the session remembers the invite so that register,
* login, and Discord all land back here.
*/
public function show(Request $request, string $token, RegistrationGate $gate): View|Response
{
$invite = CampaignInvite::findByToken($token);

if ($invite === null || ! $invite->isValid()) {
return $this->invalid();
}

if ($request->user() === null) {
$gate->remember($request, $invite);
}

return view('invites.show', [
'invite' => $invite,
'membership' => $invite->campaign->memberFor($request->user()),
]);
}

public function accept(Request $request, string $token, AcceptInvite $acceptInvite): RedirectResponse|Response
public function accept(Request $request, string $token, AcceptInvite $acceptInvite, RegistrationGate $gate): RedirectResponse|Response
{
$invite = CampaignInvite::findByToken($token);

if ($invite === null || ! $invite->isValid()) {
return $this->invalid();
}

$gate->forget($request);

$campaign = $invite->campaign;

if ($campaign->memberFor($request->user()) !== null) {
Expand Down
11 changes: 10 additions & 1 deletion app/Providers/FortifyServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Actions\Fortify\UpdateUserPassword;
use App\Actions\Fortify\UpdateUserProfileInformation;
use App\Http\Responses\RegisterResponse;
use App\Support\Auth\RegistrationGate;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
Expand All @@ -30,7 +31,15 @@ public function boot(): void
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);

Fortify::loginView(fn () => view('auth.login'));
Fortify::registerView(fn () => view('auth.register'));
Fortify::registerView(function (Request $request) {
$gate = app(RegistrationGate::class);

if (! $gate->allows($request)) {
return response()->view('auth.register-closed', [], 403);
}

return view('auth.register', ['invite' => $gate->pendingInvite($request)]);
});
Fortify::requestPasswordResetLinkView(fn () => view('auth.forgot-password'));
Fortify::resetPasswordView(fn (Request $request) => view('auth.reset-password', ['request' => $request]));

Expand Down
71 changes: 71 additions & 0 deletions app/Support/Auth/RegistrationGate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

namespace App\Support\Auth;

use App\Models\CampaignInvite;
use App\Models\User;
use Illuminate\Http\Request;

/**
* May this request make an account?
*
* Mode "open" says yes to everyone. Mode "invite", the default, says yes to a
* session that holds a valid invite token, and to the first person to reach an
* install with no users, who is about to make the first campaign. The invite page
* writes the token for a guest; nothing else does. The token is looked up on every
* ask rather than remembered as a flag, so an invite revoked between the tap and
* the form closes the door with it.
*
* Fortify's register view, CreateNewUser, and the Discord sign-in all ask here and
* nowhere else.
*/
final class RegistrationGate
{
public const SESSION_KEY = 'registration.invite';

public function isInviteOnly(): bool
{
return config('registration.mode') !== 'open';
}

public function allows(Request $request): bool
{
if (! $this->isInviteOnly()) {
return true;
}

if ($this->pendingInvite($request) !== null) {
return true;
}

return ! User::query()->exists();
}

public function pendingInvite(Request $request): ?CampaignInvite
{
$token = $request->session()->get(self::SESSION_KEY);

if (! is_string($token) || $token === '') {
return null;
}

$invite = CampaignInvite::findByToken($token);

return $invite !== null && $invite->isValid() ? $invite : null;
}

/**
* A guest opened an invite. Every door they take next, register, login, or
* Discord, redirects to the intended URL, so the invite is that URL.
*/
public function remember(Request $request, CampaignInvite $invite): void
{
$request->session()->put(self::SESSION_KEY, $invite->token);
$request->session()->put('url.intended', $invite->url());
}

public function forget(Request $request): void
{
$request->session()->forget(self::SESSION_KEY);
}
}
19 changes: 19 additions & 0 deletions config/registration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

return [

/*
|--------------------------------------------------------------------------
| Who may make an account
|--------------------------------------------------------------------------
|
| "invite", the default, opens the register page to two people only: whoever
| holds a valid invite link, and the first person to reach an install that
| has no users yet. "open" is a public register page. Anything else reads as
| "invite". Support\Auth\RegistrationGate is the one place that asks.
|
*/

'mode' => env('DEMGEM_REGISTRATION', 'invite'),

];
Loading
Loading