Skip to main content

Self-service staff password reset

How staff recover a forgotten password, or look up a forgotten username, without an administrator. A password reset always requires a code sent by SMS to the account's mobile number, even when the account does not use 2FA at login. Implemented in include/user_system.class.php (a constructor hook plus _processPasswordReset() and friends) with templates templates/forgot_password_form.template.php, templates/forgot_username_form.template.php and templates/reset_password_form.template.php.

Flow​

  1. Request — the staff login page (gated by PASSWORD_RESET_ENABLED, default on) shows "Forgot your password?". Posting a username arms a reset: a 32-char token is generated (generate_random_string(), openssl-backed) and only its jethro_password_hash() is stored in staff_member.resethash with resetexpires = NOW() + INTERVAL 24 HOUR; the link BASE_URL_ABSOLUTE/?reset_password=TOKEN&username=... is emailed via Emailer to the address on the account (From: MEMBER_REGO_EMAIL_FROM_ADDRESS, else the first sysadmin's address, mirroring _notifySysadmins()).
  2. Accept email token — opening the emailed link validates the token and expiry, rotates the session ID and binds $_SESSION['password_reset'] to that account and exact resethash. GETs never send SMS or contact the SMS provider. No account can reach the new-password form on email proof alone.
  3. Send SMS explicitly — every armed request requires an SMS code; the account's login 2FA policy does not change this. The email-authenticated user presses Send code. A same-origin POST atomically reserves the code hash and resetsmssent before any gateway lookup/send. A send/resend is allowed at most once per 60 seconds for that request across all browser sessions. Missing mobile, blocked SMS or gateway failure gives an actionable error, never email-only fallback. Failure clears only that challenge hash and retains the cooldown timestamp.
  4. Verify SMS gate — a separate POST checks the six-digit code with plain password_verify(). Codes expire ten minutes after their reserved send. resetsmsattempts allows two total checks per request; resends do not restore attempts. A transaction and account-row lock serialize verification, so an earlier wrong check cannot scrap a correct final check in another session. Two incorrect codes scrap the request. Success rotates the session ID and stores the verified challenge hash in this reset session; it does not log the user in.
  5. Choose new password — only the verified session sees the password form; direct completion POSTs must pass the same gate. A resend or code expiry revokes earlier verification. Staff_Member::processPasswordField() enforces the normal password policy. The final conditional update checks the armed request, verified challenge and expiry again, saves the password, and clears the reset so only one completion wins.
  6. Password login — the user still enters the new password normally. Successful completion sets $_SESSION['2fa_verified'] with the account ID and a five-minute expiry. The next password-authenticated login consumes it, skipping another SMS only for that account. Mismatch, expiry, incorrect-password login, logout, cancellation or staging another reset cannot preserve that credit. No durable trust cookie is set.

The active account and request identity/expiry are checked at every reset stage, including rendering. Login's 2FA policy (2FA_REQUIRED_PERMS, 2FA_ENABLED) does not weaken a reset: the SMS challenge applies to every request, and changing that policy neither removes nor adds it. If no code can be sent — no SMS gateway, no usable sender, no mobile number on the account, or SMS_2FA_BLOCK_MESSAGES — the reset cannot complete; an administrator must reset the password instead. The username reminder remains email-only.

Recovery uses $_SESSION['password_reset'], not login's $_SESSION['2fa']['pending_user']: the latter calls _logUserIn() when its code is accepted, which would authenticate the account before the password was reset. The short-lived 2fa_verified marker is checked only after normal password and active-account checks. It deliberately has no password-fingerprint binding; even if the password changes again during its five-minute lifetime, login still requires the current password.

Username reminder​

The login page also offers "Forgot your username?" (same PASSWORD_RESET_ENABLED gate, needed by staff who forgot the username that the reset form asks for). Posting an email address emails all active, non-archived staff usernames registered to that address — _person.email is not unique, so the email may list several. The response is identical whether or not the address matches an account, so the form reveals nothing to a probe. The reminder goes to the stored address, and only for an exact (ASCII case-insensitive) match: the _person.email collation folds accents, so staff@exämple.org would otherwise match staff@example.org and mail the usernames to whoever owns the look-alike domain. Each account is reminded at most once an hour (staff_member.usernamereminded, claimed with a conditional UPDATE), so neither a looping requester nor fresh sessions can mail-bomb an address. Entry point: _processForgotUsername(), template templates/forgot_username_form.template.php.

Security properties​

PropertyMechanism
No plaintext credentials at restOnly bcrypt hashes of the token and SMS code are stored. (_person.resethash, the member-portal flow, stores that token raw — an older pattern; do not copy it here.)
Tokens and codes checked with plain password_verify()Not jethro_password_verify(), which also accepts a support override password at login; that must never stand in for a reset token or SMS code
Every reset needs the second factorThe SMS challenge is unconditional: an account with 2FA off at login still verifies a code, and no email proof unlocks the password form. Trust cookies never waive a reset gate. Recent successful reset SMS verification can satisfy exactly one password-authenticated login in the same session for five minutes
SMS code guessingTwo total code checks are counted on the account row, serialized with a transaction and row lock. Fresh sessions and resends do not buy more guesses. Password-form POSTs cannot verify codes or consume guesses
Single-use, expiringresetexpires > NOW() guards every check; completion clears the request; the reset session only works for the request it validated, so a completed, scrapped or re-armed request (or any password change) voids it
Voided by password changesStaff_Member::save() (My Account, admin edits, bin/jethro_resetpassword) and the login-time password upgrade clear any outstanding request
Disabled accountsOnly active = 1 accounts can request, validate or complete a reset
No enumerationReset-request responses are identical for known/unknown usernames and email-send failures (unknown requests burn a bcrypt hash and verify to even out CPU time); invalid links get one generic error. SMTP timing can still distinguish a successful email send. SMS errors are shown only after a valid emailed token has established the reset session
Request-forgery protectionAll POSTs pass request_origin_is_proven_current(); refusals are logged with log_unproven_login_origin('staff') (see Request origin protection)
Host-header poisoningThe link is built from BASE_URL_ABSOLUTE: set an absolute BASE_URL (or ALLOWED_HOSTS) in conf.php, or a forged Host header can point the emailed link, token included, at another host
Session fixationSession ID rotates at email-token acceptance, SMS verification and successful completion; normal login rotates it again
SMS/email bombingUsername-only requests send only hourly-throttled email. A valid emailed token and explicit same-origin POST are required to send SMS; GETs and link scanners cannot send. Each request has a database-backed 60-second send cooldown, retained on transport failure
Dev/demo kill switchSMS_2FA_BLOCK_MESSAGES also blocks reset codes: resets are refused and logged, not sent
Auditerror_log PASSWORD RESET REQUESTED / COMPLETED / FAILED lines with username and remote IP, ABANDONED with the account id (matching the LOGIN SUCCESS/FAILURE convention), plus USERNAME REMINDER SENT / FAILED and _2faLog() notes; tokens and codes are never logged

Schema​

staff_member stores the following reset/reminder state outside the ORM:

ColumnPurpose
resethashBcrypt hash of the single-use emailed token
resetexpiresRequest expiry, 24 hours after arming
resetsmshashBcrypt hash of the current SMS challenge; null before sending or after a failed send
resetsmssentLast reserved send time: 60-second cooldown and ten-minute code lifetime
resetsmsattemptsTotal code checks against the request, never reset by resending
usernameremindedLast username reminder, for the hourly throttle

Fresh installs use Staff_Member::getInitSQL(); existing installs use the idempotent upgrades/2026-upgrade-to-2.40.sql. The fields are deliberately absent from Staff_Member::_getFields() and managed with raw SQL.

Notes​

  • Recovery never logs the account in. Its verified SMS factor can satisfy the immediate next password login once, within five minutes, in the completing browser session only. Later logins follow ordinary 2FA/trust-cookie policy.
  • No admin page shows a pending reset: the columns are outside the ORM, so an administrator cannot see or clear one from the configuration pages. Editing the account's password (Staff_Member::save()) clears it.
  • A lost phone (or an install with no working SMS gateway/sender) still needs an administrator — bin/jethro_resetpassword remains the admin CLI fallback.
  • PASSWORD_RESET_ENABLED (conf.php, default on) hides the login-page link and disables all reset request handling when set to false. Set it false if SMS cannot be sent reliably: a reset that cannot reach the code step is a dead end.
  • The reset template keeps its submit action in normal flow above the cancellation separator. Use text-right, not pull-right, so the following <hr> cannot wrap beside the button.

Functional testing​

tests/functional/email/password-reset.spec.ts exercises the forgot-username reminder and asserts that email proof alone never unlocks the password form: that project configures no SMS gateway, so the code request fails closed. tests/functional/sms/sms-2fa-password-reset.spec.ts uses its own transient people and staff accounts to exercise SMS-gated recovery, including a reset by an account whose login does not use 2FA. It checks no SMS on requests, link GETs or reloads; rejects forged password POSTs; verifies cross-session send cooldown and attempt limits; checks resend/expiry and session-bound verification; completes a single-use reset; and checks immediate-login credit versus ordinary 2FA after logout or in another browser. The link comes from MailPit and the code from the SMS mock's lastPost. Unit tests cover the unconditional SMS gate, challenge binding, and the next-login marker's account, expiry, logout and single-use boundaries.

The SMS scenario's .conf sets 2FA_SENDER_ID = 'Jethro' and 2FA_REQUIRED_PERMS so the login-credit path is also exercised. Its .smsmock.php selects ordinary Cellcast mock behaviour. It does not register a sender: the mock accepts sends without enforcing upstream sender registration. Tests that need pre-existing sender IDs can seed the mock profile's account state (setBusinessNames(), setSenders() or setSenderIds()), rather than inventing an upstream registration endpoint. No real provider is contacted. See Functional test harness.

The mock's profile information page links directly to these metadata endpoints. Use jethro/smsmockserver v1.0.1 or later: v1.0.0 generated relative links that could duplicate the provider path (for example cellcast/cellcast/meta/lastPost). The corrected links preserve the mock mount and work with or without a trailing slash for Cellcast, 5CentSMS and MobileMessage.

Devbox demo instance​

devbox.d/demo/conf.php points each supported SMS provider at its default mock account: /smsmockserver/cellcast, /smsmockserver/5centsms or /smsmockserver/mobilemessage. The dependency's bundled profiles/{cellcast,5centsms,mobilemessage}.smsmock.php files configure a balance of 12345 and StDemos: ACMA-approved for Cellcast and 5CentSMS, and an alphanumeric sender for MobileMessage. This is mock provider account state, not Jethro demo SQL data; no demo-data edit or database reload is needed. Functional scenarios and recording comparisons retain their separate profiles.

The demo config also sets 2FA_SENDER_ID = 'StDemos', shared by login and reset codes. This explicit setting matters for MobileMessage: its sender-list API has no ACMA approval flag, so the automatic pre-login fallback cannot select its IDs. The provider remains selectable in System Configuration; ordinary SMS sender selection is not forced.

The default accounts load automatically from the dependency's bundled profiles. No extra demo profile directory is required in SMSMOCK_PROFILES. Restart PHP-FPM after changing that environment setting in an already-running checkout.

To simulate a reset, use an active staff account with an email address and a mobile number (every reset requires an SMS code, even when login does not use 2FA). Open ?forgot_password=1, request the reset, then read the link in /emailmockserver/. Read the captured SMS via /smsmockserver/cellcast/meta/lastPost, /smsmockserver/5centsms/meta/lastPost or /smsmockserver/mobilemessage/meta/lastPost, matching the selected provider. SMS codes go only to the mock, not a handset. SMS_2FA_BLOCK_MESSAGES must remain off for resets to complete.

If MailPit's Delete action reports a CORS violation, check that the nginx /emailmockserver/ proxy preserves Host with its browser-facing port. See MailPit proxy requirements; do not disable origin checks on the captured password-reset mailbox.