← All plugins
golem15.mfa

Multi-factor authentication

Second factors for golem15.user accounts in SummerCMS applications: a login gate that answers a challenge instead of a token, and the PHP user plugin's /_user/api/v1/2fa routes for TOTP, WebAuthn security keys, recovery codes, codes by email and trusted devices, with a backend settings screen and the Users screen's "Reset 2FA" service.

summer plugin:install golem15.mfa
Latest version
v0.2.1
Framework
v0.6.5
Requires
golem15.user v0.1.20
Category
Users
Go module
git.golem15.com/golem15/sm-mfa-plugin

README

golem15.mfa

Second factors for golem15.user accounts in SummerCMS applications: a login gate that answers a challenge instead of a token, and the PHP user plugin's /_user/api/v1/2fa routes for TOTP, WebAuthn security keys, recovery codes, codes by email and trusted devices, with a backend settings screen and the Users screen's "Reset 2FA" service.

import _ "git.golem15.com/golem15/sm-mfa-plugin"

Module git.golem15.com/golem15/sm-mfa-plugin, package mfa, plugin ID golem15.mfa, requires golem15.user.

Overview

The plugin ports the PHP user plugin's two-factor service. At boot it adds a login gate to the registry golem15.user publishes (userclasses.LoginGates). When a user with an enabled second factor signs in with email and password, POST /_user/api/v1/login answers 200 {two_factor_required: true, challenge_token, available_methods, expires_at} and no token. The client then completes the challenge at one of the unauthenticated challenge routes, which answer the same {token, user} as /login, minted by golem15.user's own helpers, followed by its login event.

An application without this plugin has no /2fa routes, no second-factor tables and no WebAuthn, OTP or QR modules in its build, and /login answers as before.

Features

  • A login gate for password sign-ins. Mode disabled exempts everyone, and nothing else does (there is no per-group or child-account exemption); otherwise a user with an enabled method is challenged. Passkey, device and two-factor sign-ins are never challenged. Social sign-ins skip the challenge, as in PHP, unless two_factor_social_login is on; the frontend's OAuth callback must handle two_factor_required before an application turns it on.
  • Challenges: a 64-character token from crypto/rand, stored only as its SHA-256 hex, valid two_factor_challenge_ttl minutes (5). Every verification counts an attempt in one guarded UPDATE, so a challenge allows five attempts even under parallel requests, and completes in a second guarded UPDATE, so it issues at most one token. The completing transaction also spends the factor, creates the trusted device and runs golem15.user's FinishLogin with the token and the user payload; the settings and the session cookie are read before it and the login and verified events fire after it commits, so a sign-in that fails answers the opaque 500 with the challenge still open and nothing spent (no recovery code, no TOTP step, no event). Every verification also checks that the user may still sign in, since the password step ran up to the challenge's lifetime earlier: a ban (from any address), a suspension at the verifying address (the check /login makes) or a tokens_valid_after later than the challenge (a password change or another revocation) refuses it with the route's generic 401 and spends nothing.
  • available_methods lists the user's enabled methods, not filtered by the global two_factor_available_methods (as in PHP): a method an administrator removes from the list keeps working for the users who enabled it.
  • TOTP through github.com/pquerna/otp: SHA1, 6 digits, a 30-second step and a window of one step either side. The issuer is golem15.mfa.issuer or app.name, the account the user's email. The secret is stored encrypted (lagoon.Encrypted), and the last accepted time step is stored in the method's metadata, so a code is accepted once (PHP accepted it again within the window).
  • The setup answer carries the otpauth URL as an SVG QR code, 200 by 200 pixels with a viewBox, drawn from github.com/boombuler/barcode/qr's matrix at error correction level M.
  • A deactivated (soft-deleted) account is restored only after the second factor, by golem15.user's FinishLogin: the password alone cannot reactivate an account a second factor protects.
  • Recovery codes: sets of 10 in the form XXXXX-XXXXX over 23456789ABCDEFGHJKMNPQRSTUVWXYZ, stored as bcrypt hashes at golem15.user.password.bcrypt_cost. A code works once (a guarded UPDATE consumes it) and is always accepted at 2fa/recovery, whatever methods the user has. Input is upper-cased with spaces removed (the hyphen is kept). Listing returns only the remaining count and needs the password; regenerating replaces the set in one transaction.
  • The first set is shown once: when totp/confirm or email/enable creates the user's first set (no unused code existed), the answer adds recovery_codes (PHP generated the set and never showed it). Answers that create no set are PHP's, unchanged.
  • Codes by email: six digits from crypto/rand, stored on the challenge as a bcrypt hash and mailed through golem15.mfa::mail.two_factor_code (-en for English-speaking users, chosen as golem15.user chooses its mails) with name, code and expiry_minutes. Only users who enabled the email method get a code, and verify with method: email works only for them; anyone else gets the same 401 {"error":"Invalid or expired challenge."} (PHP mailed a code to any user, which turned a TOTP account into an email account). A challenge mails at most three codes. The mail announces the shorter of two_factor_email_code_ttl and the challenge's remaining time.
  • A per-user failure cap: after failure_cap.max (10) failed verifications within failure_cap.window_minutes (15), counted from the challenge rows across challenges, instances and client addresses, /login answers 401 {"error":"Invalid or expired challenge."} and creates no challenge, and every challenge route answers its generic 401, until the window passes. A new challenge prunes only the user's challenges that expired before the window, so failures stay counted.
  • WebAuthn security keys through github.com/go-webauthn/webauthn (D-04, D-08). The options and responses use the library's standard base64url shapes, the ones navigator.credentials (with PublicKeyCredential.parseCreationOptionsFromJSON / toJSON()) and @simplewebauthn/browser work with, inside PHP's envelopes: register/options and webauthn/options answer {options, challenge}, where options is {publicKey: …} (options.publicKey is what @simplewebauthn/browser takes as optionsJSON). Attestation is none, the timeout 60 seconds (enforced on the server too), user verification preferred. This is a deliberate break from PHP's lbuchs layout (plain base64), which no client implemented.
  • The ceremony state stays on the server; a challenge the client sends back is only a lookup key. Registration state is kept in the cache (cooler) for two minutes under the user and the challenge and is consumed once (Pull), so a replayed or foreign registration fails. The expected challenge of a login is stored on the login challenge's row (method webauthn), so webauthn/verify works only after webauthn/options for the same challenge token.
  • Credentials keep PHP's columns (credential_id and public_key as base64url, attestation type, transports, sign count, name, enabled, last used) plus credential_data, the library's credential record as JSON (flags, sign count, AAGUID, attestation), written back after every assertion. An assertion whose signature counter did not increase (a clone warning) or whose backup-eligible flag differs from the registration is refused. The user handle is the user id as 8 bytes big-endian, as in PHP.
  • A user's first key enables the webauthn method (and creates the first recovery-code set, returned once); removing the last key disables it, with the last-method cleanup. available_methods lists webauthn only while the user has an enabled key.
  • Passwordless passkey sign-in (D-14, off by default, two_factor_passwordless_login): see Passkeys below.
  • Trusted devices (off by default): with trusted_device_enabled on, a completed verify or recovery with a truthy trust_device adds trusted_device_token (64 characters, stored as SHA-256 hex with the device's "{browser} on {os}" name and address). A later /login that sends it in the body skips the challenge for trusted_device_ttl_days (30). The token is bound to its user and is read from the login body, so a social sign-in is never skipped. The status lists the devices, and the user revokes one or all of them.
  • Revocation beyond PHP (D-07): any password change (the user's own, a reset by mail or one an administrator sets) deletes the user's trusted devices inside the password write's transaction, so a failure rolls the change back. Every AccessRevokedEvent (a ban or a password change) also expires the user's open login challenges in that transaction, and a password change demotes the user's passkeys to second-factor keys (see Passkeys). Turning off the user's last method deletes their recovery codes, as PHP did, and their trusted devices.
  • Changing a second factor needs the password (beyond PHP): removing TOTP, email or a security key, registering any security key or passkey, and confirming TOTP when the user already has a second factor ask for the user's password, checked through golem15.user's failed-login throttle. factor_changes_require_password: false restores PHP's password-free contract (see Security notes).
  • A settings screen (mfa, category Users, permission golem15.mfa.access_settings) holds every key of the Configuration table except issuer, failure_cap and factor_changes_require_password. Each saved value overrides the configuration on the next request, without a restart; an empty value, an empty method or group list included, falls back to it (an untouched taglist is saved as NULL). The mode is checked against disabled, optional and enforced (a stored unknown value behaves as optional), the methods against totp, email and webauthn, and the enforce groups against the existing user group codes.
  • The admin reset (D-15): the plugin publishes userclasses.TwoFactorAdmin, so golem15.user's Users screen offers its "Reset 2FA" record action (permission golem15.users.reset_two_factor). It disables every method and clears its secret and metadata, deletes the recovery codes and trusted devices, and fires golem15.user.2fa.disabled with method all, all in the action's transaction.
  • The challenge routes share the 2fa-verify throttle bucket, 10 requests a minute per client address.

Routes

Challenge routes (no authentication, the challenge token is the credential; throttle:2fa-verify):

Route Request Answer
POST /_user/api/v1/2fa/verify challenge_token (64), method (totp or email), code (6) 200 {token, user}; 422 {error, errors}; 401 {"error":"Invalid verification code.","two_factor_failed":true}; 401 {"error":"Invalid or expired challenge."} for email without the email method or a sent code
POST /_user/api/v1/2fa/recovery challenge_token (64), code 200 {token, user}; 422 {error, errors}; 401 {"error":"Invalid recovery code.","two_factor_failed":true}
POST /_user/api/v1/2fa/email/send challenge_token (64) 200 {"message":"Verification code sent.","email":"j******[email protected]"}; 422 {error}; 401 {"error":"Invalid or expired challenge."}; 401 {"error":"Invalid challenge."}
POST /_user/api/v1/2fa/webauthn/options challenge_token (64) 200 {options: {publicKey: PublicKeyCredentialRequestOptions}, challenge}; 422 {error}; 401 {"error":"Invalid or expired challenge."} (also for a user without a key); 401 {"error":"Invalid challenge."}; 403 {"error":"WebAuthn is not available."} when the relying party is not configured
POST /_user/api/v1/2fa/webauthn/passwordless/options {} 200 {options: {publicKey: PublicKeyCredentialRequestOptions}, challenge}; 403 {"error":"Passwordless login is not available."}
POST /_user/api/v1/2fa/webauthn/passwordless/verify challenge (from the options), assertion (AuthenticationResponseJSON) 200 {token, user}; 422 {error, errors}; 401 {"error":"WebAuthn verification failed."}; 403 as options
POST /_user/api/v1/2fa/webauthn/verify challenge_token (64), assertion (AuthenticationResponseJSON) 200 {token, user}; 422 {error, errors}; 401 {"error":"Invalid or expired challenge. Request WebAuthn options first."}; 401 {"error":"WebAuthn verification failed.","two_factor_failed":true}

Management routes (jwt.auth on each route, throttle:user-api; without a principal 401 {"error":"Unauthorized"}). The password the routes below ask for goes in the JSON body (the query also works, as on the recovery-code routes, but puts it in access logs); a missing or wrong one answers 403 {"error":"Password confirmation required."} and changes nothing. With factor_changes_require_password: false the factor-changing routes need no password, as in PHP:

Route Request Answer
GET /_user/api/v1/2fa/status {enabled, enforced, methods, webauthn_credentials, recovery_codes_remaining, available_methods, trusted_device_enabled, trusted_devices}
POST /_user/api/v1/2fa/totp/setup {secret, qr_code_svg, qr_code_url}; 403 {"error":"TOTP is not available."}
POST /_user/api/v1/2fa/totp/confirm secret (base32, 16 to 64 characters), code (6), password (only when the user already has an enabled second factor) {"message":"TOTP enabled successfully.","status":…} (plus recovery_codes for a first set); 422 {error, errors}; 403 as setup; 403 {"error":"Password confirmation required."}; 422 {"error":"Invalid verification code."} (in this order)
DELETE /_user/api/v1/2fa/totp password {"message":"TOTP disabled.","status":…}; 403 {"error":"Password confirmation required."}
POST /_user/api/v1/2fa/email/enable {"message":"Email 2FA enabled.","status":…} (plus recovery_codes for a first set); 403 {"error":"Email 2FA is not available."}
DELETE /_user/api/v1/2fa/email password {"message":"Email 2FA disabled.","status":…}; 403 {"error":"Password confirmation required."}
GET /_user/api/v1/2fa/recovery-codes?password= password {"recovery_codes_remaining":N,"message":"Recovery codes cannot be viewed after creation. Regenerate to get new codes."}; 403 {"error":"Password confirmation required."}
POST /_user/api/v1/2fa/recovery-codes/regenerate password {"recovery_codes":[…],"message":"Save these codes securely. They will not be shown again."}; 403 as above
DELETE /_user/api/v1/2fa/trusted-devices/{id} id digits {"message":"Device revoked.","status":…}; 404 {"error":"Device not found."} (also for another user's device)
DELETE /_user/api/v1/2fa/trusted-devices {"message":"All trusted devices revoked.","status":…}
POST /_user/api/v1/2fa/webauthn/register/options passwordless (optional, honoured only with two_factor_passwordless_login on) {options: {publicKey: PublicKeyCredentialCreationOptions}, challenge}; 403 {"error":"WebAuthn is not available."} (method not available, or no usable relying party)
POST /_user/api/v1/2fa/webauthn/register attestation (RegistrationResponseJSON), challenge (from the options), name (optional, up to 255), password (every registration) {"message":"Security key registered successfully.","credential":{"id","name","created_at"},"status":…} (plus recovery_codes for a first set); 422 {error, errors}; 403 as above; 403 {"error":"Password confirmation required."}; 422 {"error":"Registration failed: <reason>"} with a fixed reason (invalid or expired challenge, invalid response, verification failed, credential already registered) (in this order)
DELETE /_user/api/v1/2fa/webauthn/{id} id digits, password {"message":"Security key removed.","status":…}; 403 {"error":"Password confirmation required."} (checked before the id); 404 {"error":"Credential not found."} (also for another user's key)

verify, recovery and webauthn/verify accept trust_device; /login accepts trusted_device_token.

In status, methods are the user's enabled methods, available_methods the effective global list, webauthn_credentials lists the enabled keys as PHP did, {id, name (default "Security Key"), last_used_at, created_at} with +00:00 dates, and trusted_devices (only while trusted devices are enabled) lists {id, device_name, ip_address, last_used_at, trusted_until, created_at}, last used first, with dates in Laravel's raw Carbon form 2026-10-21T12:00:00.000000Z as PHP answered them. The other dates of the API use +00:00.

With golem15.user.jwt.token_cookie on, a completed challenge sets golem15.user's session cookie and leaves token out of the body, as /login does.

Passkeys

With two_factor_passwordless_login on (settings screen or configuration, read per request), a user signs in with a passkey alone: no password and no second challenge, because the passkey with user verification is both factors (D-14).

  • Registering a passkey: register/options with passwordless: true asks the authenticator for a discoverable (resident) credential with user verification required and asks the browser for the credProps extension. The key is stored as a passkey only when it was requested, the authenticator verified the user and credProps reported rk: true; otherwise it is a second factor only (fail closed). webauthn must be an available method.
  • Signing in: passwordless/options answers discoverable options with user verification required and no allowed credentials, and keeps the ceremony state in the cache for two minutes, used once. passwordless/verify accepts only an enabled credential registered as a passkey whose user handle matches its owner, verifies the assertion with user verification, refuses a clone warning, then requires an activated account that is neither banned nor suspended, and answers {token, user} through golem15.user's own steps: FinishLogin restores a deactivated account, as a full sign-in with password and second factor would, and the login event fires with source passkey. The login gate is not consulted.
  • Every refusal (unknown or consumed challenge, a second-factor-only key, missing user verification, a foreign handle, a banned, suspended or unactivated account) answers the same 401 {"error":"WebAuthn verification failed."}; nothing tells the cases apart.
  • While the setting is off, or the mode is disabled, both routes answer 403 {"error":"Passwordless login is not available."}, and passwordless at registration is ignored. Turning the setting off does not delete passkeys: they keep working as second factors.
  • The routes sit in the 2fa-verify bucket (10 a minute per client address). Plan 04 of the phase reviews this path explicitly (D-14).
  • A password change (the user's own, a reset or an administrator's) demotes the user's passkeys to second-factor keys (DemotePasskeys, in the password write's transaction): they stay enabled as second factors, and sign in without the password again only after the user registers them as passkeys anew. Registering a key or passkey needs the user's password (unless factor_changes_require_password is off, PHP's contract, where whoever holds a stolen session can register a passkey); the demotion also keeps a passkey added that way from surviving the password change that locks the intruder out.

Configuration

Keys under golem15.mfa.*, overridable through SUMMER_GOLEM15__MFA__<KEY> (for example SUMMER_GOLEM15__MFA__TWO_FACTOR_MODE, SUMMER_GOLEM15__MFA__FAILURE_CAP__MAX; see config/config.yaml). The names are the PHP user plugin's settings names. The settings screen overrides all of them but issuer, failure_cap.* and factor_changes_require_password per request.

Key Default Meaning
two_factor_mode optional disabled (nobody is challenged), optional or enforced (reported in status only, as in PHP)
two_factor_available_methods [totp, email] Methods users may enable: totp, email, webauthn
two_factor_enforce_groups [] User group codes enforced mode applies to; empty means everyone
two_factor_email_code_ttl 10 Minutes an emailed code is announced as valid
two_factor_challenge_ttl 5 Minutes a challenge stays valid
two_factor_passwordless_login false Passwordless passkey sign-in (see Passkeys)
trusted_device_enabled false Trusted devices
trusted_device_ttl_days 30 Days a trusted device skips the challenge
two_factor_social_login false Social sign-ins go through the challenge
issuer app.name TOTP issuer
failure_cap.max, failure_cap.window_minutes 10, 15 Per-user cap on failed verifications
factor_changes_require_password true Removing a factor, registering a key or passkey and confirming TOTP beside an enabled factor need the user's password. false restores PHP's password-free contract for a frontend that cannot send the password yet, and re-opens the stolen-session exposure (see Security notes)
webauthn.rp_id host of app.url WebAuthn relying party ID
webauthn.rp_name app.name Relying party name authenticators show
webauthn.origins origins of app.url and golem15.user.frontend_url Page origins allowed to run a ceremony

WebAuthn relying party

The relying party ID must be the host of the pages that call navigator.credentials (the frontend, not the API) or a registrable suffix of it, and every such page origin must be listed in webauthn.origins. When the frontend and the API share one host, the defaults fit. When they are on different hosts (app.example.com and api.example.com), set rp_id to the shared parent (example.com) or to the frontend host, and list the frontend origin. Browsers refuse IP addresses as relying party IDs, so a site whose app.url is http://127.0.0.1:… has no relying party: the routes answer WebAuthn is not available. until rp_id names a host (localhost works for local development). Changing rp_id later orphans every registered key.

Registration state lives in the cooler cache. With the memory driver it lives in one process: an application running several instances needs the Redis cache driver, or a ceremony that starts on one instance and finishes on another fails (closed).

WebAuthn credentials of the PHP plugin are not importable as they are: PHP stored a PEM public key, while go-webauthn verifies with the COSE key and needs the credential record (flags) this plugin stores in credential_data.

Admin

The settings page mfa (permission golem15.mfa.access_settings, granted to the developer role; category Users) has four tabs: General (two_factor_mode as a dropdown with "Server configuration" as the empty choice, two_factor_available_methods and two_factor_enforce_groups as array taglists, two_factor_social_login), Codes (two_factor_email_code_ttl, two_factor_challenge_ttl, 1 to 60 minutes), Passkeys (two_factor_passwordless_login) and Trusted devices (trusted_device_enabled, trusted_device_ttl_days, 1 to 365). The values live in the singleton golem15_mfa_settings (migration 202610220005_create_golem15_mfa_settings); NULL columns fall back to the configuration, and so do empty lists, which the form stores as NULL. cabana settings forms have no radio or checkbox list, which PHP's form used, hence the dropdown and taglists.

API reference

Package mfa: PluginID, Plugin, BucketTwoFactorVerify, SettingsCode, PermissionAccessSettings. Mail templates golem15.mfa::mail.two_factor_code (Polish) and golem15.mfa::mail.two_factor_code-en, on postcard's default layout.

Package classes:

  • Config, LoadConfig(app *backpack.App) (Config, error), Effective, LoadEffective(ctx, app, db) (Effective, error), ConfigPrefix, KnownMethods, KnownModes, DefaultAvailableMethods and the other Default… constants.
  • Gate (implements userclasses.LoginGate), Database(app), ClientIP(app, r).
  • NewChallengeToken() (string, error), HashToken(raw string) string, CreateChallenge, FindChallenge, BeginAttempt, CompleteChallenge, ExpireOpenChallenges, ChallengeRevoked, FailureCount, FailureCapReached, ErrInvalidChallenge, ChallengeTokenLength, MaxAttempts.
  • RecoveryCodeAlphabet, RecoveryCodeCount, MaxRecoveryCodeLength, BcryptCost, NewRecoveryCode, GenerateRecoveryCodes, EnsureRecoveryCodes, NormalizeRecoveryCode, MatchRecoveryCode, MarkRecoveryCodeUsed, ConsumeRecoveryCode, RemainingRecoveryCodes, DeleteRecoveryCodes.
  • EmailCodeTemplate, MaxEmailSends, NewEmailCode, MaskEmail, SendEmailCode, EmailCodeMinutes, VerifyEmailCode.
  • NewTOTPSecret(issuer, account string) (secret, otpauthURL string, err error), TOTPURL, NormalizeTOTPSecret, TOTPCounter, VerifyTOTP(secret, code string, at time.Time, lastCounter int64) (int64, bool, error), TOTPPeriod, TOTPWindow.
  • QRSVG(text string, size int) (string, error).
  • EnabledMethods, MethodRow, MethodEnabled, EnableMethod, DisableMethod, AcceptTOTPCounter, TouchMethod, LastCounter, Enabled, Enforced, Status.
  • CompleteLogin(ctx, app, db, r, user) (map[string]any, error), CompleteLoginAs(ctx, app, db, r, user, source), FinishSignIn(ctx, app, db, r, user) (the token, the payload and golem15.user's FinishLogin on db, without the login event; the challenge routes run it inside the completing transaction), FireLogin(ctx, app, user, source), ChallengeUser.
  • Passkeys: BeginPasswordless(ctx, app, cache) (map[string]any, error), FinishPasswordless(ctx, app, cache, db, challenge, assertionJSON, ip) (*usermodels.User, *Assertion, error).
  • ParseDeviceName, IssueTrustedDevice, CheckTrustedDevice, RevokeTrustedDevices, RevokeTrustedDevice, TrustedDeviceList, UnknownDevice.
  • WebAuthn: WebAuthnFor(ctx, app) (*webauthn.WebAuthn, error), UserHandle(id uint) []byte, UserIDFromHandle, WebAuthnUser (NewWebAuthnUser(ctx, db, user)), BeginRegistration(ctx, app, cache, db, user, passwordless), FinishRegistration(ctx, app, cache, tx, user, challenge, attestationJSON, name), VerifyRegistration, BeginAssertion(ctx, app, db, challenge, user), FinishAssertion(ctx, app, db, challenge, user, assertionJSON) (*Assertion, error), VerifyAssertion, RecordAssertion(ctx, tx, assertion), Assertion, WebAuthnCredentialList, HasWebAuthnCredential, DeleteWebAuthnCredential, WebAuthnTimeout, WebAuthnStateTTL, WebAuthnFailure and its values ErrWebAuthnChallenge, ErrWebAuthnInvalid, ErrWebAuthnVerification, ErrWebAuthnDuplicate, ErrWebAuthnNoOptions, ErrWebAuthnNoCredentials, and ErrWebAuthnUnavailable.
  • Admin (implements userclasses.TwoFactorAdmin: HasTwoFactor, Reset; both include WebAuthn keys), OnAccessRevoked(app) (the AccessRevokedEvent listener: open challenges on every event, trusted devices and passkeys on a password change), DemotePasskeys(ctx, db, userIDs...).
  • Effective.MethodAvailable(method), Effective.ChallengeDuration().
  • Events ChallengedEvent, FailedEvent, VerifiedEvent, RecoveryUsedEvent, EnabledEvent, DisabledEvent, RecoveryRegeneratedEvent, WebAuthnRegisteredEvent, WebAuthnRemovedEvent with ChallengedEventName (golem15.user.2fa.challenged), FailedEventName, RecoveryUsedEventName, VerifiedEventName, EnabledEventName, DisabledEventName, RecoveryRegeneratedEventName, WebAuthnRegisteredEventName (golem15.user.2fa.webauthn.registered), WebAuthnRemovedEventName (golem15.user.2fa.webauthn.removed); MethodAll; Fire.

Package controllers: Verify, Recovery, EmailSend, WebAuthnOptions, WebAuthnVerify, PasswordlessOptions, PasswordlessVerify, WebAuthnRegisterOptions, WebAuthnRegister, WebAuthnRemove, Status, TOTPSetup, TOTPConfirm, TOTPDisable, EmailEnable, EmailDisable, RecoveryCodesCount, RecoveryCodesRegenerate, TrustedDeviceRevoke, TrustedDevicesRevokeAll, QRSize.

Package models: TwoFactorMethod, TwoFactorChallenge, TwoFactorRecoveryCode, TrustedDevice, WebAuthnCredential (DisplayName()), DefaultCredentialName, Settings (Fillable(), Rules(), BeforeValidate(tx)), LoadSettings(ctx, db) (*Settings, error), SettingsMethods, StringList, JSONMap, MethodTOTP, MethodEmail, MethodWebAuthn, MethodRecovery, ModeDisabled, ModeOptional, ModeEnforced, LangPrefix.

Tables (PHP's names and columns): golem15_user_two_factor_methods, golem15_user_two_factor_challenges (plus an email_sends counter), golem15_user_two_factor_recovery_codes, golem15_user_webauthn_credentials (plus credential_data and passwordless, unique credential_id) and golem15_user_trusted_devices, and the settings singleton golem15_mfa_settings. Migrations 202610220001_create_golem15_user_two_factor_methods, 202610220002_create_golem15_user_two_factor_challenges, 202610220003_create_golem15_user_two_factor_recovery_codes, 202610220004_create_golem15_user_trusted_devices, 202610220005_create_golem15_mfa_settings and 202610220006_create_golem15_user_webauthn_credentials.

Events (PHP names): golem15.user.2fa.challenged and .failed and .verified fire outside any transaction and their listener errors are logged; .enabled, .disabled, .recovery_used, .recovery_regenerated, .webauthn.registered and .webauthn.removed fire inside the write's transaction (Tx), and a listener error rolls the write back. golem15.user's login event (golem15.user.login, source two_factor) fires after a completed challenge, before .verified.

Security notes

  • Challenge tokens are stored as SHA-256 hex and the TOTP secret as AES-GCM ciphertext; neither is ever logged, and log lines carry only user ids and error types.
  • A gate error fails the sign-in closed: golem15.user answers its opaque 500 and issues no token.
  • A TOTP code is accepted once, also when two verifications race with it: the accepted step is recorded in a guarded UPDATE inside the completing transaction.
  • Recovery and email codes are bcrypt hashes; codes are never logged. A wrong recovery code costs up to ten bcrypt compares (about 0.6 s at cost 10), so the input is capped at 32 characters before any compare, the loop stops at the first match, and the bucket and the failure cap bound the rate.
  • An emailed code goes only to a user who enabled the email method, at most three per challenge.
  • Trusted-device tokens are stored as SHA-256 hex, bound to their user, expire after trusted_device_ttl_days, are off by default, and are revoked by any password change and by the removal of the last method.
  • WebAuthn ceremony state is server-side and single use; registration failures answer fixed reasons, and no attestation, assertion, challenge or library error detail is logged or answered (a clone warning logs only the credential row id).
  • Every management query is scoped by the user id from the verified session JWT; {id} routes accept digits only, and another user's device answers 404.
  • The password-confirming routes (the recovery-code routes and the factor-changing routes below) sit behind throttle:user-api (PHP's management group had no throttle), and every non-empty password they check is a login attempt in golem15.user's failed-login throttle for the client address: golem15.user.throttle.attempt_limit (5) wrong passwords suspend the account there, as at /login, and while the account is banned or suspended from any address these routes answer the 403 {"error":"Password confirmation required."} even to the right password. A missing password is refused without counting. A stolen session is therefore no password oracle.
  • totp/confirm accepts the secret the client sends back, as PHP did, but only for the caller's own account, only as base32 of 16 to 64 characters, and only with a current code from it.
  • A session token alone cannot change the user's second factors (beyond PHP, whose management routes needed only the session): DELETE totp, DELETE email, DELETE webauthn/{id}, every webauthn/register (a security key or a passkey, first factor or not) and a totp/confirm that would replace or add a factor beside an enabled one need the user's password. Validation (422) and availability (403) answers come first, so PHP's bodies for malformed requests are unchanged. A totp/confirm checks for an enabled factor again under the user's row lock inside its write, so two racing password-free confirms of a user without a factor enable exactly one secret (the other answers the 403). The paths that stay password-free are the first TOTP factor of an account that has none (the account is protected by its password alone anyway), email/enable (codes go to the account's own address), totp/setup and register/options (they store nothing) and the trusted-device routes. factor_changes_require_password: false restores PHP's contract for an application whose frontend cannot send the password yet; it re-opens the exposure: a stolen session token can then remove, replace or add second factors while it lives (the password change that ends the session still demotes passkeys, so nothing added this way signs in without the new password).
  • Activating an account with the mailed code (POST /_user/api/v1/activate-by-code) goes through this plugin's gate as a password sign-in when golem15.user consults the login gates there (sm-user-plugin after v0.1.19): with require_activation off an account can enable a second factor before it activates, and the code answers a challenge for it instead of a token.

Dependencies

  • golem15.user (git.golem15.com/golem15/sm-user-plugin v0.1.20 or later (v0.1.12 added the login gate registry, FinishLogin, IssueToken, APIArray, FireLoginEvent, TwoFactorAdmin and AccessRevokedEvent.PasswordChanged; v0.1.20 gates activate-by-code): accounts, the gate, the token, the user payload, the reset action and the password-change hook.
  • github.com/pquerna/otp v1.5.0 (packages totp, hotp), github.com/boombuler/barcode v1.1.0 (package qr) and github.com/go-webauthn/webauthn v0.18.2 (packages webauthn, protocol), decided in the project's decision note on second factors.
  • SummerCMS v0.5.0 (git.golem15.com/golem15/summercms), modules backpack, bouncer, cabana, compass, cooler, lagoon, pact, party, phrasebook, postcard, surf, wire.
  • github.com/jackc/pgx/v5 (already in the framework's graph): only pgconn.PgError, to read the configuration alone before the settings table exists and to recognise a duplicate credential.

Testing

go vet ./...
go test -short ./...          # no Docker
go test ./...                 # also the testcontainers Postgres smoke tests

TestQRSVGSmoke (no database) checks that the SVG draws exactly the dark modules of the QR matrix, at 200 by 200 pixels with a viewBox. TestTracerSmoke (Postgres) enables TOTP through setup and confirm, signs in with the password to get a challenge, completes it with a code, and checks the stored ciphertext and token hash, the single use of a challenge, the replay refusal, PHP's 422 body and the 429 of the eleventh request from one address. TestChallengeSmoke (Postgres) covers the first recovery-code set and its hashes, single use, the remaining count behind the password, regeneration, email codes only for users who enabled them (and the rendered -en mail with its capped expiry), the send cap, five attempts per challenge, exactly one token from 20 parallel verifications, the failure cap and its window, and the cleanup when the last method goes. TestTrustedSettingsSmoke (Postgres) covers trusted devices (the stored hash and device name, the skipped challenge, another user's and an expired token, the revoke routes, the setting off), revocation on a password change and its rollback, the settings screen saved through the admin API applying on the next request, the social toggle, the allow-lists, the status keys and Carbon dates, and the published reset service.

TestWebAuthnCeremonySmoke (no database) runs the plugin's ceremony steps against a virtual authenticator (an ECDSA P-256 key answering with attestation none): an IP-address app.url is no relying party, creation options ask for no attestation, and assertions are refused for a counter that did not increase, a changed backup-eligible flag, missing user verification where it is required, a foreign origin and a wrong challenge. TestWebAuthnSmoke (Postgres) registers a key through the API (PHP's answer, the first recovery codes, the stored record), refuses reused registration state, lists the key in the status, signs in with it as the second factor (verify before options refused, the sign count written back, a clone refused), removes the last key (the method turns off and the next login is not challenged), and checks the admin reset and the 403 while webauthn is not available.

TestPasswordlessSmoke (Postgres) checks both passkey routes answer 403 while the setting is off (and passwordless at registration is ignored), a passkey registered through the API signs its user in with one login event of source passkey and its record written back, and the one 401 for a second-factor key, a key registered without credProps, an assertion without user verification, a foreign user handle, a banned or unactivated user and a reused challenge.

The unit tests pin one decision each. Without a database: TestTOTP (the one-step window, step boundaries and replay refusal on injected clocks, the code form, secret normalization, the otpauth URL), TestQRSVG (the level-M matrix for several text lengths inside the quiet zone, the size attributes, well-formed XML), TestRecoveryCodeFormat, TestMaskEmail, TestEmailExpiryMinutes, TestWebAuthnShapes (the relying party, the plugin's creation and passkey request options, the registration state used once by its own user, the passkey flag, the user handle; it runs BeginRegistration on a dry-run GORM handle) and TestRoutesAndBuckets (the 20 routes with their buckets and jwt.auth, and the 2fa-verify bucket keyed per client address). On Postgres: TestGate, TestChallengeLifecycle, TestFailureCap, TestRecovery, TestEmailCode (including that no mailed code or challenge token reaches a log line), TestTrustedDevice, TestRevocation, TestCompletionFailureSpendsNothing (a broken session-cookie block or a failing user payload answers 500 with the challenge open, the recovery code unspent, no trusted device and no event, and the retry completes), TestPasswordConfirmationThrottle (wrong confirmations suspend the account through golem15.user's throttle, a suspended account is refused even the right password, a right one resets the count), TestFactorChangesNeedPassword (the five factor-changing routes refuse a missing or wrong password with PHP's 403 and change nothing, a wrong one counts in the throttle, a suspended account is refused the right one, the first factor of a user with none needs no password, two racing password-free confirms enable one secret, validation and availability answer first, and factor_changes_require_password: false restores the password-free contract), TestChallengeAfterRevocation (a ban, a suspension at the verifying address and a later tokens_valid_after refuse a pending challenge without spending the factor; a password change expires the user's open challenges), TestSettings (including the settings form's round trip keeping the configuration), TestStatusShape, TestAdminReset (through golem15.user's Users screen), TestTokensAtRest, TestMigrations, TestWebAuthn, TestPasswordless (including that a password change demotes the user's passkeys), TestPHPErrorBodies (every status and body of PHP's two route tables) and TestEveryLoginPathIsGated, which lists every place golem15.user and this plugin mint a session token (read from the user plugin source at USER_PLUGIN, else the directory go list -m reports) and drives each first-factor path of a TOTP user to a challenge, activate-by-code included.

TestPHPMethodMap (no database) keeps testdata/PHP_METHOD_MAP.md honest: it maps every test method of the PHP user plugin's tests/security/AuthenticationTest.php (listed in testdata/php_methods.txt, compared with the live file when PHASE196_PHP_AUTH or the default path has it) to the Go test that covers it or to not-applicable with its reason, and checks that each named Go test exists in its repository (this one; the user plugin at USER_PLUGIN or the directory go list -m reports; the social login plugin at SOCIALLOGIN_PLUGIN or the sibling checkout, skipped when absent). TestPHPUser005 (no database) ports the USER-005 type-confusion check: the mode is a typed string that the configuration and the settings form accept only as one of the three modes.

Versions

VersionFrameworkRequiresReleased
v0.2.1v0.6.5golem15.user v0.1.202026-11-16
v0.2.0v0.6.0golem15.user v0.1.202026-11-05
v0.1.3v0.6.0golem15.user v0.1.122026-10-30