git clone https://garage44.eu/jeroen/cartopolis.gitcartopolis-agent · 2026-11-30T17:14:36Z
feat(accounts): forgot your password? through a mailed link A person who forgot their password could only ask an operator. Now /forgot on the web page (linked under every password field, and from the app's sign-in card, which opens it in the browser) mails a one-hour link to the account's confirmed address; /reset-password spends it on a new password. - Every outcome of /api/password/forgot answers 202, and it counts against the registration limits, so the form tells nobody whether an address has an account. - An unconfirmed address gets its confirmation link again instead. - A reset signs the account out everywhere (sessions and access tokens) and clears the wrong-password count for the name. - Tokens are stored hashed in their own table (V52, reserved).
crates/atlas/web/mock.ts | 14 ++
.../web/src/components/elements/signin/signin.tsx | 11 +
crates/atlas/web/src/components/main/main.tsx | 4 +
.../atlas/web/src/components/pages/chat/chat.tsx | 1 +
.../atlas/web/src/components/pages/login/login.css | 7 +
.../web/src/components/pages/password/password.tsx | 207 +++++++++++++++++
crates/atlas/web/src/lib/signup.ts | 25 ++
crates/cartopolis/src/systems/gui/lib_login.rs | 24 ++
crates/cartopolis/src/systems/gui/login_screen.rs | 11 +
.../simulator/migrations/V52__password_resets.sql | 20 ++
crates/simulator/src/auth.rs | 8 +
crates/simulator/src/http.rs | 142 ++++++++++++
crates/simulator/src/lib.rs | 1 +
crates/simulator/src/mail.rs | 24 ++
crates/simulator/src/password_reset.rs | 256 +++++++++++++++++++++
crates/simulator/src/registration.rs | 8 +
crates/simulator/tests/integration/http_surface.rs | 88 +++++++
docs/notes/self-service-accounts.md | 26 ++-
18 files changed, 872 insertions(+), 5 deletions(-)
diff --git a/crates/atlas/web/mock.ts b/crates/atlas/web/mock.ts
index dfa83dcf..cefacf75 100644
--- a/crates/atlas/web/mock.ts
+++ b/crates/atlas/web/mock.ts
@@ -1090,6 +1090,20 @@ export async function mockApi(req: Request, url: URL): Promise<Response | null>
if (p === '/api/register/resend' && method === 'POST') {
return json({ok: true})
}
+ if (p === '/api/password/forgot' && method === 'POST') {
+ return new Response(null, {status: 202})
+ }
+ if (p === '/api/password/reset' && method === 'POST') {
+ // Any token works but `expired`, so the refusal can be looked at too.
+ const b = await body<{password: string; token: string}>(req)
+ if (b.token === 'expired') {
+ return refuse(410, 'that link has expired — ask for a new one')
+ }
+ if ((b.password ?? '').length < registration.min_password_length) {
+ return refuse(400, `password must be at least ${registration.min_password_length} characters`)
+ }
+ return new Response(null, {status: 204})
+ }
// ── Signing in through another site (unauthenticated half) ───────────
if (parts[1] === 'auth' && parts[3] === 'start' && method === 'GET') {
diff --git a/crates/atlas/web/src/components/elements/signin/signin.tsx b/crates/atlas/web/src/components/elements/signin/signin.tsx
index 9af32325..d68a1721 100644
--- a/crates/atlas/web/src/components/elements/signin/signin.tsx
+++ b/crates/atlas/web/src/components/elements/signin/signin.tsx
@@ -63,6 +63,17 @@ export class PlayerSignIn extends MithrilComponent<SignInAttrs> {
type="password"
validation={this.v.password}
/>
+ <p class="auth__forgot">
+ <a
+ href="/forgot"
+ onclick={(e: Event) => {
+ e.preventDefault()
+ m.route.set('/forgot')
+ }}
+ >
+ Forgot your password?
+ </a>
+ </p>
<Button disabled={!this.v.$valid} loading={s.busy} type="submit" variant="primary">
Sign in
</Button>
diff --git a/crates/atlas/web/src/components/main/main.tsx b/crates/atlas/web/src/components/main/main.tsx
index 7469263d..e92f8356 100644
--- a/crates/atlas/web/src/components/main/main.tsx
+++ b/crates/atlas/web/src/components/main/main.tsx
@@ -6,6 +6,7 @@ import {Building} from '@/components/pages/building/building'
import {Chat} from '@/components/pages/chat/chat'
import {Buildings} from '@/components/pages/buildings/buildings'
import {PublicCommunity, PublicPerson} from '@/components/pages/public/public'
+import {Forgot, ResetPassword} from '@/components/pages/password/password'
import {Register} from '@/components/pages/register/register'
import {Verify} from '@/components/pages/verify/verify'
import {Tokens} from '@/components/pages/tokens/tokens'
@@ -101,6 +102,9 @@ export function mountRoutes(root: Element) {
'/': chatPage,
'/register': page(Register),
'/verify': page(Verify),
+ // "Forgot your password?", and where its mailed link lands.
+ '/forgot': page(Forgot),
+ '/reset-password': page(ResetPassword),
'/buildings': page(Buildings),
// The old path, from before a person owned buildings rather than one
// house; links to it are in sent mail.
diff --git a/crates/atlas/web/src/components/pages/chat/chat.tsx b/crates/atlas/web/src/components/pages/chat/chat.tsx
index fd8a1cd1..2a46d080 100644
--- a/crates/atlas/web/src/components/pages/chat/chat.tsx
+++ b/crates/atlas/web/src/components/pages/chat/chat.tsx
@@ -1562,6 +1562,7 @@ export class Chat extends MithrilComponent {
type="password"
validation={this.v.password}
/>
+ <p class="auth__forgot">{Link('/forgot', 'Forgot your password?')}</p>
<div class="auth__actions">
<Button disabled={!this.v.$valid} loading={s.busy} type="submit" variant="primary">
Sign in
diff --git a/crates/atlas/web/src/components/pages/login/login.css b/crates/atlas/web/src/components/pages/login/login.css
index 5209c7e5..92a081c3 100644
--- a/crates/atlas/web/src/components/pages/login/login.css
+++ b/crates/atlas/web/src/components/pages/login/login.css
@@ -52,3 +52,10 @@
.auth + * {
margin-top: var(--m-space-5);
}
+
+/* "Forgot your password?", tucked under the password field it is about. */
+.auth__forgot {
+ margin-top: calc(-1 * var(--m-space-2));
+ font-size: var(--m-font-size-sm);
+ text-align: right;
+}
diff --git a/crates/atlas/web/src/components/pages/password/password.tsx b/crates/atlas/web/src/components/pages/password/password.tsx
new file mode 100644
index 00000000..35f133e7
--- /dev/null
+++ b/crates/atlas/web/src/components/pages/password/password.tsx
@@ -0,0 +1,207 @@
+import m, {MithrilComponent} from '@garage44/mithril'
+import {Alert, Button, Card, FieldText} from '@garage44/mithril/components'
+import {validation, validations} from '@garage44/mithril/validation'
+
+import {$s} from '@/app'
+import {COMMUNITY} from '@/lib/base'
+import {bind, local} from '@/lib/reactive'
+import {forgotPassword, resetPassword, tokenFromLocation} from '@/lib/signup'
+
+/**
+ * "Forgot your password?": an address in, a link out.
+ *
+ * Says the same thing whatever the address, as the server does — "no account
+ * has that address" would tell anyone whether a person is here. The mail
+ * names the account, for the person who forgot that too.
+ */
+export class Forgot extends MithrilComponent {
+ s = local({busy: false, email: '', sent: false})
+
+ v = validations({
+ email: validation(bind(this.s, 'email'))
+ .required('That does not look like an email address.')
+ .check((value) => {
+ const address = value.trim()
+ const at = address.lastIndexOf('@')
+ return at >= 1 && address.slice(at + 1).includes('.')
+ }, 'That does not look like an email address.'),
+ })
+
+ send = async (e: Event) => {
+ e.preventDefault()
+ const s = this.s
+ if (s.busy || !this.v.$validate()) {
+ return
+ }
+ s.busy = true
+ s.sent = await forgotPassword(s.email.trim())
+ s.busy = false
+ }
+
+ view() {
+ const s = this.s
+
+ if (s.sent) {
+ return (
+ <div class="auth">
+ <Card title="Check your inbox">
+ <Alert tone="success">
+ If <b>{s.email.trim()}</b> belongs to an account here, we've sent it a link to choose a
+ new password. It works once and expires in an hour.
+ </Alert>
+ <p class="auth__lede">
+ Nothing arrived? It may be in a spam folder, or the account may use another address.
+ </p>
+ <div class="auth__actions">
+ <Button onclick={() => (s.sent = false)} variant="ghost">
+ Try another address
+ </Button>
+ <Button onclick={() => m.route.set(COMMUNITY)} variant="ghost">
+ Back to sign in
+ </Button>
+ </div>
+ </Card>
+ </div>
+ )
+ }
+
+ return (
+ // A form, so Enter or the phone's Go key sends the link.
+ <form class="auth" novalidate onsubmit={this.send}>
+ <Card title="Forgot your password?">
+ <p class="auth__lede">
+ Enter the email address of your account, and we'll send a link to choose a new password.
+ </p>
+ <FieldText
+ autocomplete="email"
+ disabled={s.busy}
+ label="Email"
+ model={bind(s, 'email')}
+ type="email"
+ validation={this.v.email}
+ />
+ <div class="auth__actions">
+ <Button disabled={!this.v.$valid} loading={s.busy} type="submit" variant="primary">
+ Send the link
+ </Button>
+ <Button disabled={s.busy} onclick={() => m.route.set(COMMUNITY)} variant="ghost">
+ Back to sign in
+ </Button>
+ </div>
+ <p class="auth__lede">
+ Signed up through Discord, Google or another site? Sign in there again instead — there is no
+ password to reset.
+ </p>
+ </Card>
+ </form>
+ )
+ }
+}
+
+type Phase = 'choosing' | 'done' | 'no-token'
+
+/**
+ * Where the link in the mail lands: choose the new password.
+ *
+ * Nothing is spent on opening the page — only the button does that — so a mail
+ * scanner fetching the link changes nothing.
+ */
+export class ResetPassword extends MithrilComponent {
+ s = local({busy: false, password: '', phase: 'choosing' as Phase, token: ''})
+
+ v = validations({
+ password: validation(bind(this.s, 'password'))
+ .required()
+ .rule((value) => {
+ const min = $s.registration?.min_password_length ?? 0
+ return value.length >= min ? null : `The password needs at least ${min} characters.`
+ }),
+ })
+
+ oninit() {
+ const token = tokenFromLocation(window.location.search)
+ this.s.token = token
+ if (!token) {
+ this.s.phase = 'no-token'
+ }
+ }
+
+ save = async (e: Event) => {
+ e.preventDefault()
+ const s = this.s
+ if (s.busy || !this.v.$validate()) {
+ return
+ }
+ s.busy = true
+ const ok = await resetPassword(s.token, s.password)
+ s.busy = false
+ if (ok) {
+ s.password = ''
+ s.phase = 'done'
+ }
+ }
+
+ view() {
+ const s = this.s
+
+ if (s.phase === 'done') {
+ return (
+ <div class="auth">
+ <Card title="Password changed">
+ <Alert tone="success">
+ Your new password works now, here and in the app. You've been signed out everywhere
+ else.
+ </Alert>
+ <div class="auth__actions">
+ <Button onclick={() => m.route.set(COMMUNITY)} variant="primary">
+ Sign in
+ </Button>
+ </div>
+ </Card>
+ </div>
+ )
+ }
+
+ if (s.phase === 'no-token') {
+ return (
+ <div class="auth">
+ <Card title="Choose a new password">
+ <Alert title="That link is incomplete" tone="danger">
+ Open the link from the mail in full, or ask for a new one.
+ </Alert>
+ <div class="auth__actions">
+ <Button onclick={() => m.route.set('/forgot')} variant="primary">
+ Ask for a new link
+ </Button>
+ </div>
+ </Card>
+ </div>
+ )
+ }
+
+ const min = $s.registration?.min_password_length
+ return (
+ <form class="auth" novalidate onsubmit={this.save}>
+ <Card title="Choose a new password">
+ <FieldText
+ autocomplete="new-password"
+ disabled={s.busy}
+ help={min ? `At least ${min} characters.` : undefined}
+ label="New password"
+ model={bind(s, 'password')}
+ type="password"
+ validation={this.v.password}
+ />
+ <div class="auth__actions">
+ <Button disabled={!this.v.$valid} loading={s.busy} type="submit" variant="primary">
+ Save the password
+ </Button>
+ <Button disabled={s.busy} onclick={() => m.route.set('/forgot')} variant="ghost">
+ Ask for a new link
+ </Button>
+ </div>
+ </Card>
+ </form>
+ )
+ }
+}
diff --git a/crates/atlas/web/src/lib/signup.ts b/crates/atlas/web/src/lib/signup.ts
index b06abd65..b2e20da4 100644
--- a/crates/atlas/web/src/lib/signup.ts
+++ b/crates/atlas/web/src/lib/signup.ts
@@ -81,6 +81,31 @@ export async function resend(email: string): Promise<boolean> {
}
}
+/**
+ * Ask for a link to choose a new password. Like `resend`, the server answers
+ * success whatever the address, so this can only say what was done.
+ */
+export async function forgotPassword(email: string): Promise<boolean> {
+ try {
+ await signupApi.post('/api/password/forgot', {email})
+ return true
+ } catch (e) {
+ report(e, 'Could not send a link')
+ return false
+ }
+}
+
+/** Spend the mailed link on a new password; the server signs the account out everywhere. */
+export async function resetPassword(token: string, password: string): Promise<boolean> {
+ try {
+ await signupApi.post('/api/password/reset', {password, token})
+ return true
+ } catch (e) {
+ report(e, 'Could not set that password')
+ return false
+ }
+}
+
/**
* Sign back in with the password, for the person who registered some other day.
*
diff --git a/crates/cartopolis/src/systems/gui/lib_login.rs b/crates/cartopolis/src/systems/gui/lib_login.rs
index dd84ace6..3ee6439f 100644
--- a/crates/cartopolis/src/systems/gui/lib_login.rs
+++ b/crates/cartopolis/src/systems/gui/lib_login.rs
@@ -128,6 +128,8 @@ struct State {
error: Option<String>,
offered: Vec<Offered>,
external_error: Option<String>,
+ /// The server has a web page to send somebody to: to sign up, or to
+ /// choose a new password.
register: bool,
/// The server, named at the foot of the card.
server: Option<String>,
@@ -161,6 +163,7 @@ enum Act {
Reopen,
Cancel,
Register,
+ Forgot,
ChangeServer,
}
@@ -351,6 +354,11 @@ fn act(a: Act, screen: &mut LoginScreen, session: &mut SessionState, store: &mut
crate::systems::data_layers::open_url(&url);
}
}
+ Act::Forgot => {
+ if let Some(url) = screen.forgot_url() {
+ crate::systems::data_layers::open_url(&url);
+ }
+ }
Act::ChangeServer => screen.edit_server = true,
}
}
@@ -473,6 +481,21 @@ fn form(l: &Live) -> View {
}
}
};
+ // A way back in for somebody who forgot the password: the server's own page,
+ // which mails a link.
+ let forgot = {
+ let l = l.clone();
+ move || -> View {
+ if !l.state.get().register {
+ return View::Empty;
+ }
+ view! {
+ <div style="display: flex; justify-content: flex-end">
+ <Button variant=Variant::Ghost size=Size::Sm onclick={l.act(Act::Forgot)}>"Forgot your password?"</Button>
+ </div>
+ }
+ }
+ };
// A way in for somebody with no account: the server's own page.
let register = {
let l = l.clone();
@@ -526,6 +549,7 @@ fn form(l: &Live) -> View {
view! {
<FieldText model={l.username.clone()} label="Account name" placeholder="your account name" autocomplete="username" onkeydown={Some(enter)} id="signin-user" />
<FieldText model={l.password.clone()} r#type=TextType::Password label="Password" autocomplete="current-password" onkeydown={Some(enter_password)} id="signin-password" />
+ {forgot}
<FieldSwitch model={l.remember.clone()} label="Stay signed in on this device" id="signin-remember" />
{sign_in}
{under}
diff --git a/crates/cartopolis/src/systems/gui/login_screen.rs b/crates/cartopolis/src/systems/gui/login_screen.rs
index 55819188..21d5639f 100644
--- a/crates/cartopolis/src/systems/gui/login_screen.rs
+++ b/crates/cartopolis/src/systems/gui/login_screen.rs
@@ -286,6 +286,17 @@ impl LoginScreen {
self.api_base().map(|base| format!("{base}/register"))
}
+ /// Where the server lets somebody choose a new password — its web page's
+ /// `/forgot`, which mails a link — under the same conditions as
+ /// [`Self::register_url`].
+ #[must_use]
+ pub fn forgot_url(&self) -> Option<String> {
+ if !crate::systems::data_layers::open_url_supported() {
+ return None;
+ }
+ self.api_base().map(|base| format!("{base}/forgot"))
+ }
+
/// The request for a session the browser's round trip left for the app.
fn token_request(&mut self, token: String, username: String) -> Option<SessionRequest> {
let server = normalize_server(&self.server);
diff --git a/crates/simulator/migrations/V52__password_resets.sql b/crates/simulator/migrations/V52__password_resets.sql
new file mode 100644
index 00000000..597c046f
--- /dev/null
+++ b/crates/simulator/migrations/V52__password_resets.sql
@@ -0,0 +1,20 @@
+-- Outstanding "forgot your password?" links (`password_reset.rs`).
+--
+-- A table of its own rather than more rows in `email_verifications`: that one is
+-- emptied per principal whenever a confirmation link is (re)sent, and a reset
+-- link is a stronger credential — it sets the password — so it gets a shorter
+-- life and must not be spendable as a confirmation, nor the other way round.
+--
+-- Hashed for the reason sessions and verification links are: a copy of this
+-- database must not be a bag of ways into other people's accounts. Unix seconds,
+-- like those tables. A row is deleted on use, when a newer link is asked for and
+-- once expired, so the table is the set of links currently outstanding.
+CREATE TABLE IF NOT EXISTS password_resets (
+ token_hash TEXT PRIMARY KEY,
+ principal TEXT NOT NULL,
+ created_at INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS password_resets_principal
+ ON password_resets (principal);
diff --git a/crates/simulator/src/auth.rs b/crates/simulator/src/auth.rs
index fbae6504..8503801e 100644
--- a/crates/simulator/src/auth.rs
+++ b/crates/simulator/src/auth.rs
@@ -905,6 +905,14 @@ impl Sessions {
}
}
+ /// Forget the wrong passwords counted against `username`: its password was
+ /// just replaced through a mailed link (`password_reset`), so the guesses
+ /// were at one that no longer exists, and the person must not be locked
+ /// out of the new one for the rest of the window.
+ pub fn forgive_failed_logins(&self, username: &str) {
+ self.failed_logins.forget(&username.trim().to_lowercase());
+ }
+
/// Issue a fresh random opaque token bound to a principal + its username.
/// Record that `principal` has just signed in again with another account
/// on purpose, to confirm it is them (`signin`, purpose `reauth`).
diff --git a/crates/simulator/src/http.rs b/crates/simulator/src/http.rs
index ae8750f9..5573e7df 100644
--- a/crates/simulator/src/http.rs
+++ b/crates/simulator/src/http.rs
@@ -118,6 +118,8 @@ pub fn router(state: HttpState) -> Router {
.route("/api/register", get(registration_status).post(register))
.route("/api/register/verify", post(verify_registration))
.route("/api/register/resend", post(resend_verification))
+ .route("/api/password/forgot", post(forgot_password))
+ .route("/api/password/reset", post(reset_password))
.route("/api/buildings/search", get(search_buildings))
.route("/api/buildings/claim", post(claim_building))
.route("/api/buildings/mine", get(my_buildings))
@@ -667,6 +669,146 @@ async fn resend_verification(
Ok(accepted())
}
+// ---------------------------------------------------------------------------
+// Forgot your password?
+// ---------------------------------------------------------------------------
+
+#[derive(Deserialize)]
+struct ForgotRequest {
+ email: String,
+}
+
+/// Mail a link to choose a new password (`crate::password_reset`).
+///
+/// Answers 202 whatever it finds, for the reason [`CHECK_YOUR_INBOX`] gives:
+/// a form that said "no account has that address" would tell anyone whether a
+/// person is here. Counted against the registration limits, because it costs
+/// the same mail and mails the same people.
+async fn forgot_password(
+ State(state): State<HttpState>,
+ ConnectInfo(peer): ConnectInfo<SocketAddr>,
+ headers: HeaderMap,
+ Json(body): Json<ForgotRequest>,
+) -> ApiResult<Response> {
+ let Ok(email) = registration::normalize_email(&body.email) else {
+ return Ok(accepted());
+ };
+ if !state
+ .registration_throttle
+ .per_caller
+ .allow(&caller_key(&headers, peer))
+ {
+ return Err(too_many());
+ }
+ if !state.registration_throttle.per_email.allow(&email) {
+ return Ok(accepted());
+ }
+
+ let found = with_db(&state, |c| {
+ Ok(match crate::password_reset::request(c, &email)? {
+ crate::password_reset::Request::Reset { username, token } => Some((
+ username,
+ password_link(&state.config.public_base_url, &token),
+ true,
+ )),
+ // Never confirmed: the confirmation link is what this person needs,
+ // and confirming signs them in, password or not.
+ crate::password_reset::Request::Pending => {
+ match registration::pending_by_email(c, &email)? {
+ Some(pending) => {
+ let token = registration::reissue(c, &pending)?;
+ let link = verification_link(&state.config.public_base_url, &token);
+ Some((pending.username, link, false))
+ }
+ None => None,
+ }
+ }
+ crate::password_reset::Request::Unknown => None,
+ })
+ })?;
+
+ match found {
+ Some((username, link, true)) => {
+ let (subject, text) = mail::password_reset_message(
+ &username,
+ &link,
+ crate::password_reset::RESET_TTL.as_secs() / 60,
+ );
+ send_or_log(&state, &email, &subject, &text).await;
+ tracing::info!(%username, "password reset link sent");
+ }
+ Some((username, link, false)) => {
+ let (subject, text) = mail::verification_message(
+ &username,
+ &link,
+ registration::VERIFICATION_TTL.as_secs() / 3600,
+ );
+ send_or_log(&state, &email, &subject, &text).await;
+ tracing::info!(%username, "password reset asked for an unconfirmed account: link re-sent");
+ }
+ None => tracing::info!("password reset asked for an address with no account"),
+ }
+ Ok(accepted())
+}
+
+#[derive(Deserialize)]
+struct ResetRequest {
+ token: String,
+ password: String,
+}
+
+/// Spend a reset link on a new password, and sign the account out everywhere.
+///
+/// A POST from the web app's `/reset-password`, for the reason
+/// [`verify_registration`] is one: mail scanners fetch links, and a GET that
+/// did anything would let them.
+async fn reset_password(
+ State(state): State<HttpState>,
+ Json(body): Json<ResetRequest>,
+) -> ApiResult<StatusCode> {
+ let token = body.token.trim().to_string();
+ if token.is_empty() {
+ return Err(bad_request("that link is missing its token"));
+ }
+ check_password(&body.password)?;
+ let password = body.password;
+ let hash = tokio::task::spawn_blocking(move || auth::hash_password(&password))
+ .await
+ .map_err(|e| internal(anyhow::anyhow!("hash task: {e}")))?
+ .map_err(internal)?;
+ let outcome = with_db_mut(&state, |c| crate::password_reset::finish(c, &token, &hash))?;
+ match outcome {
+ crate::password_reset::Finish::Done {
+ principal,
+ username,
+ } => {
+ let revoked = state
+ .sessions
+ .revoke_principal(Uuid::parse_str(&principal).unwrap_or_else(|_| Uuid::nil()));
+ state.sessions.forgive_failed_logins(&username);
+ tracing::info!(%username, revoked, "password reset through a mailed link");
+ Ok(StatusCode::NO_CONTENT)
+ }
+ crate::password_reset::Finish::Expired => Err(ApiError(
+ StatusCode::GONE,
+ "that link has expired — ask for a new one".into(),
+ )),
+ crate::password_reset::Finish::Unknown => Err(ApiError(
+ StatusCode::NOT_FOUND,
+ "that link is not valid — it may have been used already, or replaced by a newer one"
+ .into(),
+ )),
+ }
+}
+
+/// `{base}/reset-password?token={token}`, the web app's page for it.
+fn password_link(base: &str, token: &str) -> String {
+ format!(
+ "{}/reset-password?token={token}",
+ base.trim_end_matches('/')
+ )
+}
+
// ---------------------------------------------------------------------------
// Admin API
// ---------------------------------------------------------------------------
diff --git a/crates/simulator/src/lib.rs b/crates/simulator/src/lib.rs
index 46ed5b06..c3dd3f01 100644
--- a/crates/simulator/src/lib.rs
+++ b/crates/simulator/src/lib.rs
@@ -28,6 +28,7 @@ pub mod looks;
pub mod mail;
pub mod net;
pub mod pages;
+pub mod password_reset;
pub mod physics;
pub mod pictures;
pub mod plans_watch;
diff --git a/crates/simulator/src/mail.rs b/crates/simulator/src/mail.rs
index 29bddc49..afcf5984 100644
--- a/crates/simulator/src/mail.rs
+++ b/crates/simulator/src/mail.rs
@@ -213,6 +213,30 @@ pub fn verification_message(username: &str, link: &str, valid_hours: u64) -> (St
(subject, body)
}
+/// The "forgot your password?" mail.
+///
+/// Names the account, because a person who forgot the password has often
+/// forgotten the name too, and this is the one place it can be told to them
+/// safely: to the address the account was confirmed with.
+#[must_use]
+pub fn password_reset_message(username: &str, link: &str, valid_minutes: u64) -> (String, String) {
+ let subject = "Choose a new Cartopolis password".to_string();
+ let body = format!(
+ "Hello {username},\n\
+ \n\
+ Someone — we hope you — asked to choose a new password for the\n\
+ Cartopolis account {username}. Open this link to do it:\n\
+ \n\
+ {link}\n\
+ \n\
+ The link works once and expires in {valid_minutes} minutes. Choosing a\n\
+ new password signs the account out everywhere it is signed in.\n\
+ \n\
+ If this wasn't you, ignore this mail: your password stays as it is.\n"
+ );
+ (subject, body)
+}
+
/// What is sent when an operator activates an account by hand.
///
/// The person registered, waited for a link that never came and may well have
diff --git a/crates/simulator/src/password_reset.rs b/crates/simulator/src/password_reset.rs
new file mode 100644
index 00000000..4c457f85
--- /dev/null
+++ b/crates/simulator/src/password_reset.rs
@@ -0,0 +1,256 @@
+//! "Forgot your password?": a link mailed to the account's confirmed address,
+//! good for one new password.
+//!
+//! # What it rests on
+//!
+//! Control of the mailbox the account was confirmed with — the same proof
+//! registration took (`registration`). So only an account with a *confirmed*
+//! address gets a link. A pending one has never shown its address answers, and
+//! the useful mail for it is the confirmation link again, which the handler
+//! sends instead; an operator-made account, or one made through another site
+//! that shared no address, has nowhere to send anything, and its way back is
+//! still an operator.
+//!
+//! # What a reset does besides the password
+//!
+//! Signs the account out everywhere ([`crate::auth::Sessions::revoke_principal`]):
+//! the person asking may be asking *because* somebody else has the password,
+//! and a reset that left that somebody's session open would not have helped.
+
+use crate::auth::{random_token, token_hash};
+use anyhow::Context;
+use rusqlite::{Connection, OptionalExtension};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+/// How long a reset link works.
+///
+/// Much shorter than a confirmation link (`registration::VERIFICATION_TTL`):
+/// the person asking is at the form now, waiting for the mail, and this link
+/// sets the password, so a copy left in a mailbox should stop working soon.
+pub const RESET_TTL: Duration = Duration::from_secs(60 * 60);
+
+fn unix_now() -> i64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_secs() as i64)
+ .unwrap_or(0)
+}
+
+/// What [`request`] found for an address.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Request {
+ /// A confirmed account: mail it this link's token.
+ Reset { username: String, token: String },
+ /// An account whose address was never confirmed: mail the confirmation
+ /// link again rather than a reset (`registration::reissue`).
+ Pending,
+ /// No account has this address. Told to nobody.
+ Unknown,
+}
+
+/// Mint a reset token for the account with `email`, replacing any it had.
+///
+/// Replacing, as the confirmation link's re-send does: two live links means
+/// the older mail still works after the newer one was asked for.
+pub fn request(conn: &Connection, email: &str) -> anyhow::Result<Request> {
+ let email = email.trim().to_lowercase();
+ let row: Option<(String, String, Option<String>)> = conn
+ .query_row(
+ "SELECT id, username, email_verified_at FROM accounts WHERE lower(email) = ?1",
+ [&email],
+ |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
+ )
+ .optional()?;
+ let Some((principal, username, verified_at)) = row else {
+ return Ok(Request::Unknown);
+ };
+ if verified_at.is_none() {
+ return Ok(Request::Pending);
+ }
+ let token = random_token();
+ let now = unix_now();
+ conn.execute(
+ "DELETE FROM password_resets WHERE principal = ?1 OR expires_at < ?2",
+ rusqlite::params![principal, now],
+ )?;
+ conn.execute(
+ "INSERT INTO password_resets (token_hash, principal, created_at, expires_at)
+ VALUES (?1, ?2, ?3, ?4)",
+ rusqlite::params![
+ token_hash(&token),
+ principal,
+ now,
+ now + RESET_TTL.as_secs() as i64,
+ ],
+ )
+ .context("insert password reset")?;
+ Ok(Request::Reset { username, token })
+}
+
+/// What [`finish`] made of a token.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Finish {
+ /// The password is replaced.
+ Done { principal: String, username: String },
+ /// No such token: never issued, already used, or replaced by a newer one.
+ Unknown,
+ /// Issued, and too old.
+ Expired,
+}
+
+/// Spend a reset token on a new password, given as an argon2 PHC string — the
+/// caller hashes it first, with no database lock held (`auth`'s module note).
+///
+/// The row goes whether the token was in time or not, as a confirmation
+/// link's does: an expired one is worth nothing, and a used one must not work
+/// twice.
+pub fn finish(conn: &mut Connection, token: &str, pw_hash: &str) -> anyhow::Result<Finish> {
+ let hash = token_hash(token);
+ let tx = conn.transaction()?;
+ let row: Option<(String, i64)> = tx
+ .query_row(
+ "SELECT principal, expires_at FROM password_resets WHERE token_hash = ?1",
+ [&hash],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .optional()?;
+ let Some((principal, expires_at)) = row else {
+ return Ok(Finish::Unknown);
+ };
+ tx.execute("DELETE FROM password_resets WHERE token_hash = ?1", [&hash])?;
+ if expires_at < unix_now() {
+ tx.commit()?;
+ return Ok(Finish::Expired);
+ }
+ let username: Option<String> = tx
+ .query_row(
+ "SELECT username FROM accounts WHERE id = ?1",
+ [&principal],
+ |r| r.get(0),
+ )
+ .optional()?;
+ let Some(username) = username else {
+ // The account was deleted between the mail and the click.
+ tx.commit()?;
+ return Ok(Finish::Unknown);
+ };
+ tx.execute(
+ "UPDATE accounts SET pw_hash = ?2 WHERE id = ?1",
+ rusqlite::params![principal, pw_hash],
+ )?;
+ tx.commit()?;
+ Ok(Finish::Done {
+ principal,
+ username,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::registration;
+
+ fn db() -> Connection {
+ let mut conn = Connection::open_in_memory().unwrap();
+ crate::db::migrate(&mut conn).unwrap();
+ conn
+ }
+
+ fn hash(pw: &str) -> String {
+ crate::auth::hash_password(pw).unwrap()
+ }
+
+ /// A registered account whose link was opened.
+ fn confirmed(conn: &mut Connection, username: &str, email: &str) {
+ let registration::Begin::Created { token, .. } =
+ registration::begin(conn, username, email, &hash("oldpassword")).unwrap()
+ else {
+ panic!("registration did not create an account");
+ };
+ registration::verify(conn, &token).unwrap();
+ }
+
+ fn signs_in(conn: &Connection, username: &str, password: &str) -> bool {
+ let stored = crate::auth::lookup_credential(conn, username)
+ .unwrap()
+ .unwrap();
+ crate::auth::verify_password(password, &stored.phc)
+ }
+
+ #[test]
+ fn a_link_sets_the_password_once() {
+ let mut conn = db();
+ confirmed(&mut conn, "ada", "ada@example.com");
+ let Request::Reset { username, token } = request(&conn, " Ada@Example.com ").unwrap()
+ else {
+ panic!("a confirmed address gets a link");
+ };
+ assert_eq!(username, "ada");
+
+ let outcome = finish(&mut conn, &token, &hash("newpassword")).unwrap();
+ assert!(matches!(outcome, Finish::Done { ref username, .. } if username == "ada"));
+ assert!(signs_in(&conn, "ada", "newpassword"));
+ assert!(!signs_in(&conn, "ada", "oldpassword"));
+
+ assert_eq!(
+ finish(&mut conn, &token, &hash("thirdpassword")).unwrap(),
+ Finish::Unknown
+ );
+ assert!(signs_in(&conn, "ada", "newpassword"));
+ }
+
+ #[test]
+ fn asking_again_replaces_the_earlier_link() {
+ let mut conn = db();
+ confirmed(&mut conn, "ada", "ada@example.com");
+ let Request::Reset { token: first, .. } = request(&conn, "ada@example.com").unwrap() else {
+ panic!()
+ };
+ let Request::Reset { token: second, .. } = request(&conn, "ada@example.com").unwrap()
+ else {
+ panic!()
+ };
+ assert_eq!(
+ finish(&mut conn, &first, &hash("newpassword")).unwrap(),
+ Finish::Unknown
+ );
+ assert!(matches!(
+ finish(&mut conn, &second, &hash("newpassword")).unwrap(),
+ Finish::Done { .. }
+ ));
+ }
+
+ #[test]
+ fn only_a_confirmed_address_gets_a_link() {
+ let mut conn = db();
+ registration::begin(&mut conn, "grace", "grace@example.com", &hash("pw12345678")).unwrap();
+ assert_eq!(
+ request(&conn, "grace@example.com").unwrap(),
+ Request::Pending
+ );
+ assert_eq!(
+ request(&conn, "nobody@example.com").unwrap(),
+ Request::Unknown
+ );
+ }
+
+ #[test]
+ fn an_expired_link_is_told_apart_and_spent() {
+ let mut conn = db();
+ confirmed(&mut conn, "ada", "ada@example.com");
+ let Request::Reset { token, .. } = request(&conn, "ada@example.com").unwrap() else {
+ panic!()
+ };
+ conn.execute("UPDATE password_resets SET expires_at = 0", [])
+ .unwrap();
+ assert_eq!(
+ finish(&mut conn, &token, &hash("newpassword")).unwrap(),
+ Finish::Expired
+ );
+ assert!(signs_in(&conn, "ada", "oldpassword"));
+ assert_eq!(
+ finish(&mut conn, &token, &hash("newpassword")).unwrap(),
+ Finish::Unknown
+ );
+ }
+}
diff --git a/crates/simulator/src/registration.rs b/crates/simulator/src/registration.rs
index fa74b054..98921483 100644
--- a/crates/simulator/src/registration.rs
+++ b/crates/simulator/src/registration.rs
@@ -452,6 +452,14 @@ impl Throttle {
})
}
+ /// Drop a key's count, for when what it counted no longer applies.
+ pub fn forget(&self, key: &str) {
+ self.hits
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .remove(key);
+ }
+
/// Count one attempt against a key. `false` means over the limit.
pub fn allow(&self, key: &str) -> bool {
let now = SystemTime::now();
diff --git a/crates/simulator/tests/integration/http_surface.rs b/crates/simulator/tests/integration/http_surface.rs
index 0b5e13a8..2aa17fae 100644
--- a/crates/simulator/tests/integration/http_surface.rs
+++ b/crates/simulator/tests/integration/http_surface.rs
@@ -627,6 +627,94 @@ async fn a_registration_cannot_sign_in_until_the_link_is_opened() {
assert_eq!(status, 404);
}
+/// "Forgot your password?", end to end: the request answers the same for any
+/// address, the link sets a new password once, and the account's open
+/// sessions end with the old password.
+#[tokio::test]
+async fn a_forgotten_password_is_replaced_through_a_mailed_link() {
+ let (handle, dir) = server().await;
+ let db = dir.path().join("http.db").to_str().unwrap().to_string();
+ let base = http_base(&handle);
+
+ let (status, _) = api(
+ "POST",
+ format!("{base}/api/register"),
+ None,
+ Some(serde_json::json!({
+ "username": "ada",
+ "email": "ada@example.com",
+ "password": "correcthorse",
+ })),
+ )
+ .await;
+ assert_eq!(status, 202);
+ let (status, _) = api(
+ "POST",
+ format!("{base}/api/register/verify"),
+ None,
+ Some(serde_json::json!({ "token": link_token(&db, "ada@example.com") })),
+ )
+ .await;
+ assert_eq!(status, 200);
+ let session = player_session(&base, "ada", "correcthorse").await;
+
+ // A known and an unknown address get one answer.
+ let forgot = |email: &'static str| {
+ api(
+ "POST",
+ format!("{base}/api/password/forgot"),
+ None,
+ Some(serde_json::json!({ "email": email })),
+ )
+ };
+ let (known_status, known) = forgot("Ada@Example.com").await;
+ let (unknown_status, unknown) = forgot("nobody@example.com").await;
+ assert_eq!(known_status, 202);
+ assert_eq!((known_status, known), (unknown_status, unknown));
+
+ // The mail is only logged here, and the link's stored copy is a hash, so
+ // the test mints its own through the call the endpoint makes.
+ let token = {
+ let conn = cartopolis_simulator::db::open_and_migrate(&db).unwrap();
+ match cartopolis_simulator::password_reset::request(&conn, "ada@example.com").unwrap() {
+ cartopolis_simulator::password_reset::Request::Reset { token, .. } => token,
+ other => panic!("a confirmed account gets a link, got {other:?}"),
+ }
+ };
+ let reset = |password: &'static str| {
+ api(
+ "POST",
+ format!("{base}/api/password/reset"),
+ None,
+ Some(serde_json::json!({ "token": token.clone(), "password": password })),
+ )
+ };
+ let (status, body) = reset("short").await;
+ assert_eq!(status, 400, "the password rules hold here too: {body}");
+ let (status, body) = reset("batterystaple").await;
+ assert_eq!(status, 204, "reset: {body}");
+ let (status, _) = reset("anotherpassword").await;
+ assert_eq!(status, 404, "a used link must not work twice");
+
+ let (status, _) = api(
+ "GET",
+ format!("{base}/api/buildings/mine"),
+ Some(session),
+ None,
+ )
+ .await;
+ assert_eq!(status, 401, "the sessions from before the reset are over");
+ let (status, _) = api(
+ "POST",
+ format!("{base}/api/login"),
+ None,
+ Some(serde_json::json!({"username": "ada", "password": "correcthorse"})),
+ )
+ .await;
+ assert_eq!(status, 401, "the old password is gone");
+ player_session(&base, "ada", "batterystaple").await;
+}
+
/// The way through when the verification mail never arrives: an admin activates
/// the account, and the same password then plays. Only an admin may, and only
/// once.
diff --git a/docs/notes/self-service-accounts.md b/docs/notes/self-service-accounts.md
index 9b764230..d6f39ad3 100644
--- a/docs/notes/self-service-accounts.md
+++ b/docs/notes/self-service-accounts.md
@@ -1,7 +1,7 @@
---
topic: self-service-accounts
-triggers: [registration.rs, simulator/src/buildings.rs, mail.rs, "register", "sign up", "verification", "verify email", "smtp", "claim a house", "nummeraanduiding", "Locatieserver", "PDOK", V11__account_email, V12__house_claims]
-updated: 2026-08-29
+triggers: [registration.rs, password_reset.rs, "forgot password", "password reset", V52__password_resets, simulator/src/buildings.rs, mail.rs, "register", "sign up", "verification", "verify email", "smtp", "claim a house", "nummeraanduiding", "Locatieserver", "PDOK", V11__account_email, V12__house_claims]
+updated: 2026-11-30
---
# Strangers can make accounts now, and claim one house each
@@ -107,6 +107,22 @@ reputation.
alternative considered was holding a home address per account to compare
against, which is more personal data than the account store carries and is not
proof either.
-- **No password reset.** Registration mails a link; forgetting a password still
- needs an operator. The pieces (a token table, a mailer, a throttle) are now all
- present, so it is a small feature rather than a project.
+## Forgot your password? (built 2026-11-30)
+
+`/forgot` on the web page (linked under every password field there, and from
+the app's sign-in card, which opens it in the browser) posts an address to
+`/api/password/forgot`; the mail links to `/reset-password?token=…`, which
+posts the new password to `/api/password/reset` (`password_reset.rs`,
+`V52__password_resets.sql`). What is not obvious from the code:
+
+- **Only a confirmed address gets a reset link.** An unconfirmed one gets its
+ confirmation link again — confirming signs the person in, which is what they
+ wanted. An account with no address (made by an operator, or through another
+ site that shared none) gets nothing, and still needs an operator.
+- **Every outcome answers 202**, as registration does, and the request counts
+ against the same `RegistrationLimits`: it costs the same mail.
+- **A reset signs the account out everywhere** (sessions *and* access tokens,
+ `revoke_principal`) and clears the wrong-password count for the name. The
+ person asking may be asking because somebody else has the password.
+- The link lives an hour, not a day: it sets the password, and the person is
+ at the form waiting for it.