# Differences From PHP

Source: https://keyringauth.com/docs/0.x/go/differences

## Introduction

Keyring for Go covers most of the PHP package and passes the whole [contract suite](https://github.com/keyringauth/keyring/blob/main/contract/README.md): `contract/bin/run-go` runs every file in it. This page lists everything that isn't the same: what isn't there yet, what works differently because Go or Laravel Go works differently, where the Go port is stricter on purpose, and the Laravel Go API that would let it match the PHP package exactly. Each Go page links here from the sections it affects.

The Go port follows the PHP package wherever the two can agree, and the [Rust crate](https://keyringauth.com/docs/0.x/rust/differences) where PHP doesn't apply. Where it parts from the Rust crate in a way you'd notice coming from Rust, this page says so.

## Not Available Yet

These need something Laravel Go doesn't have (see [What Laravel Go Would Need](https://keyringauth.com/docs/0.x/go/differences#what-laravel-go-would-need)):

- **Laravel's own auth events.** `Login`, `Logout`, `Failed` and `Lockout` aren't dispatched. Keyring dispatches its own `Registered`, `Verified`, `PasswordReset` and `PasswordChanged` in place of Laravel's.
- **Translations.** Laravel Go has no translator or locale, so every message is the PHP package's English one.
- **Argon2 passwords.** Laravel Go's `hash` checks bcrypt alone (`$2y$`, `$2a$` and `$2b$`), so a password a PHP application hashed with Argon2 can't be checked here.
- **Rehashing a password on sign in.** Laravel Go's guard signs a fingerprint of the password hash into every session, so a new hash would sign out the user's other sessions.
- **Sharing sessions with a PHP application.** Session payloads, Laravel's own `sessions` table and the guard's remember cookie are in different formats, so a browser can't move between a Go and a PHP application. Only Keyring's own tables are shared. Each side needs its own `SESSION_TABLE` if both use database sessions.

These have nothing in the way, and aren't done yet:

- **Security keys and attestation.** Only `none` attestation is checked. There's no `packed` or `fido-u2f`, no attestation roots, no AAGUID lists, no `requireAttestation()` or `allowOnly()`, and no second key factor (`WebAuthn::securityKeys()->as(...)`). So no key is ever attested, and nothing reaches AAL3.
- **Four security emails.** `second_factor_failed`, `recovery_code_used`, `account_locked` and `clone_suspected` aren't sent yet. Their log entries and events are there, and `Notifications.Off` takes their names.
- **The activity page** (`activity()` and `unlistedActivityTypes()`), and `recordIpsUsing()`.
- **`Keyring::unlock($user, $factor)`**, which clears one second factor's limits. `Keyring.Unlock` takes the user alone.
- **A code factor's own rate limits**, categories other than possession or address, and a `credential_id` for its row.
- **Bases for an identity provider driver** of your own (the PHP package's OAuth 2.0 and OpenID Connect classes). A driver of your own does the whole flow itself.
- **Second factors of your own** other than code factors. See [Factors of Your Own](https://keyringauth.com/docs/0.x/go/differences#factors-of-your-own).
- **The PHP package's `fixIncorrectEdDSAKey`** for registrations.
- **Reading and ending sessions from your own code**: `Sessions::signOutEverywhere()`, `stillSignedIn()` and the rest of `Sessions` and `SessionRegistry`. Run `keyring:sign-out`, or answer `false` from `AllowSignInWhen`. See [Services for Your Own Code](https://keyringauth.com/docs/0.x/go/differences#services-for-your-own-code).
- **`StepUp` and `SessionAssurance`**, which decide a step-up in a controller and read what the session proved. Put `RequireAssurance` or `RequireFreshVerification` on the route instead. See [Step-Up](https://keyringauth.com/docs/0.x/go/step-up).
- **The email for a sign in on an unrecorded device** your own `auth.Login` made, and marking a session recalled on routes `AuthenticateSession` doesn't cover.
- **Tidying up after a deleted user**, as the `HasKeyring` trait's `deleted` listener does: signing them out with `account_deleted`, ending their reset links, and deleting their sign-in methods, devices and log entries. See [Protected Attributes and Users](https://keyringauth.com/docs/0.x/go/differences#protected-attributes-and-users).
- **Reserved lookalikes** in scripts beyond Latin, Greek and Cyrillic. See [Email Changes and Reserved Addresses](https://keyringauth.com/docs/0.x/go/differences#email-changes-and-reserved-addresses).
- **MySQL.** The schema is checked against PHP's on SQLite and PostgreSQL only. On MySQL, Laravel Go's timestamp columns are `datetime`, where PHP's are `timestamp`.

And these have no counterpart, because there are no Eloquent models:

- **Swapping the models** (`useAuthenticatorModel()` and the rest). The tables are Keyring's own.
- **The `HasKeyring` trait.** Your user model's `Updating` hook calls [`Keyring.GuardChanges`](https://keyringauth.com/docs/0.x/go/protected-changes#protected-attributes), and code that creates users checks `Keyring.AddressReserved`. `Keyring.SignInMethods` stands in for `$user->keyring`.

## What Behaves Differently

### Signing In and Out

- **The user type is a type parameter.** `keyring.New[models.User]()` and `keyring.From[models.User](ctx)`. Users need an integer `ID`, string `Email` and `Password` fields and a `RememberToken`, which `Register` checks. The tables' `authenticatable_id` columns are big integers.
- **Finding users.** Keyring finds users with `auth.ModelUsers[U]` on `Config.Username`, unless you hand it your `auth.Users[U]` with `Keyring.FindUsersWith`, since Laravel Go keeps the registered provider to itself.
- **Signing out one browser.** Laravel Go has no `logoutCurrentDevice()`. Keyring empties the session and takes back both remember cookies itself, keeping the user's remember token, so a session that ends signs out that browser alone, as in the PHP package. Only `POST /logout`, but while impersonating, and a session whose record can't be ended, go through `auth.Logout`, which gives the user a new remember token. Unlike the Rust crate, which always uses `Auth::logout`.
- **A user with no remember token** is given one by `auth.Logout`, where Laravel's `logout()` only cycles a token that's there. Signing out everywhere doesn't give one, where the PHP package's `cycleRememberToken()` does. So `users.remember_token` can differ between the two sides for such a user.
- **A new password signs out every other session.** Laravel Go's guard signs a fingerprint of the password hash into every session, so `sign_out_others: false` can't keep the others. Their records end at once anyway, as `password_changed`. `sign_out_others` decides the rest of signing out everywhere, such as a new remember token. The browser that changed the password is signed in again under the new hash before it moves to its new record.
- **Middleware order.** Keyring adds `AuthenticateSession[U]` to the web group itself, and runs `auth.Session[U]` inside it, since a package's middleware runs before the application's. Don't add `auth.Session` yourself. An `auth.Session` of yours that runs ahead of it is refused with a `500` on every request.
- **Your own sign out.** Your `auth.Logout` is noticed by `AuthenticateSession` once the handler returns, by the record's ID leaving the session, so only on routes in the web group. The reason is `logged_out`.
- **A signed-in browser at a guest page** goes where Laravel's `RedirectIfAuthenticated` sends it: the route named `dashboard`, else `home`, else the site's root. The Rust crate sends it to `home`. Laravel Go has no `redirectUsersTo()`, and can't look up an unnamed `/dashboard` route, so name the route if a PHP application sharing users points there.
- **The session lock.** A request that waits the full 10 seconds for the session lock gets a `500`, not a `423`: Laravel Go answers its own lock timeout with a `423`, which a Keyring client reads as a step-up.
- **The user's row lock** is `FOR NO KEY UPDATE` on PostgreSQL, `FOR UPDATE` on MySQL and none on SQLite, and is waited for 5 seconds at most, where the PHP package waits as long as the database does. Past that the request answers `500`. There's no setting to turn it off.
- **A passkey alone that fails** names its account, and its `factor_failed` entries are refusals, capped by `SecurityLog.Refusals`, where the PHP package writes every one. `FactorFailed.Identifying` says so.
- **When `CloneSuspected` fires.** When the failure is counted, before `FactorFailed`, where the PHP package dispatches it from inside the check. The entries and their order are the same.
- **A right code is spent before the `unavailable` refusal**, in the PHP package's order. The Rust crate refuses first.
- **A failed challenge answer doesn't save the attempt**, where the PHP package's `VerifyFactor` saves it. The passkey options it held are spent on the server either way. An answer that leaves a code out of guesses is saved, so the page starts again.
- **The account's limits are cleared by the owner's right code** with devices off, as the PHP package's `FailureCounts::succeeded()` clears them. The same holds in all three ports.
- **Times are UTC.** `created_at` on log entries and alerts, and `password_reset_tokens.created_at`, are written and compared in UTC. A PHP application on another `app.timezone` sharing the database would see alert times and reset link ages differently.

### Remember Me

- **The guard's cookie differs.** Laravel Go's guard cookie is JSON named `remember_web`, where Laravel's is `id|token|hash` under `remember_web_<sha1>`. Keyring's own `remembered_session` cookie is the same on both sides, but a browser can't move between a Go and a PHP application.
- **A cookie sign in is told by the session ID changing**, as there's no `viaRemember()`. Keyring's own sign ins know they asked for it.
- **Your own `auth.Login(r, user, true)`** gets Keyring's cookie, and its record is marked remembered just after. The Rust crate records such a session, but not as remembered.
- **A browser that changes its password** isn't brought back by "remember me" afterwards, as with the PHP package. The Go port signs it in again without "remember me".

### Ending Another Session

Laravel Go has no way to destroy another browser's session by its ID, so ending one ends its Keyring record, and `AuthenticateSession` signs that browser out on its next request. Its session data stays in the store until it expires.

`DELETE /user/devices/{device}` 404s on a device already marked signed out, as the PHP package's `->active()` does. After a sign out that failed part way, the report link or the sessions list finishes it.

A 404 for someone else's device or authenticator says `Not Found`, not the PHP package's "No query results for model [...]", which names a PHP class.

### Policies and the Pipeline

- **The policy** is a closure with the request's context: `Keyring.Require(func(ctx context.Context, user *U, attempt keyring.Attempt) keyring.Requirement)`. There's no fixed-requirement setting beside it: a closure returning one does the same.
- **Requirements hang off `Level`**: `keyring.AAL2.Requirement()`, with `RequireFactors` and `RequireSteps` for the PHP package's `factors()` and `steps()`, and `NoDowngrade()` and `NoDowngradeExcept(...)` for its default argument. The zero `Requirement` is the default policy, not a requirement of nothing.
- **Steps are values** implementing `Step[U]`, given to `Keyring.Pipeline`, named by their type or a `Name()` method and the `Step*` constants.
- **Steps of your own only run between `VerifyFactor` and `CompleteAttempt`.** `EnsureNotThrottled`, `VerifyFactor` and `CompleteAttempt` can't be changed, even dangerously. A change Keyring refuses stops `Register`.
- **A step can only fail a verification** (`StepContext.Fail`), not lock it out.
- **The unregistered-factor refusal stays with `DetermineRequirement`**, in the PHP package's order. With that step dangerously removed or replaced, Keyring still refuses such an account, where the PHP package's refusal goes with the step.
- **`ResolveDevice` doesn't note "trust this device".** The form field is read where it's posted, so removing or replacing the step doesn't lose it.
- **`AllowSignInWhen`** answers a bool, as the PHP closure. `AllowsSignIn(nil, user)` is allowed outside a request.
- **Keeping a user out** signs this browser out even when ending the others fails, and answers `500`, where the PHP package throws before its own sign out.
- **`RequireAssurance` takes no recovery code alone for AAL1**, as the Rust crate's audit settled, where the PHP package's `keyring:aal1` does.

### Requiring a Second Factor

- **`RequireEnrollment` fails closed without the session**, a `500`, where the PHP package's finds no user and lets the request through.
- **The page saved for `continue`** carries `RequireEnrollment`'s own requirement. Laravel Go doesn't let a middleware see the values of the route's other middleware, so give `RequireEnrollment` the same options as the route's `RequireAssurance`, or a user who enrolls enough for one is sent back by the other.
- **A held user is let through to `PasswordChangeURL`'s page** past `RequireEnrollment`. In the PHP package and the Rust crate, a held user with no second factor goes round in a loop between the two pages.
- **The hold's exceptions are route names**, as in the PHP package, so a route of yours with one of those names is let through too.
- **The page saved is the URL as it came.** Laravel's `fullUrl()` sorts the query string, and `r.FullURL()` keeps it as sent.

### Managing Authenticators

- **Changes take the owner's cache lock and the user's row**, as the Rust crate's do, where the PHP package takes the row lock alone. On SQLite there's no row lock, so the cache lock is what keeps two changes apart.
- **Beginning an enrollment counts against `Limits.Forms`**, where the PHP package's route has no limit.
- **Making the default the default again keeps it.** The PHP package unsets it.
- **A posted credential whose `id` isn't the attested one** is refused, where webauthn-lib stores the attested ID whatever was posted.
- **Renaming or choosing as default one removed meanwhile** is a `404`, where the PHP package saves its stale copy and says it did.
- **A removal whose devices can't be distrusted** isn't made, and nothing is announced.
- **The first factor's recovery codes** are made under the lock, so a set made meanwhile in another request is kept.
- **Factors the Go port can't check** (a security key a PHP application added, or passkeys with `Factors.Passkeys` off) aren't listed, renamed or removed, and an account with one is refused at sign in with the `unavailable` `422`. They still freeze the account once added, and keep the recovery codes.
- **Registration with managing sign-in methods and no email verification** stops `Register`, unless `AllowEnrollmentWhen` decides, where the PHP package throws at the first enrollment.
- **`SignInMethods`** is the Rust crate's, as a Go application can't reach `$user->keyring`.
- **The QR code** is drawn from `rsc.io/qr`, 192 pixels across with no margin, not BaconQrCode's markup.

### Factors of Your Own

Code factors and primary factors of your own are there (see [Code Factors](https://keyringauth.com/docs/0.x/go/differences#code-factors)). Any other second factor of your own isn't yet.

- **A primary factor is a struct**, `PrimaryFactor[U]`, given to `Keyring.AddPrimaryFactor`, finding its user with an `IdentifiesUsers[U]` (`Identify` and `Verify`), which may also implement `ValidatesSignIns`, `DiscoversUsers` and `Stalls`.
- **It says what it proves once**, for the factor (`Categories`, `PhishingResistant`, `DeviceBound`), where a PHP factor's `categories()`, `phishingResistant()` and `deviceBound()` can vary with the authenticator. What a session proved with one counts for the categories recorded then, as in the PHP package.
- **It only starts a sign in.** It never answers the challenge or confirm pages, and users don't enroll it: the PHP package's `answersChallenges()`, `enrollable()`, `onePerUser()`, `priority()` and `errorKey()` aren't ported. A refusal is reported on the first of `IdentifiedBy`, or on `code`.
- **There's no `attested()`, `present()`, `limits()` or `authenticators()`** (virtual authenticators) to override. It counts under the configured limits: the address's alone, or the typed name's and the account's when `IdentifiedBy` includes `Config.Username`.
- **`Verify` answers whether the proof holds** rather than with a `Verification`, and gets the row as a `PrimaryAuthenticator`, its secret decrypted.
- **Keyring doesn't validate its fields** (`identificationRules()`, `rules()`): the factor does, in `Validate`, refusing with a `*web.InputError`. Keyring calls it before the limits, so a missing field is answered alike whether or not the account is refused without saying so.
- **A row that isn't the user's confirmed authenticator of the factor**, named by `Identified.AuthenticatorID`, is taken as nobody found, after `Stall`.
- **A primary factor's key is the process's**, as the Rust crate's: `Register` refuses a code factor of another application in the process with the same key, and the other way round.

### Code Factors

- **A code factor is a struct**, `CodeFactor[U]`, given to `Keyring.AddCodeFactor`, its sender a `SendsCodes[U]`, and making a new authenticator an optional `MakesCodeAuthenticators[U]`. It proves possession, or the address with `SentToAnAddress`.
- **`Register` refuses what the PHP package refuses at first use**: `verification_code` in `Notifications.Off` with emailed codes on, and `Limits.Codes` under one or `Limits.CodesPer` under a second with a code factor on. Codes are capped at 18 digits.
- **Emailed codes are off** until `Factors.EmailCodes` is set, as the PHP package has them only once registered.
- **Codes are sent in the request**, never queued, so a code never sits in the jobs table. A sender's error is the request's `500`, with the new code already kept.
- **Each cache keeps its values its own way.** PHP serializes and Laravel Go doesn't, so a code one side sent is checked only by the side that sent it. The keys and hashes are the same.
- **Sends for adding a factor are limited per account only**, as in the PHP package. Whoever is signed in chooses the destination, so a paid SMS sender can be made to text other people's numbers, a few every ten minutes per account. Limit by destination and IP in your `Deliver`.
- **Wrong guesses are read, compared, then counted**, in all three ports, so two guesses at once can both be checked against the same count. An enrollment's code can get about twice `MaxGuesses` across a code begun again late in the window.

### Passkeys and Attestation

- **WebAuthn is Keyring's own** package (`go/keyring/webauthn`, standard library only), running webauthn-lib's checks in its order, so what passes and what's refused matches the PHP package. Ed25519 keys are checked, which the Rust crate can't do.
- **Records are written back as webauthn-lib writes them**: its keys in its order, nulls left out, unknown fields dropped, IDs as unpadded base64url, the AAGUID lowercased. The Rust crate keeps unknown fields and the stored order.
- **Answers are capped**: authenticator data or an attestation object over 64 KiB is refused before it's read, and so is a registration with an empty credential ID. webauthn-lib reads any size and only caps a credential ID at 1023 bytes.
- **Cross-origin answers are refused**: `crossOrigin: true` with no `topOrigin`, and a `topOrigin` of `null`, which webauthn-lib lets through.
- **Settings are checked at boot**: origins, the relying party ID and algorithm names, where the PHP package throws on the first ceremony.
- **International hosts** follow the URL Standard's bidi and joiner rules, as browsers do. A few hosts PHP takes stop `Register` with passkeys on.
- **`Factors.Passkeys` is on by default**, where the PHP package has whatever factors the application lists.
- **A passkey alone loads its user with `Find`**, not `FindForLogin`, as in the PHP package and the Rust crate. Use `AllowSignInWhen` to keep users out of every factor.
- **A user handle's oldest key** is found by `created_at`, then `id`.
- **An AAGUID** is read only in its hex form.
- Security keys and attestation aren't there yet. See [Not Available Yet](https://keyringauth.com/docs/0.x/go/differences#not-available-yet).

### Devices

- **The describer** is a function in `Devices.Describe`, and the locator a `LocatesIPs` value in `Devices.Locator`, not classes the container builds. The locator is asked once per request.
- **Countries are compared as text**, so `"1"` and `"01"` are two countries, where the PHP package compares loosely. An empty location is unknown.
- **The new-device email goes through the queue**, after commit, as in the PHP package. Laravel Go uses the `database` queue whenever `DATABASE_URL` is set, so without a worker (or `QUEUE_CONNECTION=sync`) nothing is sent.
- **A failed device-trust mark** still ends the trust and answers `500`, where the PHP package stops before the update.
- **The device a sign in comes from** is loaded again each time the policy is asked, so trust taken away meanwhile counts at once.

### Sessions and the Registry

- **One driver.** The registry is always `keyring_sessions` on the application's database. The PHP package's `sessions.driver`, `table` and `connection` aren't ported.
- **Overlapping requests are ported** (`Sessions.OverlappingRequests`, on), unlike the Rust crate. Keyring wraps the web group's `StartSession` store, removes a replaced session's cookies by renaming them to nothing, and takes `Sec-Fetch-Site` off such a request so the CSRF token decides. A `StartSession` you add yourself isn't covered.
- **A record is ended only if it's the user's**, stricter than the PHP package and the Rust crate.
- **An alert is shown to one sign in only**, marked seen only if still unseen, where the PHP package can show it to two at once.
- **Pages that also serve guests** are listed by route name in `Sessions.ContinueAsGuest`, as in the PHP package. An empty name stops `Register`.
- **A risk step-up's new record is noted as used now**, so a session stepped up near its idle limit carries on. The PHP package and the Rust crate copy the old record's last activity.
- **A sign in whose session can't be saved** has its record ended, as the Rust crate's `EndUnsavedSignIns` ends it, by middleware Keyring places in the web group itself. Only a request whose session wasn't saved ends one, where the crate ends the record on any `5xx`.

### Impersonation

- **Who may impersonate whom** is given to `Keyring.AllowImpersonationWhen`, which also takes the request's context. One that panics fails a start with a `500`, and counts as a no while an impersonation runs.
- **`Impersonation.Middleware` is a list of middleware values**, `RequireAssurance[U]{Level: keyring.AAL2}` and `RequireFreshVerification[U]{Within: 15 * time.Minute}` by default, standing in for the PHP package's `['keyring:aal2', 'keyring.fresh:15m']`. Unlike the Rust crate's two settings, the confirm for AAL2 builds on what still counts toward it, as in the PHP package.
- **`Keyring.Impersonate`** asks what `Impersonation.Middleware` asks before it starts anything, and returns the step-up's answer for you to send, where the PHP package leaves that to the route's middleware. A refusal is an `*ImpersonationRefusedError`, and the reasons are string constants (`RefusalSelf` and the rest).
- **`Keyring.StopImpersonating`, signed out instead,** leaves `auth.User` returning the impersonated user for the rest of the request, as Laravel Go can't make the guard forget a user without `auth.Logout`. Answer straight away.
- **Every start, Keyring's route's too, also refuses**, as `impersonating`, a start from a session record an impersonation that hasn't ended already parked: a copy of the session from before a start. The PHP package doesn't check this. That impersonation ends as it's refused, so a session left that way isn't refused again. The Rust crate does the same.
- **Someone's name** is their `Name` field, or the field of `Config.Username`'s column, standing in for the `name` attribute and username.
- **Going back keeps both remember cookies**, even when the user's password changed while impersonated and Laravel Go's guard took its cookie back. The Rust crate loses the guard's cookie there.
- **Your own `auth.Logout` while impersonating** ends the impersonation and the parked session, as in the PHP package, and gives the user a new remember token, as `Auth::logout()` does. There's no `logoutCurrentDevice()`, so use Keyring's `POST /logout`.
- **The claim that only one request ends an impersonation** is kept in the default cache store, where the PHP package keeps it in `cache.limiter`'s.
- **`Impersonation.ShowInActivity`** is read by nothing yet, as there's no activity feed.

### Single Sign-On

- **All four of the PHP package's drivers** are there: `oidc`, `google`, `microsoft` and `github`, so links any of them made in PHP sign in here.
- **Providers are a slice** of `SSOProvider` in `SSO.Providers`, built with `OIDCProvider`, `GoogleProvider`, `MicrosoftProvider` and `GitHubProvider`. A name given twice stops `Register`. Anything else wrong with one is found when it's built, reported and left off the login page.
- **A driver of your own** implements `IdentityProvider` and is registered with `SSO.Extend`. Its identity is held to the provider and request Keyring knows, and refused without an issuer or subject, where the PHP package takes what its driver says.
- **ID tokens** are checked by Keyring's own `jose` package, and where a provider's URLs point by its own `hosts` package, each ported from the PHP package. Go's `crypto/rsa` refuses an RSA exponent over 2³¹−1, which OpenSSL takes. No provider publishes one.
- **`::ffff:0:0/96` is inward**, and a URL with no host is never the same host as anything, as the Rust crate's fixes.
- **`SSO.ResolveHosts`** stands in for `HostResolver::fake()`. Nil asks DNS.
- **DNS rebinding is refused.** A token endpoint or key set let through only for being on the public internet is connected to only at a public address, so a name that resolves somewhere private by the time it's connected to is refused. The PHP package resolves the name again and connects. `PrivateEndpoints`, the issuer's own host and port, and an issuer on this machine skip it, as they skip the address check.
- **Linking refuses an account any row already has**, before inserting, where the PHP package inserts and turns the unique violation away the same.
- **`Factors.SingleSignOn` starts off**, as it needs a provider.
- **An `amr` given as an object** is read in key order. It counts toward nothing.
- **Discovery documents** are cached as their checked body and read from the cache each time.
- **Only a `2xx` answer from a provider counts**, as the Rust crate's, where the PHP package takes a `3xx` too. Keyring reads at most 1 MiB of one.
- **Your application's HTTP client settings don't reach a provider**: the headers, tokens, query, retries and transport given in `laravel.Options.HTTP` stay behind, where the PHP package's requests go through Laravel's `Http` facade with whatever it was given.

### Signing In From Your Own Routes

- **`Keyring.Attempt` takes a factor's key**, and **`Keyring.AttemptSSO`** the identity and "remember me", where the PHP package's `Keyring::attempt()` reads them from the request. With `Factors.SingleSignOn` off, `AttemptSSO` is a `404`. A refusal is the error, for `web.Fail`, where the PHP package throws a `ValidationException`.
- **A browser someone is signed in on is sent on** by `Attempt` and `AttemptSSO`, as `Guest` sends it, where the PHP package signs the new user in over them.
- **`SignInAs` takes `ProvedPassword()` or `ProvedAuthenticator(id)`**, one of the user's own sign-in methods of a factor the application has, where `SignIn::as()` takes any `Verification`.
- **`LinkedSSO` and `LinkNewAccount`** are the Rust crate's: `SingleSignOn::linked()`, and the PHP example's creating the row. `LinkNewAccount` refuses an account with any sign-in method, a password included, and dispatches nothing, as the PHP example, where the Rust crate's dispatches `AuthenticatorAdded`.
- **Keyring's limiters aren't yours to put on a route**, so there's no `keyring-login-options` for your own callback. Put a rate limit of your own on it.

### Pages and Responses

- **Pages are Inertia pages**, `auth/{name}`, or the page's name and props for a JSON request. There are no views, and no `renderUsing()`. With `Config.Pages` off, anything but JSON is a `404`.
- **A lockout's `429`** is a validation error with its own status. A browser gets the `422`, which goes back to the form.
- **Answer bodies.** Keyring's own JSON keeps the PHP package's key order. Page props and Laravel Go's own error bodies are maps, so their key order varies.
- **A guest's redirect to log in** from a signed-in route carries Keyring's security headers, which the PHP package's lacks.
- **The `Sec-Purpose` header** is read as Laravel reads it, so a Chrome prerender counts as a prefetch.

### Routes

- **Keyring adds its routes to the web group**, under `Config.Prefix`. With `Config.Routes` off, call `Keyring.Routes` where you want them. There's no `domain` setting.
- **Route names are the PHP package's**, so `Sessions.ContinueAsGuest`, `Config.EnrollmentExcept` and `Config.PasswordChangeExcept` take names, as in the PHP package. The Rust crate takes paths.
- **Middleware are typed values**: `RequireAssurance[U]{Level: keyring.AAL2, DeviceBound: true}` for `keyring:aal2,device-bound`, and `RequireFreshVerification[U]{Within: 5 * time.Minute}` for `keyring.fresh:5m`. `Config.ChangesMiddleware` is a list of them.
- **`BlockSession`** marks a route for the session lock, standing in for `->block()`, and works on routes in the web group alone.
- **Signed links** are signed relative to the site with Laravel Go's URL signer, so a link either side signs opens on the other.

### Risk

- **Signals are values**, given with `Keyring.RiskSignals`, which adds to them. There's no replacing the list. Each built-in signal is a struct whose zero fields are the PHP package's defaults, so a score of 0 can't be asked for: leave the signal out.
- **An answer is a struct**, `keyring.Action{StepUp: true, Notify: true}`, not a builder. `LockFor` is a duration, and zero locks nothing.
- **`RespondToRisk`** takes the context: `func(ctx context.Context, risk *keyring.Risk, at keyring.Checkpoint) keyring.Action`.
- **`Risk.Levels` must be in order, with a medium of at least 1.** The PHP package takes anything.
- **A sign in's attempt always carries a risk once assessed**, empty when nothing was found.
- **`ImpossibleTravel`'s distance** can differ from PHP's in the last bit, as Go's sine and cosine aren't the C library's.
- **Risk locks aren't shared with PHP**, even on one cache store: each side writes the lock in its own format. A lock placed on one side holds on that side only.

### Events

- **Events are generic structs**, such as `keyring.FactorFailed[models.User]`, carrying the user as `*U` and plain values where the PHP payload is a model.
- **`SessionEnded[U]`** is new, dispatched where the PHP package's middleware ends a session.
- **`FactorFailed`** carries `Identifying` for a passkey alone.
- **Package listeners run first.** Keyring's own listeners, which write the security log and send emails, run before your application's, so a listener of yours that fails can't keep an entry off the log.
- **`ProviderIdentityAccepted[U]`** carries the identity without the request's secrets or the token's nonce.

### The Security Log

- **Writing never fails a sign in.** Each entry is written in its own savepoint. A failed write is reported and goes to `slog.Default()`, under a `keyring` group, with `notice` at info and `critical` at error. Laravel Go has no named log channels, so there's no `security_log.channel`. With `Features.SecurityLog` off, every entry goes there.
- **Request IDs** come from your log context under `SecurityLog.ContextKey` (`trace_id`), or a UUID.
- **The `once` refusal** (a lockout's `locked_out`) is taken with one atomic cache add, where the PHP package checks then counts.
- **Setting a struct whole turns things off.** `cfg.Features = keyring.Features{Devices: true}` turns the security log off, and `cfg.SecurityLog = keyring.SecurityLog{...}` turns alerts off. Set fields one at a time.

### Emails

- **Keyring's own emails** have the PHP package's lines without Laravel's notification layout, which Laravel Go hasn't got.
- **Replacing one** is a function in `Notifications.Mail` or `Notifications.AccountMail` returning a `mail.Mailable`.
- **Security emails are queued** after commit. **Account emails** (the reset link, the verification link and `already_registered`) are sent with the mailer in the background, never queued, as the PHP package sends them in the request: a reset token never sits in the jobs table.
- **Subjects** are those of the Laravel the PHP package runs on: "Reset your password" and "Verify your email address". The Rust crate uses Laravel's older wording.
- **A taken address at registration** is mailed at the address its account has, and only when that's the address typed once both are normalised. The PHP package and the Rust crate mail the typed address, which on a collation that ignores accents tells another mailbox that an address is registered.
- **`registered` and `registration-received`** name the login page by its route, wherever you placed Keyring's routes.
- **The 429 for another verification link** counts down as the sign-in lockout does.
- See [Not Available Yet](https://keyringauth.com/docs/0.x/go/differences#not-available-yet) for the four security emails not sent yet.

### Passwords

- **The features start off.** Registration, email verification, password resets, password changes and email changes are off until you turn them on and give Keyring your actions, as the Rust crate starts them, where the PHP package's config turns them on. One that's on without its action stops `Register`.
- **Actions take and give maps**: `CreatesNewUsers[U]` (`Validate`, then `Create`), `ResetsUserPasswords[U]` and `UpdatesUserPasswords[U]`, their passwords already in NFC. They save the password themselves.
- **`Config.Email`** is new, the PHP package's `keyring.email`, apart from `Config.Username`.
- **Email verification** is `Features.EmailVerification`, standing in for `MustVerifyEmail`. With it on, the user type needs an `EmailVerifiedAt` or `EmailVerified` field and the users an `auth.EmailVerifier`. A Go application sharing users with a PHP application that verifies addresses should turn it on.
- **Who may sign in** follows the PHP package's `hidesRegisteredAddresses()`: registration on and `Registration.RevealTaken` off. The Rust crate has a switch of its own.
- **Taken addresses** are looked for in the user model's table under `Config.Email`, or through an optional `Taken` method on the action (`TakenAddresses`). A unique violation from `Create` is looked at again, as in the PHP package, rather than taken as "taken".
- **The checks the Rust audit moved ahead of the action stay ahead of it**: the current password again, the held one, and one bcrypt can't take are refused before your action runs.
- **A reset runs under the owner's lock**, so two resets with one link go through once, and is refused once the account's address has changed since the link was found. Laravel's broker takes no lock.
- **A change's write rolls back** with the user's row lock on PostgreSQL and MySQL when the action fails. On SQLite it stands.
- **The password actions run with a deadline**, 2 seconds before the owner's 10 second lock lapses, and the breach checks fit within it. A check that runs out counts as unchecked.
- **`RequirePasswordChange`** takes the reason as a string, `""` for none.
- **Laravel's messages for `email|max:255`** both show, as Laravel doesn't stop at the first rule a field breaks.
- **`password_reset_tokens`** is created by Keyring where it's missing, in Laravel's schema, from a migration with a name no PHP application has. An application migration of yours that makes it and sorts before Keyring's keeps its own.
- **Resets and an email change at once.** `auth.EmailVerifier` can't compare and set, so null `email_verified_at` in the same write as an address change of your own.
- **TOTP secrets** decode as the Rust crate's (any case, spaces, padding, at least 10 bytes), looser than Google2FA: a hand-imported 20 or 52 character secret works here and fails in PHP.

### Email Changes and Reserved Addresses

- **Saving the address.** Keyring saves it with `model.Update`, writing `Config.Email` and, for a newly confirmed address, `email_verified_at` in the same write. A `ValidatesEmailChanges[U]` that's also a `SavesEmails[U]` saves it itself.
- **A confirmation that finds the account already has the new address** finishes the change rather than cancelling it, as the Rust crate does.
- **Changes are found by `authenticatable_type` and attribute**, so a change another user type or another attribute made isn't this application's to confirm.
- **Reserved lookalikes.** The PHP package folds an address with Laravel's `Str::transliterate()`. It's ported as the Rust crate ports it: a table of what that does to Latin, Greek and Cyrillic letters, general punctuation and characters that don't show. A character from another script is kept, lowercased, where the PHP package transliterates or drops it, so an address with one only matches itself, and a reservation made on one side isn't found by the other.

### Protected Attributes and Users

- **Laravel Go's models have an `Updating` hook**, not Eloquent's `updating` event. Call `Keyring.GuardChanges(ctx, user, values)` from it, or before a write that doesn't go through the model, with the columns it writes. It compares them with the stored row, as `isDirty()` does, and forgets the old address's reset link when the address changes, as the trait's `updated` listener does. `Register` refuses a user type without the hook while anything is protected, unless `Config.GuardChangesManually` is set. See [Protected Attributes](https://keyringauth.com/docs/0.x/go/protected-changes#protected-attributes).
- **Creating a user isn't a change.** Check its address with `Keyring.AddressReserved`.
- **Deleting a user** isn't seen by Keyring. Their sessions carry on until `AuthenticateSession` finds the user gone and signs the browser out, as `logged_out`, and their rows stay in Keyring's tables. Delete them yourself where you delete users.
- **`Keyring.WithoutProtection`** takes a context and a function, and logs `protection_bypassed` before the function runs: a bypass that can't be logged doesn't happen.

### Console Commands

- They run as your application's commands (`go run . keyring:prune`), and exit with the PHP commands' codes: 0 when they worked, 1 when they didn't, and 2 for arguments that don't go together. `keyring:prune`, `keyring:sweep`, `keyring:sign-out` and `keyring:import` read from the database's writer, not a read replica, as the PHP package's `useWritePdo()` has them.
- `keyring:prune` names each table rather than each model (`Pruned 3 [keyring_devices] records.`). A zero `SecurityLog.KeepFor`, `Devices.KeepRevokedFor`, `Devices.KeepUnseenFor` or `EmailChanges.KeepEndedFor` is its default, since Go can't tell zero from unset, so a struct set whole doesn't delete the whole table. `Register` refuses a negative one. `PruneAt` set to `""` leaves scheduling it to you, as the PHP package's `null` `prune_at`.
- `keyring:sign-out` names a user by their `Config.Username` column and ID, and only takes an ID made of digits. It warns when the default cache store is Laravel Go's `memory` or `discard` store.
- `keyring:import` reads Fortify's columns from the table `SessionUserType` names, or the one `--table` names, warning that it files every row under `AuthenticatableType` when that's another table. It decrypts them with the application key, where the PHP package asks Fortify for its encrypter. It can't read Fortify's config, so a secret that was never confirmed needs `--fortify-confirm` (or `--unconfirmed`). A passkey it imports that can't sign in here is listed with the PHP package's warnings, naming `WebAuthn.Algorithms` and `WebAuthn.MinimumRSABits` where they say `config/keyring.php`. In place of "Register … first", it asks for `Factors.Passkeys` on. See [Importing Two-Factor Data](https://keyringauth.com/docs/0.x/go/upgrading-from-fortify#importing-two-factor-data).
- `keyring:install` writes nothing, as the migrations come with the package and the config, the package and the actions are your Go code. It prints the `keyring.New` for what was picked and what's left to do, asks nothing, and has no `--force`. Since Keyring for Go has passkeys and the security log on unless they're turned off, it prints `cfg.Factors.Passkeys = false` and `cfg.Features.SecurityLog = false` when they aren't picked. There's no `security-keys` factor. With an authenticator app or passkeys picked, it requires a second factor unless `--optional-second-factor`: it prints `EnrollmentURL` set to `/settings/security`, and a `Middleware` function that appends `RequireEnrollment` to the `web` group. Where the PHP command asks for the `HasKeyring` trait, it asks for the user model's `Updating` hook that calls `GuardChanges` (or `Config.GuardChangesManually`) whenever `update-passwords` or `email-changes` is on, since `Register` refuses those without it.
- There's no `canSweep()` or `MissingMigration`, as Keyring for Go has the database registry alone and the migrations come with the package. `Sessions.SweepEvery` is a `time.Duration`, and zero is off, as the PHP package's `null`, since Go can't tell zero from unset. Over 12 hours is 12 hours, which `keyring:sweep` says as it runs and logs once a day. A zero `Sessions.SweepLimit` is 1000.

### Services for Your Own Code

- **`Keyring.ClearAccount`** and **`Keyring.Unlock`** start a user's sign-in limits over, the second also lifting a risk lock.
- **`Keyring.RequirePasswordChange`**, `RequiresPasswordChange`, `PasswordChangeReason` and `CancelPasswordChange` manage password holds.
- **`Keyring.PendingEmailChange`** and `CancelEmailChanges` read and cancel email changes.
- **`Keyring.SignInMethods`** lists a user's sign-in methods as a settings page shows them.
- **`Keyring.Record`**, `RecordOrFail`, `RecordRefusal`, `CountEntries`, `AccountsFrom` and `PullAlerts` reach the security log.
- **`Keyring.Assess`**, `Enforce`, `NewAssessment`, `AssessmentOf`, `IsRiskLocked` and `SignalsAt` reach risk, for a step of your own.
- There's no service to sign a user out everywhere from your code. Run `keyring:sign-out`, or answer `false` from `AllowSignInWhen`, and Keyring signs every session out on its next request.

### Test Helpers

- **`keyringtest.New[U](t, client)`** gives the helpers for one test's application, and has its refusals answer at once, as `InteractsWithKeyring` does for a test case.
- **`kt.Fake()`** starts a new fake that decides in place of an earlier one rather than returning it, its assertions with a count are `Times` methods, and it's undone when the test ends, so a subtest's fake gives way to its parent's again.
- **Acting as a session that proved something** is `kt.ActingAs(&user, proofs)`, with `keyringtest.Assurance(level)` or `VerifiedWith(...)` and `FreshAt(at)` for a time, not methods on the test case.
- **Factory states** are values given to `kt.Add(&user, ...)`. `RecoveryCodes()` is a new set Keyring made, returned with its codes, rather than the PHP factory's fixed ones, and there's no `securityKey()` or `attested()`, as Keyring for Go has no security keys or attestation.
- **`VirtualAuthenticator`** registers with a `none` attestation only, and there's no `VirtualManufacturer`.
- **`FakeIdentityProvider`** goes in Keyring's settings with `Register(name)` and is `Serve`d in the test, through `httpclienttest`.
- **`Conformance`** is a struct whose `Run(t)` runs each check as a subtest on an application of its own, rather than a trait of test methods. It acknowledges dangerous steps and unchecked routes with `AcknowledgedDangerousSteps` and `AcknowledgedUncheckedRoutes`, checks the email and password are protected through `model.Update` (or its `Update`, for an application with `GuardChangesManually`), and doesn't check that a registry returns what it revokes or keeps a session's handle when it moves (Keyring for Go has one registry), nor bcrypt's half of the 64-character password check (Laravel Go only hashes with bcrypt).

## What Laravel Go Would Need

What the Go port works around, and the Laravel Go API that would let it match the PHP package. "As laravel-rust" means the Rust crate lacked it too.

| Missing in Laravel Go | What It Would Give | What the Go Port Does Instead |
|---|---|---|
| Signing out one browser (`logoutCurrentDevice()`), as laravel-rust | Signing out without a new remember token. | Empties the session and takes both remember cookies back itself, keeping the token. `auth.Logout` only for `POST /logout`, but while impersonating, and where a record can't be ended. |
| Destroying another session by its ID, or the session store from a request, as laravel-rust | Removing an ended session's data at once. | The record's check signs that browser out on its next request. |
| `viaRemember()`, and knowing the guard queued its remember cookie, as laravel-rust | Telling a remember cookie's sign in. | Tells it by the session ID changing. Keyring's own sign ins know they asked for it. |
| Laravel's auth events (`Login`, `Logout`, `Failed`, `Lockout`, `PasswordReset`, `Registered`, `Verified`), or a hook before `auth.Login` writes the session, as laravel-rust | Writing a sign in's record alongside it, and seeing your own sign out as it happens. | Dispatches its own events, and notices your sign out once the handler returns. |
| A per-request clock, or a public way to move the application's | A test clock for one request. | The contract app moves the application's clock with `reflect` and `unsafe`, under a lock. |
| A route-level session lock (`->block()`), as laravel-rust | Taking the session lock for a route. | `BlockSession`, on a cache lock. |
| A fixed-window rate limiter with decay, lock keys and `availableIn()`, as laravel-rust | Counting attempts as Laravel's `RateLimiter`. | Keeps its own counts in the cache, outside any transaction. |
| A public way to reach the application's `auth.Users[U]` | Finding users exactly as the guard does. | `auth.ModelUsers[U]` on `Config.Username`, or the users given to `Keyring.FindUsersWith`. |
| A package placing middleware after the application's own | Appending `AuthenticateSession` after your `auth.Session`. | Runs `auth.Session[U]` inside `AuthenticateSession[U]`. |
| A validation error with a status other than 422 | A lockout's `429` with its message on the field. | Wraps the error with a `429` status. A browser gets the `422`. |
| A translator and locale, as laravel-rust | Translating Keyring's messages. | English only. |
| Reset tokens in `password_reset_tokens`, as laravel-rust | Reset links either side sends working on the other. | Keeps the tokens in that table itself, as Laravel's `DatabaseTokenRepository`. |
| Keeping other sessions when the password changes, as laravel-rust | `sign_out_others: false` honoured. | Ends the other records as `password_changed` either way, and signs this session in again with `auth.Login`. |
| A generic OpenID Connect driver that checks the ID token | Single sign-on through the framework. | Keyring's own OpenID Connect client, with the `jose` and `hosts` packages. |
| A DNS resolver the HTTP client is pinned to, as PHP | Checking an endpoint's addresses and connecting to the same ones. | Resolves a name itself, then the client resolves it again. |
| TOTP and WebAuthn, as laravel-rust | | Keyring's own `totp` and `webauthn` packages. |
| A QR code renderer, as laravel-rust | An authenticator app's QR code. | `rsc.io/qr`, drawn as an SVG of Keyring's own. |
| `session.CreateTable`'s `last_activity` as PHP's integer | One `sessions` table for both sides. | Each side keeps its own session table. Keyring's tables are shared. |
| Timestamps at PHP's precision by default | `Y-m-d H:i:s` without thinking about it. | Keyring's columns are whole seconds and every time it writes is cut to the second. Set `DB_TIME_PRECISION=0` for what Laravel Go writes itself, such as `email_verified_at`. |
| A `MustVerifyEmail` a user type opts into | Telling a type that verifies its address from one that just has the column. | `Features.EmailVerification`. |
| A timestamp column of PHP's `timestamp` type on MySQL | Identical MySQL schemas. | Not checked yet. |
| Argon2 hashes | Checking Argon2 passwords a PHP application made. | bcrypt only. |
| A request of its own per test request on `laraveltest.RefreshDatabase`'s transaction | Requests a test makes at once each waiting for the other. | Runs each request on a `db.Concurrent` branch. A request a test makes while its own code holds a savepoint on the client's context hangs until the test times out. |
| Named log channels a package can write to | The security log's fallback in a channel of its own. | `slog.Default()`, under a `keyring` group. |
| A hook around `StartSession`'s load and save | Overlapping requests without workarounds. | A wrapped store on the web group's `StartSession`. Others aren't covered. |
| Removing a cookie from a `web.Response` | Taking a session's cookies off an overlapping request's answer. | Renames each to nothing, which `net/http` never writes. |
| A CSRF check that doesn't pass on `Sec-Fetch-Site` alone | The PHP package's `419` for a request on a destroyed session. | Takes the header off such a request. |
| `FOR NO KEY UPDATE` in the query builder | The user's row lock without raw SQL. | Raw SQL on PostgreSQL. |
| A middleware seeing the route's other middleware with their values | `RequireEnrollment` saving a page with what a `RequireAssurance` on the route asks. | `RequireEnrollment` takes the same options. Give it the route's. |
| `Sec-Purpose: prefetch;prerender` read as a prefetch | `StartSession` not noting a prerender as the last page seen. | Keyring reads it as Laravel does for its own pages. |
| `redirectUsersTo()`, and an unnamed `/dashboard` or `/home` route | Choosing where a signed-in browser at a guest page goes. | Asks the `dashboard` and `home` route names, then the site's root. |
| Session payloads and the remember cookie in PHP's format, as laravel-rust | One session store for both sides. | Not shared. |
| A request's attribute bag | Keeping a request's location once looked up. | A memo in the request's context. |
| Telling whether a named cache store exists without using it | `Register` refusing a `Risk.Store` that isn't configured. | The first lock panics, a `500`. |
| A pipeline of types the container resolves, as laravel-rust | Steps an application names, Keyring's own among them in any order. | `Steps[U]` of `Step[U]` values between `VerifyFactor` and `CompleteAttempt`, Keyring's checks around them fixed. |
| Cache values in PHP's serialized format | Sharing codes, risk locks and discovery documents with PHP on one store. | Each side reads only what it wrote. |
