Security, authentication and access

Handbook · Coverage · Source reference

Authentication answers “who is making this request?” Authorization answers “may this person perform this action?” Pulse uses Laravel Sanctum for identity and Spatie roles/permissions plus explicit policies for access. A frontend button being hidden does not authorize its backend endpoint.

This chapter describes the current core source. Names shown in security settings are not automatically enforced policies. See User for the identity model and Plugins for plugin execution permissions.

Start with the request boundary

Core API routes are in backend/routes/api.php; bootstrap middleware is in backend/bootstrap/app.php.

Boundary Actual behavior
Global IP check CheckIpBan is prepended before requests reach controllers
Public authentication /api/v1 login, register, reset, OAuth and 2FA verification use throttle:10,1
Authenticated core routes auth:sanctum and user.banned
Admin group The authenticated group plus role:admin|moderator
Plugin management and marketplace Additional role:admin in their route groups
Fine-grained user changes UserPolicy checks invoked by user management controller
Forced password change Alias exists; core API groups do not currently attach it
Installer Installation detection and locking have a separate middleware boundary

Read middleware on the exact route. The admin-group comment mentions a license, but the group's actual middleware list is the role check above. Comments are not additional enforcement.

Register and log in

All paths in this table include the /api/v1 prefix.

Method/path Request Success and side effect
POST /register or /auth/register username, email, password, password_confirmation 201 {user, token}; creates identity and Sanctum token
POST /login or /auth/login login, password 200 {user, token} or a 2FA challenge
GET /user Authenticated request Serialized user directly, not {user: ...}
POST /logout or /auth/logout Current bearer token Deletes current access token
POST /logout-all Authenticated request Deletes all personal access tokens
POST /user/change-password See below Updates password and clears force flag

login accepts an email or username. Passwords are checked by PasswordVerifier, which also accepts an imported legacy hash once and replaces it with a bcrypt hash; change-password and the 2FA password confirmations use the same verifier (see Migrating from legacy games). A bad password or banned account raises validation errors, normally HTTP 422. Missing authentication is HTTP 401; role/policy denial is normally 403; excessive public authentication requests are 429.

RegisterRequest requires a unique username and email, strings up to 255 characters, and a confirmed password with at least eight characters. Public registration assigns user only if that role already exists. It never falls back to admin, including demo mode. Registration creates no game-specific stats directly; plugins own their game initialization.

last_active, last_login_at and last_login_ip are written only by CoreEvents::signedIn(), so only for a completed sign-in: a password login without 2FA, a login after /2fa/verify, or OAuth. The password step of a 2FA account no longer writes them, so a timestamp means the sign-in finished.

Example: authenticate a local development client

Run from a terminal with a local account you created during setup. Obtain the backend base URL from setup; $PULSE_API below means that URL plus /api/v1.

curl -X POST "$PULSE_API/login" \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{"login":"your-local-username","password":"your-local-password"}'

Expected: HTTP 200 with user and token, or two_factor_required: true and challenge_token. Keep the token private. A subsequent request uses:

curl "$PULSE_API/user" \
  -H 'Accept: application/json' \
  -H "Authorization: Bearer $PULSE_TOKEN"

Expected: the current user resource. Do not paste real tokens into documentation or issue reports.

Personal tokens and sessions

UserSettingsController exposes authenticated /user/sessions and /user/api-tokens routes.

API Arguments/defaults Return/constraint
GET /user/sessions None sessions and tokens, each limited to the newest 20
GET /user/api-tokens None {data: [...]} with metadata, never existing plain tokens
POST /user/api-tokens name required, max 120; abilities array optional; nullable expires_at date 201 with plain_text_token and token metadata
DELETE /user/api-tokens/{token} Integer token ID {success: bool}; scoped to current user

Creation defaults abilities to ['*'] and expiration to null. The delete endpoint refuses the current token with 422; logout is the route for revoking that credential. Database sessions report isCurrent: false; token metadata compares the actual current access token.

An ability string does not enforce itself. A consuming route must check abilities. Core's general auth:sanctum group is an identity check and does not attach an ability middleware.

The logout controller expects a deletable current access token. Test session-cookie clients separately; do not assume the bearer-token logout implementation covers every Sanctum stateful session behavior.

Password changes and recovery

POST /user/change-password takes new_password, new_password_confirmation, and normally current_password. Passwords require at least eight characters. A force_change: true request skips current-password verification only when the user's force_password_change flag is also true.

ForcePasswordChange::handle() would block other requests with 403 and a force_password_change response flag if attached. Its allowlist includes versioned user info, password change, logout, and the CSRF cookie. Registering the alias alone does not enable this server-wide gate.

Public recovery route Request Behavior
POST /forgot-password email Replaces prior reset token; mails frontend reset URL
POST /validate-reset-token email, token {valid: true} or 400 invalid/expired
POST /reset-password email, token, confirmed password Changes password and deletes used reset token

Recovery uses password_reset_tokens directly, hashes a random 64-character token, and hardcodes a 60-minute expiry. Changing Laravel broker defaults alone does not rewrite this controller's rules. Unknown email returns the generic success message; an existing account without configured mail can return 500. Do not describe this as perfectly indistinguishable account discovery behavior.

Successful reset does not explicitly revoke Sanctum tokens. Successful ordinary password change also does not revoke them. Token revocation is a separate operation.

Two-factor authentication

TwoFactorAuthService uses Google2FA TOTP. Its stored secret and recovery codes are encrypted with the application key.

Authenticated /2fa route Input Result
GET /status None enabled, confirmed_at
POST /setup None Secret, base64 SVG QR image, QR URL; temporary secret in session
POST /confirm Six-character code Enables 2FA after verification; returns recovery codes
POST /disable Current password Clears secret, codes and confirmation timestamp
POST /recovery-codes Current password Current unused codes
POST /regenerate-recovery-codes Current password Replaces stored code collection

Setup and confirmation must share a working session because setup stores 2fa_secret there. A bearer header alone does not establish that continuity. A missing setup session produces 400; an invalid code produces 422.

Login with enabled 2FA returns a random 64-character challenge, cached for five minutes. Public POST /2fa/verify takes challenge_token and code. It allows five unsuccessful attempts per challenge; subsequent attempts receive 429. Invalid/expired challenges receive 403. A valid code deletes the challenge and creates a token, but the current controller then loads ['profile', 'roles']. Core User has no profile() relationship, so the standalone-core response can fail after those side effects. This is a known implementation gap, not a working completion guarantee; see User limitations.

Recovery codes are generated as eight random pairs of ten characters, separated by -. Each successful use removes that code. recovery_codes_count in the settings UI does not change this hardcoded generation count. The service currently passes no custom TOTP verification window.

Service API for trusted backend code

Signature Result/side effect
generateSecretKey(): string New TOTP secret
generateRecoveryCodes(): Collection Eight newly generated codes; no user/database save
getQrCodeUrl(User $user, string $secret): string Provisioning URL
verify(string $secret, string $code): bool TOTP check
enable(User $user, string $secret, string $code): bool Saves encrypted data only after valid code
disable(User $user): void Clears all 2FA fields
isEnabled(User $user): bool Secret and confirmation both present
verifyCodeOrRecovery(User $user, string $code): bool TOTP, then consumes matching recovery code
useRecoveryCode(User $user, string $code): bool Direct recovery-only check; false on mismatch; encrypts/saves remaining codes on success
getRecoveryCodes(User $user): array Decrypted unused codes
regenerateRecoveryCodes(User $user): Collection Saves a replacement collection

Recovery consumption is an atomic once-only claim: useRecoveryCode opens a transaction whose first statement locks the user's row (SELECT ... FOR UPDATE), decides from the codes stored on that locked row rather than the caller's loaded model, and saves the remaining codes before commit. A code that is not stored at all, such as a wrong TOTP code, is refused from a plain read first, without a transaction or lock. On MariaDB and MySQL two concurrent callers with the same code queue on the row lock and only one succeeds; SQLite ignores FOR UPDATE, but its transactions are serializable, so there a second caller either finds the code already gone or fails with a database-busy error instead of waiting, and cannot use the code twice. One use cannot write back a stale list that restores a code another request just used. Direct service calls perform no password/challenge/role authorization themselves.

Decrypt failures can throw in the 2FA service. Preserve APP_KEY across restarts/restores; generating a replacement key is not a recovery step for existing secrets.

OAuth sign-in and account linking

Supported provider names in OAuthService are discord, google, github, facebook (OAuthService::providerNames()). Twitter was dropped in 1.0.2: its Socialite driver was never usable with these routes, and it gives no address the engine could treat as confirmed. A supported name still needs credentials and a working Socialite driver in the installed application.

Public routes are GET /oauth/providers, GET /oauth/{provider}/redirect, GET /oauth/{provider}/callback, and POST /oauth/{provider}/complete. Authenticated routes are GET /oauth/linked, POST /oauth/{provider}/link/start, POST /oauth/{provider}/link (body current_password; first-party browser session only, never a bearer token) and DELETE /oauth/{provider}/unlink (body current_password); link and unlink share throttle:account-password-check, 5 a minute per account.

Linking a provider (since 1.0.3). A signed-in member starts from Account settings: link/start stores a link intent in the session (the hash of the state Socialite just stored, the account, its browser-session version, the provider, ten minutes) and returns the provider URL. The provider sends the browser back to the one callback. A callback whose state is the intent's is a link and never a sign-in: it spends the code at once, parks the identity in the session (encrypted, bound to the account, session version and provider, ten minutes) and redirects to /settings?oauth_link=<provider> (or ?oauth_link_error=cancelled|failed). POST /link checks the current password, then writes the parked identity to that account only (code link_not_started, identity_taken or link_failed on a 400). Any other callback is a sign-in and leaves nothing /link accepts, so a sign-in can never become a link, and a sign-in redirect drops a pending link intent. Since 1.0.4 the confirm form shows which provider account is waiting (GET link/pending: provider, email, name, nickname, for the same session only), an account with two-factor sign-in on also gives its code to POST /link (after the password, only while an identity is waiting), and every link and unlink emails the owner (oauth-linked, oauth-unlinked). The OAuth return codes (oauth_error, oauth_2fa) are read by the player router for whatever page draws /login, a kit's login page included.

A password of its own. users.has_own_password is false for an account an OAuth sign-up made (its stored password is random) and becomes true with any new password (reset, change, admin, console). Such an account cannot pass a current-password check, so link, unlink and the admin re-check (POST /admin/reauth) answer 422 with code: password_not_set, and the player settings and admin re-check pages offer the reset email to set one. GET /api/v1/user shows has_own_password to the account itself only. Rows from before the migration read true.

Registration. OAuth sign-up honours registration_enabled (RegistrationPolicy::open(), shared with RegisterRequest): a new identity is refused with registration_closed (JSON 403) before an account or a Discord pending sign-up is made, and complete refuses a pending sign-up once registration is off. A linked identity still signs in.

getRedirectUrl(string $provider): string validates configuration and returns the provider redirect URL; Socialite keeps the state in the session and checks it on the callback and on link. handleCallback(string $provider): array returns user and is_new, or a Discord pending registration with pending_token. A provider identity that is already linked signs in through its link. A callback never links an identity to an existing account by address (since 1.0.2). A new identity needs an address the provider confirmed (confirmedEmail(): Google email_verified === true plus a Gmail/googlemail address or a non-blank Workspace hd; Discord verified === true; GitHub's primary verified address; Facebook never). Without one the callback answers email_unverified and links or creates nothing, whether or not an account holds the address; a confirmed address that an account already holds answers account_exists. The member signs in to that account and links the provider from there. fetchLinkIdentity(string): array exchanges a link callback's code; linkIdentityTo(User, array): bool attaches the identity to that account only and refuses one another account owns without touching it. New Discord identities are cached for ten minutes, encrypted, so a username can be chosen.

createUserFromPending(array $pending, string $username): User performs identity/provider creation in a transaction. linkProvider(User, string, SocialiteUser): OAuthProvider creates or replaces a user's provider record. unlinkProvider(User, string): array answers UNLINKED, NOT_LINKED or LAST_WAY_IN under the account row lock; it never removes the last offered and configured provider of an account without a password of its own. getLinkedProviders(User): array returns provider metadata without access tokens.

getSupportedProviders(): array returns a reindexed list of configured provider names from that supported set. isProviderConfigured(string $provider): bool checks credentials/enabled settings; it does not validate the provider against the supported set or perform a network probe, and database errors can propagate.

OAuth credentials can come from config/services.php or database settings. A configured environment client ID makes a provider appear configured; database fallback requires a client ID and enabled value '1'. Runtime application of database credentials can override environment credentials when its stored client ID is nonempty. See configuration.

OAuth uses a separate controller flow from password login. Since 1.0.3 the callback refuses a banned account, asks the sign-in gate, and gives an account with 2FA on the same session-bound challenge as a password sign-in before any session exists; review OAuthController before promising other password-login checks.

Roles, permissions and policy

Role management lives under /api/v1/admin/roles, /admin/permissions, and /admin/users/{id}/roles. The route boundary is admin or moderator; the role controller itself does not add an admin-only check. Treat moderator access according to the implemented route, not the page label.

Roles are created with guard_name: sanctum. Role create/update accepts permission names or numeric IDs, filters to existing Sanctum permissions, and synchronizes valid names. Invalid supplied permissions are filtered rather than creating new permissions.

Create/update also accept color (#RRGGBB or null, the player-name colour exposed as name_color on the user resource) and plugin_admin_access (plugin slugs, or ["*"] for every plugin). Writes are admin-only and recorded in the activity log. A holder of a granted role may use that plugin's engine-approved routes/admin.php routes (EnforcePluginAdminBoundary, PluginAdminAccess); core /api/v1/admin routes keep their own boundaries, a grant reaches only controllers whose class file is inside that plugin's directory, a plugin admin route that removes the guard by any means is refused with 403, a banned account gets nothing through a grant, and the admin role always reports ["*"]. The admin SPA still admits only admin and moderator accounts, so a staff member who uses a granted plugin's admin screens also needs the moderator role.

UserPolicy defines:

Action Allowed
List/view Admin or moderator
Create Admin
Update Admin/moderator; never self; moderator cannot update admin
Delete Admin; never self or any admin target
Ban Admin/moderator; never self or admin target

A policy method matters when a controller authorizes it. For a new plugin endpoint attach route middleware and explicitly authorize the target; see recipes. Role names, Sanctum abilities and plugin manifest permissions are three different access systems.

Horizon dashboard access

App\Providers\HorizonServiceProvider defines viewHorizon: outside the local environment, access requires a non-null authenticated user who either has role admin or has email [email protected]. The email branch does not also require the admin role. The installed Horizon provider permits the local environment independently of that gate. Configured web middleware does not by itself establish an admin-only boundary; these are the actual callback conditions.

Review the configured environment, session identity and this gate before exposing /horizon. Core API staff middleware does not automatically apply to that dashboard. Source: application provider, Laravel\Horizon\HorizonApplicationServiceProvider::authorization() in the installed dependency. See queue operation.

Bans and anti-multi review

IpBan::isIpBanned(string $ip): bool checks active records with no expiry or future expiry, then fnmatch wildcard patterns. 192.0.2.* is a pattern; this is not a CIDR parser. Global middleware returns 403 for banned addresses. Protected routes also check User::is_banned and revoke the current token when denying access.

Multi-account detection has its own page: Multi-account detection (what is recorded, the privacy note, how clusters form and how staff act). In short, since 1.0.4: security.anti_multi_record_on_auth (env ANTI_MULTI_RECORD_ON_AUTH, default off) records register and password sign-in, and the player app posts a browser value to POST /api/v1/device-fingerprint (throttle:10,1; off answers 204). Browser values are keyed (HMAC-SHA256, keyedClientFingerprint) before storing; only they link accounts by device, and a hash derived from request headers is address evidence only.

Method Behavior
recordFingerprint(User|int $user, Request $request, ?string $clientFingerprint = null): DeviceFingerprint Stores the device row and the address sighting and evaluates, in one transaction under the anti_multi_locks row
recordFingerprintAfterResponse(...) The same after the response is sent; failures are logged
evaluateUser(int $userId, string $fingerprintHash, string $ip, ?string $source = null): ?MultiAccountCluster Links accounts by browser value (fingerprint_window_days, 30) and address (ip_window_hours, 48, per address); joins or merges open clusters; above max_cluster_size (10) writes a memberless shared_network note
paginateClusters(...), getClusters(...) Severity-ordered clusters with members, shared signals and account_count
applyClusterAction(int $clusterId, string $action, ?string $notes = null, ?User $actor = null, array &$skippedUserIds = [], ?array $memberIds = null): bool Resolves under the cluster row lock; banned bans only device-linked members (confidence 95) that staff chose ($memberIds, or all of them when null), never staff, and returns the others in $skippedUserIds

Severity: address only low, browser value only medium, both with the same account high, high plus money either way between accounts that share both critical. Severity only escalates and a resolved cluster is never reopened. Actions are none, warned, trade_locked, banned; a device-linked (confidence 95) member of a trade_locked cluster cannot send or receive player transfers (isTradeLocked); an address-only member is not locked. Register, password, OAuth and two-factor sign-ins are recorded once they complete (OAuth) or once the password is right (password, before the ban check).

Admin review routes are /admin/anti-multi/clusters (paged), /inspect/{userId} (staff) and /resolve/{clusterId} (admins with a fresh password confirmation, role:admin and admin.recent-auth).

Banned sign-in notice and appeal

When a banned player signs in with the correct password, AuthController::login still answers 422 with the same errors.login message, and adds a ban key from BanAppealService::notice(): reason (the latest ban admin action, read through activity_logs.target_user_id), until (ISO 8601 or null for permanent) and appeal (null unless a plugin opted in). No session and no API token is ever granted. The notice appears only after the password check, so it cannot be used to find out whether an account exists; a wrong password gets the ordinary credentials error.

Core only carries the appeal. A plugin opts in with the auth.banned_login filter (appeal_enabled true) and receives appeals through auth.ban_appeal. The link is /ban-appeal#<token>: 40 characters, stored in the cache only as a SHA-256 hash, valid 30 minutes, one live token per account (a newer banned sign-in replaces it). The token is in the URL fragment, so it stays out of server request and proxy logs; the player app's error reporter also drops the fragment. It is used up only when a plugin accepts the appeal; otherwise the endpoint answers 503 and the link keeps working. For an account with 2FA the notice (and any link) is given only after a correct 2FA code at /api/v1/2fa/verify, never from the password alone. The reason shown is that of the latest ban action; if the account was unbanned since, or the ban wrote no reason row, it is null. Endpoints: ban-appeal lookup and submit.

Managed API keys are a separate model

ApiKey has a generated lcp_ key and 64-character secret. /admin/api-keys manages keys, restrictions, analytics and logs. isValid() checks activation/expiry; isIpAllowed() uses exact IP matching; isDomainAllowed() uses string suffix matching; hasPermission() allows everything for an empty list or *.

These are model helpers. Current core source does not wire these keys into a request-authentication middleware. Rate and daily limits stored on a key do not become general API enforcement automatically. Use Sanctum personal tokens for the documented authenticated API flow. Domain suffix matching is not a DNS ownership or origin verification proof.

License validation and activation

App\Core\Services\LicenseService implements the legacy local LCP-<tier>-<payload>-<signature> format using RSA-SHA256. This is a separate protocol from the marketplace client's Ed25519 package signatures. It is also separate from the engine's AGPL source license. Core has no general paid-license gate; plugin.access consults this service only for plugins whose registry row has license_required enabled.

Consumer methods

These are static methods for trusted backend code. Validation returns an array containing valid and, on failure, error; successful results include payload and expired: false. Revoked/expired results add their respective flag and payload. Declared nullable return types do not mean invalid keys normally return null: the current invalid helper returns an array.

Signature Contract and side effects
validate(string $key): ?array Removes whitespace; checks format, RSA signature, decoded payload, local revocation and expiry. Does not check request domain or plugin entitlement.
validateForDomain(string $key, ?string $domain = null): ?array Runs validation, then matches the supplied domain or request()->getHost(). Exact matches ignore case; * allows all domains; *.example.com matches subdomains, not the bare example.com.
getStoredKey(): ?string Prefers LARAVEL_CP_LICENSE; otherwise reads and trims storage/license_key. A stored file does not override a nonempty environment key.
isLicensed(): bool Checks the stored key with validate(), so true alone does not prove domain or plugin coverage.
getDetails(): array Checks stored key with validateForDomain() and adds a masked key; absent storage yields valid: false.
store(string $key): bool Rejects invalid keys, then writes storage/license_key, attempts local activation recording and sends an outbound activation callback. Uses validate(), not domain validation.
maskKey(string $key): string Keeps the first 12 and last eight characters for strings over 20 characters; shorter strings are returned unchanged. Not a general secret-redaction function.

Example inside a backend method, without storing a key or contacting a remote service:

use App\Core\Services\LicenseService;

$result = LicenseService::validate('example-invalid-key');
$valid = $result['valid'] ?? false; // false
$error = $result['error'] ?? null; // format failure

For real consumer code, use validateForDomain() when the host is part of the contract and independently check the payload's plugins value. The plugin middleware requires 'all' or an array containing the exact plugin slug. It does not enforce max_users or a tier-based feature matrix. The authority HTTP generator accepts plugins as a string; a comma-separated string is not interpreted as an array by the middleware.

Verification keys and storage failures

The verification key is chosen from backend/license_public.pem, then derived from the private-key file named by LCP_LICENSE_PRIVATE_KEY_PATH (default backend/license_private.pem), then the embedded public key. The verifier does not derive its public key from the LCP_LICENSE_PRIVATE_KEY string used by generation. A local test signer therefore needs a matching verification-key source; do not assume supplying an environment private key alone makes generated keys verifiable.

isRevoked() queries the local license_keys table and returns false if that query throws. This is not a remote revocation-list check. Invalid signed payload structure or an unparsable expiry can also cause runtime exceptions beyond the normal invalid-key result; consumers must not assume every malformed input is reduced to valid: false.

store() does not check File::put()'s returned byte count. Local activation queries can throw if their schema is unavailable, and activation refusal does not undo the file write. The callback has a five-second timeout, ignores unsuccessful HTTP statuses and catches exceptions. A true return is therefore not proof of a durable write, accepted remote activation or domain permission. It also does not replace an environment key that still takes precedence.

Signing authority methods and HTTP routes

The following methods belong to the key issuer or integration infrastructure; ordinary plugin installation needs verification, not a distributed private signing key.

Signature Contract
canGenerate(): bool Checks private-key environment presence or private-key-file existence; does not prove it parses successfully.
generate(array $options): ?string Signs an RSA payload, attempts a local LicenseKey record, returns key or null on missing/invalid signing key. Record failure is logged without discarding the key. Options default domain *, tier standard, expiry lifetime, max users 0 and plugins all.
generateKeypair(): ?array Returns a new 2048-bit RSA private_key and public_key in memory; does not install files or rotate a deployment's verifier.
sendActivationCallback(string $key, array $payload): void Sends license ID, request domain/IP and activation time to a hardcoded callback URL, signing JSON with services.license.callback_secret. The key argument is not included in that request body.
recordActivation(string $licenseId, string $domain, string $ip): bool Updates activation fields on a local, non-revoked record; false for missing/revoked record. Does not independently compare the supplied domain with the signed payload.
isRevoked(string $licenseId): bool Local revoked-row existence check; query failure returns false.

All four administrative routes below sit under /api/v1/admin/license, requiring Sanctum authentication, a non-banned user and the admin-or-moderator role boundary. Each controller action also requires canGenerate() and otherwise returns 403. The comment “owner only” does not add a separate role check.

Method/path Request and response
GET /keys Optional status activated/pending/revoked and search; returns a 20-row paginator of local records.
POST /keys Required domain/customer strings max 255, email, tier standard/extended/unlimited, expires string max 20; optional nonnegative integer max_users, string plugins max 500. Returns {success, license_key, message} or 500 generation error; validation normally gives 422.
PUT /keys/{id} Nullable notes max 1,000; updates notes and returns {success, message}; absent row 404.
POST /keys/{id}/revoke Marks local row revoked with timestamp; returns {success, message}; absent row 404.

There is no core status/activate/deactivate HTTP trio for consumers in this route group. Use the service contracts above when implementing an authorized installation workflow.

The separate public POST /api/license/callback verifies X-Signature as HMAC-SHA256 over the exact raw body using services.license.callback_secret. Missing secret/header or mismatch returns 403. It validates license_id (max eight), domain (max 255), and ip (max 45), then returns {success: bool} from recordActivation(). It has no nonce/replay record or independent domain-ownership check. Do not confuse this acknowledgement with signature verification of a downloaded package.

Source: service, controller, plugin middleware and routes. Existing LicenseServiceTest signing cases skip when their private-key fixture is unavailable; a green suite with those skips does not prove the signing/activation workflow.

CORS and debugging

config/cors.php covers api/*, Sanctum CSRF cookie and Livewire paths. CORS_ALLOWED_ORIGINS is a comma-separated list; credentials default false via CORS_SUPPORTS_CREDENTIALS. Allowed headers include Authorization and X-XSRF-TOKEN. A CORS browser error does not mean the token is invalid; inspect preflight and actual response separately.

Symptom Check
401 Bearer header, revoked/expired token, frontend stale token keys
403 before login IP ban and installer state
Admin rejected Actual role and guard, then policy target restrictions
2FA confirm says no setup Same session/cookie across setup and confirm
Recovery mail fails Active EmailSetting, mail template, queue and worker
Security toggle seems ignored Find a runtime consumer; UI defaults alone are not enforcement

Source map and verification limits

Source: backend/routes/api.php, bootstrap/app.php, config/auth.php, config/cors.php, app/Core/Http/Requests/*PasswordRequest.php, LoginRequest.php, RegisterRequest.php; controllers AuthController, Auth/*, UserSettingsController, Admin/RolePermissionController, Admin/AntiMultiController, Admin/ApiKeyController; services TwoFactorAuthService, OAuthService, AntiMultiService; middleware and UserPolicy above.

Related tests: AuthLoginTest, AuthRegistrationTest, AuthSessionTest, CheckIpBanTest, UserSettingsApiTest. This chapter records source behavior; it does not certify an OAuth provider, email transport, production security audit, or live 2FA session deployment. Continue with testing and operations.

ModerationService helpers

Resolve app(App\Core\Services\ModerationService::class) in trusted, authorized backend code. The service does not apply UserPolicy automatically.

Method Returns / effect
banPlayer(User $player, User $admin, array $data): bool Saves is_banned=true and banned_until ($data['until'], a future time; omitted means permanent, and an old expired end date is always replaced), signs the player out of every browser session and API token, logs reason/until/notes and fires user.banned after commit. A past until throws InvalidArgumentException. The admin ban route uses it.
unbanPlayer(User $player, User $admin, string $reason = ''): bool Clears the flag and banned_until, logs reason, fires user.unbanned after commit.
warnPlayer(User $player, User $admin, array $data): bool Logs warning reason/severity, returns true; no persistent warning model is created here.
banIp(string $ip, User $admin, array $data): IpBan Creates active IP ban with optional expires_at; caller must validate input/permission.
unbanIp(IpBan $ipBan): bool Updates is_active=false.
getPlayerModerationHistory(User $player, int $page = 1, int $perPage = 25): array is_banned, banned_until, and one page (at most 100) of staff actions on that player, newest first: entries (id, action, reason, actor {id, username}, at, details), page, per_page, has_more. Reads the indexed activity_logs.target_user_id. Entries made by a staff account that is later deleted stay: the actor foreign key sets user_id to null, and actor becomes {id: null, username: <the name recorded in metadata.actor_username>}.

Use the policy-aware admin endpoints for their defined workflow. Passing an admin object to a service is not itself proof that the authenticated actor is that admin. Source declarations.