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