steid

@jamesgill /

1//! First-run claim and sign-in.
2//!
3//! Claiming is three screens, not one: `/auth/setup` makes the owner's account,
4//! `/auth/setup/organisation` asks who the instance is *for*, and `/auth/setup/done`
5//! says where to go next. They are separate URLs rather than one long form because the
6//! second question only makes sense once there is somebody to answer it — the claim
7//! signs you in, so the wizard carries no state of its own beyond the session and the
8//! two facts it can read back out of the database.
9
10use serde::Deserialize;
11use topcoat::{
12 Result,
13 context::Cx,
14 router::{
15 IntoResponse, Response, StatusCode,
16 content::Form,
17 error::{not_found, redirect, see_other},
18 page, query_params, route,
19 },
20 session,
21 view::{attributes, component, view},
22};
23
24use crate::{
25 application::{
26 Error, NewOrganisation, OwnerSpec, claim_instance, create_organization, end_session, login,
27 record_session, set_home_by_handle,
28 },
29 components::{
30 button::{ButtonSize, ButtonVariant, button, button_variants},
31 flash::{FlashKind, flash},
32 input::input,
33 label::label,
34 },
35 domain::{Actor, DomainError, OrgName, Password},
36 infrastructure::{
37 password::Argon2Hasher,
38 repository::{SqliteMembershipRepo, SqliteOrgRepo, SqliteSessionRepo, SqliteUserRepo},
39 },
40};
41
42use super::{
43 context::{
44 claimed, current_actor, hex, identity, instance_owner, instance_settings, location,
45 memberships, orgs, pool, server_error, setup_token, users,
46 },
47 csrf::{
48 CsrfGuard, csrf_field, csrf_verified, csrf_verified_response, csrf_verified_signed_out,
49 },
50 format::optional,
51 layout::narrow,
52 org::home_chosen,
53 rate_limit::throttled,
54};
55
56#[derive(Debug, Deserialize)]
57struct ClaimForm {
58 token: String,
59 handle: String,
60 email: String,
61 password: String,
62}
63
64#[derive(Debug, Deserialize)]
65struct LoginForm {
66 email: String,
67 password: String,
68}
69
70/// Why the last claim was refused, when it was for a reason worth saying out loud.
71///
72/// Only the password rule travels back: a wrong setup token and an already-claimed
73/// instance stay silent, because saying which one it was tells a stranger something
74/// about a secret they are guessing.
75#[query_params(error = bad_request)]
76struct Refused {
77 error: Option<String>,
78}
79
80/// A setup token carried in the link, so a provisioner can hand its customer one URL
81/// instead of a URL and a secret to paste.
82///
83/// **Prefill only.** The POST checks the submitted value against the token in memory
84/// exactly as it always did, so a link with the wrong token is refused like anything
85/// else. The cost is that the token lands in browser history and in the referrer of
86/// anything the claim page links to — acceptable for a one-time secret that is dead the
87/// moment it is used, and the page links nowhere.
88#[query_params(error = bad_request)]
89struct Prefill {
90 token: Option<String>,
91}
92
93#[page("/auth/setup")]
94async fn setup_page(cx: &Cx) -> Result {
95 if claimed(cx).await? {
96 return Err(redirect("/").into());
97 }
98
99 let refused = matches!(
100 query_params::<Refused>(cx)?.error.as_deref(),
101 Some("password")
102 );
103 let prefilled = query_params::<Prefill>(cx)?
104 .token
105 .clone()
106 .unwrap_or_default();
107
108 view! {
109 narrow(
110 <h1>"Claim this instance"</h1>
111 <p>"The setup token was printed to the server log at startup."</p>
112
113 if refused {
114 <div class="mb-4">flash(kind: FlashKind::Error, (Password::RULE))</div>
115 }
116
117 <form method="post" action="/auth/setup">
118 <p><label>"Setup token " <input type="text" name="token" value=(prefilled.as_str()) required="true" /></label></p>
119 <p><label>"Handle " <input type="text" name="handle" required="true" /></label></p>
120 <p><label>"Email " <input type="email" name="email" required="true" /></label></p>
121 <p><label>"Password " <input type="password" name="password" required="true" /></label></p>
122 <p class="text-xs text-muted-foreground">(Password::RULE)</p>
123 <button type="submit">"Claim"</button>
124 </form>
125 )
126 }
127}
128
129/// Claims the instance.
130///
131/// Rate limited before anything else happens: the setup token is the only thing
132/// standing between a stranger and ownership of an unclaimed instance, and unlike a
133/// personal access token it may have been chosen by a person.
134#[route(POST "/auth/setup")]
135async fn claim(cx: &Cx, Form(form): Form<ClaimForm>) -> Result<Response> {
136 if let Some(response) = throttled(cx) {
137 return Ok(response);
138 }
139
140 // Absent once claimed, so a claimed instance cannot be re-claimed even if the
141 // use case were somehow reached. 303 rather than `redirect`'s 307 for the same
142 // reason as the refusal below: a 307 re-POSTs the claim, to `/` this time.
143 let Some(token) = setup_token(cx) else {
144 return see_other("/").into_response(cx);
145 };
146
147 let pool = pool(cx).clone();
148 let users = SqliteUserRepo::new(pool.clone());
149 let orgs = SqliteOrgRepo::new(pool.clone());
150 let memberships = SqliteMembershipRepo::new(pool.clone());
151 let sessions = SqliteSessionRepo::new(pool);
152
153 let claimed = claim_instance(
154 &form.token,
155 token,
156 &OwnerSpec {
157 handle: form.handle,
158 email: form.email,
159 password: form.password,
160 },
161 &users,
162 &orgs,
163 &memberships,
164 &Argon2Hasher::new(),
165 )
166 .await;
167
168 let actor = match claimed {
169 Ok(actor) => actor,
170 Err(error) => {
171 eprintln!("steid: claim rejected: {error}");
172
173 // The password rule is not a secret and a form that refuses without saying
174 // why is unusable; everything else — a wrong token, an instance already
175 // claimed — goes back to a bare form, so the refusal is not an oracle.
176 let back = if matches!(
177 error,
178 Error::Domain(DomainError::Validation { ref field, .. }) if field == "password"
179 ) {
180 "/auth/setup?error=password"
181 } else {
182 "/auth/setup"
183 };
184
185 // 303, not `redirect`'s 307: a 307 preserves the method, so the browser
186 // would re-POST the claim to the target and refuse it again, forever.
187 return see_other(back).into_response(cx);
188 }
189 };
190
191 sign_in(cx, &actor, &sessions).await?;
192
193 // Not `/`: claiming signs you in, and the next thing to decide is who the instance
194 // is for. That screen sends anyone who has already answered straight back to `/`,
195 // so a reload cannot strand somebody in the wizard.
196 see_other("/auth/setup/organisation").into_response(cx)
197}
198
199/// Set by a completed password reset, which ends every session and so has nowhere to
200/// send anyone but here.
201#[query_params(error = bad_request)]
202struct Reset {
203 reset: Option<String>,
204}
205
206#[page("/auth/login")]
207async fn login_page(cx: &Cx) -> Result {
208 if !claimed(cx).await? {
209 return Err(redirect("/auth/setup").into());
210 }
211
212 let after_reset = query_params::<Reset>(cx)?.reset.is_some();
213
214 view! {
215 narrow(
216 <h1>"Sign in"</h1>
217
218 if after_reset {
219 <div class="mb-4">
220 flash(kind: FlashKind::Success, "Password changed. Sign in with the new one.")
221 </div>
222 }
223
224 <form method="post" action="/auth/login">
225 <p><label>"Email " <input type="email" name="email" required="true" /></label></p>
226 <p><label>"Password " <input type="password" name="password" required="true" /></label></p>
227 <button type="submit">"Sign in"</button>
228 </form>
229 <p class="mt-4 text-xs text-muted-foreground">
230 <a href="/auth/forgot" class="hover:text-foreground">"Forgotten your password?"</a>
231 </p>
232 )
233 }
234}
235
236/// Signs in.
237///
238/// Rate limited first, before the password is hashed: a human-chosen password is the
239/// one secret here that guessing can reach, and Argon2 is deliberately expensive
240/// enough that an unlimited endpoint is also a way to burn the server's CPU.
241///
242/// Then the login CSRF check, before the password is looked at: a submission that does
243/// not say where it came from is refused whatever it carries (launch 2.18).
244#[route(POST "/auth/login")]
245async fn sign_in_route(cx: &Cx, Form(form): Form<LoginForm>) -> Result<Response> {
246 if let Some(response) = throttled(cx) {
247 return Ok(response);
248 }
249
250 if let Some(response) = csrf_verified_signed_out(cx) {
251 return Ok(response);
252 }
253
254 let pool = pool(cx).clone();
255 let users = SqliteUserRepo::new(pool.clone());
256 let sessions = SqliteSessionRepo::new(pool);
257
258 let actor = match login(&form.email, &form.password, &users, &Argon2Hasher::new()).await {
259 Ok(actor) => actor,
260 Err(error) => {
261 eprintln!("steid: login rejected: {error}");
262
263 // 303, not `redirect`'s 307, for the same reason the refused claim above
264 // is: a 307 preserves the method, so the browser re-POSTs the credentials
265 // to the login page and is refused again, forever.
266 return see_other("/auth/login").into_response(cx);
267 }
268 };
269
270 sign_in(cx, &actor, &sessions).await?;
271
272 see_other("/").into_response(cx)
273}
274
275#[route(POST "/auth/logout")]
276async fn logout(cx: &Cx, Form(guard): Form<CsrfGuard>) -> Result<Response> {
277 if let Some(response) = csrf_verified_response(cx, &guard.csrf_token).await? {
278 return Ok(response);
279 }
280
281 // Both halves: the client discards its token, and the record goes. Doing only the
282 // first leaves the session valid server-side.
283 if let Some(hash) = session::stop(cx).await? {
284 let sessions = SqliteSessionRepo::new(pool(cx).clone());
285 end_session(
286 &crate::domain::SessionTokenHash::from_trusted(hex(&hash)),
287 &sessions,
288 )
289 .await
290 .map_err(topcoat::Error::from)?;
291 }
292
293 see_other("/").into_response(cx)
294}
295
296/// Issues a session for an authenticated actor and records it.
297async fn sign_in(cx: &Cx, actor: &Actor, sessions: &SqliteSessionRepo) -> Result<()> {
298 let Some(user_id) = actor.user_id() else {
299 return Ok(());
300 };
301
302 let session = session::start(cx).await?;
303
304 record_session(
305 crate::domain::SessionTokenHash::from_trusted(hex(&session.token_hash)),
306 user_id.clone(),
307 session.expires_at,
308 sessions,
309 )
310 .await
311 .map_err(topcoat::Error::from)?;
312
313 Ok(())
314}
315
316/// Which of the two the visitor picked on the second screen.
317#[derive(Debug, Deserialize)]
318struct WizardForm {
319 /// The hidden field every form carries; see [`csrf`](super::csrf).
320 ///
321 /// `default` so that a submission with no token at all is refused by
322 /// `csrf_verified` — a 403 saying what happened — rather than failing
323 /// deserialization into a bare 400 that says nothing.
324 #[serde(default)]
325 csrf_token: String,
326 /// `"me"` or `"org"`. A `String` rather than an enum because a value no radio
327 /// could have produced must re-render the page with a reason, not fail
328 /// deserialization into a bare 400.
329 #[serde(default)]
330 owner: String,
331 #[serde(default)]
332 handle: String,
333 #[serde(default)]
334 display_name: String,
335}
336
337/// Whether the wizard's second screen still has a question to ask.
338///
339/// Two conditions, and both are needed. **No home chosen**, because the screen exists
340/// to choose one and an instance that has is finished with it. **The sole user**,
341/// because a second person signing in on a fresh instance is not the person who gets
342/// to decide what it is for — and [`instance_owner`](super::context::instance_owner) is
343/// exactly that question, asked in the one place that will know the answer differently
344/// when milestone 7 gives the instance a real admin role.
345async fn wizard_open(cx: &Cx) -> Result<bool> {
346 Ok(!home_chosen(cx).await? && instance_owner(cx).await?)
347}
348
349/// "Who is this Steid for?"
350///
351/// Signed in only, and only while [the question is still open](wizard_open). Anyone
352/// else is sent to `/`, which lands them on the home page like any other visitor.
353#[page("/auth/setup/organisation")]
354async fn wizard_page(cx: &Cx) -> Result {
355 let Some(identity) = identity(cx).await? else {
356 return Err(redirect("/auth/login").into());
357 };
358
359 if !wizard_open(cx).await? {
360 return Err(redirect("/").into());
361 }
362
363 view! {
364 wizard_form(
365 handle: identity.handle.as_str(),
366 org_handle: "",
367 display_name: "",
368 error: "",
369 )
370 }
371}
372
373/// Records the answer, and points the root at it.
374///
375/// "Just me" makes the claimant's own page the home; "An organisation" creates one,
376/// makes them its owner, and points the root at that. Both are 303 to the last screen —
377/// see [`location`](super::context::location) for why a POST may not use `redirect()`.
378///
379/// Failure re-renders with the reason and what was typed. The commonest one is a handle
380/// already taken, which on a fresh instance means the claimant's own.
381#[page(POST "/auth/setup/organisation")]
382async fn wizard_submit(cx: &Cx, Form(submitted): Form<WizardForm>) -> Result {
383 csrf_verified(cx, &submitted.csrf_token).await?;
384
385 let Some(identity) = identity(cx).await? else {
386 return Err(not_found().into());
387 };
388
389 if !wizard_open(cx).await? {
390 return view! {
391 (StatusCode::SEE_OTHER)
392 (location("/")?)
393 };
394 }
395
396 let actor = current_actor(cx).await?;
397
398 let outcome = match submitted.owner.as_str() {
399 "me" => set_home_for(cx, &actor, &identity.handle).await,
400 "org" => match create_organization(
401 &actor,
402 &NewOrganisation {
403 handle: submitted.handle.clone(),
404 display_name: optional(&submitted.display_name),
405 },
406 &orgs(cx),
407 &memberships(cx),
408 )
409 .await
410 {
411 Ok(org) => set_home_for(cx, &actor, &org.name).await,
412 Err(error) => Err(error),
413 },
414 // Neither radio, which a browser cannot produce. Re-rendered rather than a 400,
415 // because the page it would be a 400 for is one somebody is mid-way through.
416 _ => Err(Error::Domain(DomainError::validation(
417 "choice",
418 "pick one of the two",
419 ))),
420 };
421
422 let message = match outcome {
423 Ok(()) => {
424 return view! {
425 (StatusCode::SEE_OTHER)
426 (location("/auth/setup/done")?)
427 };
428 }
429 Err(Error::Domain(DomainError::Validation { field, reason })) => {
430 format!("That {field} is no good: {reason}.")
431 }
432 Err(Error::Domain(DomainError::AlreadyExists { .. })) => {
433 format!(
434 "The handle {} is already taken on this instance.",
435 submitted.handle.trim()
436 )
437 }
438 Err(Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. })) => {
439 return Err(not_found().into());
440 }
441 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
442 };
443
444 view! {
445 wizard_form(
446 handle: identity.handle.as_str(),
447 org_handle: submitted.handle.as_str(),
448 display_name: submitted.display_name.as_str(),
449 error: message.as_str(),
450 )
451 }
452}
453
454/// Points the root at a handle the actor owns.
455async fn set_home_for(cx: &Cx, actor: &Actor, handle: &OrgName) -> crate::application::Result<()> {
456 set_home_by_handle(
457 actor,
458 handle,
459 &orgs(cx),
460 &memberships(cx),
461 &users(cx),
462 &instance_settings(cx),
463 )
464 .await
465}
466
467/// The second screen.
468///
469/// **No JavaScript, so the organisation's fields are always visible** under the second
470/// radio rather than revealed by it. Steid ships no script of its own and a `:has()`
471/// trick would be the first thing on any page whose behaviour is invisible in the
472/// markup; two fields that are ignored unless the second radio is chosen is the boring
473/// version, and boring wins.
474#[component]
475async fn wizard_form(handle: &str, org_handle: &str, display_name: &str, error: &str) -> Result {
476 view! {
477 narrow(
478 <h1 class="text-xl font-semibold tracking-tight">"Who is this Steid for?"</h1>
479 <p class="mt-1 text-sm text-muted-foreground">
480 "This decides where the root of this instance lands. You can change it "
481 "later in settings."
482 </p>
483
484 if !error.is_empty() {
485 <div class="mt-6">
486 flash(kind: FlashKind::Error, (error))
487 </div>
488 }
489
490 <form method="post" action="/auth/setup/organisation" class="mt-6 space-y-6">
491 csrf_field()
492
493 <div class="space-y-2">
494 <div class="flex items-start gap-2">
495 <input
496 id="owner-me"
497 name="owner"
498 type="radio"
499 value="me"
500 checked=(true)
501 class="mt-1"
502 />
503 label(attrs: attributes! { for="owner-me" }, "Just me")
504 </div>
505 <p class="pl-6 text-xs text-muted-foreground">
506 "The root lands on your own page, " <code class="font-mono">"/" (handle)</code>
507 "."
508 </p>
509 </div>
510
511 <div class="space-y-3">
512 <div class="flex items-start gap-2">
513 <input
514 id="owner-org"
515 name="owner"
516 type="radio"
517 value="org"
518 class="mt-1"
519 />
520 label(attrs: attributes! { for="owner-org" }, "An organisation")
521 </div>
522 <p class="pl-6 text-xs text-muted-foreground">
523 "A company or a team. It gets a handle of its own, you own it, "
524 "and the root lands there."
525 </p>
526
527 <div class="space-y-4 pl-6">
528 <div class="space-y-2">
529 label(attrs: attributes! { for="handle" }, "Organisation handle")
530 input(attrs: attributes! {
531 id="handle"
532 name="handle"
533 type="text"
534 value=(org_handle)
535 placeholder="acme"
536 maxlength=(OrgName::MAX_LEN.to_string())
537 })
538 </div>
539 <div class="space-y-2">
540 label(attrs: attributes! { for="display_name" }, "Display name")
541 input(attrs: attributes! {
542 id="display_name"
543 name="display_name"
544 type="text"
545 value=(display_name)
546 placeholder="Acme Inc"
547 })
548 </div>
549 </div>
550 </div>
551
552 <div class="flex items-center gap-3">
553 button(attrs: attributes! { type="submit" }, "Continue")
554 <a
555 href="/auth/setup/done"
556 class="text-sm text-muted-foreground hover:text-foreground"
557 >"Skip for now"</a>
558 </div>
559 </form>
560 )
561 }
562}
563
564/// The last screen: where the instance is, and what to do first.
565///
566/// Reached by finishing the wizard or by skipping it, so it reads the home page back
567/// out of the same rule `/` uses rather than being told which branch got here. Skipping
568/// leaves no home chosen, and the fallback still lands the root on the claimant.
569#[page("/auth/setup/done")]
570async fn wizard_done(cx: &Cx) -> Result {
571 let Some(identity) = identity(cx).await? else {
572 return Err(redirect("/auth/login").into());
573 };
574
575 let handle = super::org::home(cx)
576 .await?
577 .unwrap_or_else(|| identity.handle.clone());
578 let home = format!("/{handle}");
579 let new_repo = format!("/{handle}/repos/new");
580
581 view! {
582 narrow(
583 <h1 class="text-xl font-semibold tracking-tight">"Your Steid is ready"</h1>
584 <p class="mt-3 text-sm text-muted-foreground">
585 "This instance lands on " <code class="font-mono">(home.as_str())</code>
586 ". Create your first repository at "
587 <a href=(new_repo.as_str()) class="font-medium hover:underline">
588 (new_repo.as_str())
589 </a>
590 " — new repositories are private unless you say otherwise."
591 </p>
592
593 <p class="mt-6">
594 <a href=(home.as_str()) class=(button_variants(ButtonVariant::Primary, ButtonSize::Md))>
595 "Go to the home page"
596 </a>
597 </p>
598 )
599 }
600}