steid

@jamesgill /

1//! Personal access tokens — `/{handle}/settings/tokens`.
2//!
3//! The one place a token is ever visible. Everything else in Steid holds only its hash,
4//! so if this page does not show it, nobody can.
5
6use std::time::SystemTime;
7
8use serde::Deserialize;
9use topcoat::{
10 Result,
11 context::Cx,
12 router::{StatusCode, content::Form, error::not_found, page, path_param},
13 view::{attributes, component, view},
14};
15
16use crate::{
17 application::{Error, TokenSummary, issue_token, list_tokens, revoke_token},
18 components::{
19 badge::{BadgeVariant, badge},
20 button::{ButtonSize, ButtonVariant, button},
21 flash::{FlashKind, flash},
22 input::input,
23 label::label,
24 select::select,
25 },
26 domain::{DomainError, TokenId, TokenLifetime},
27};
28
29use super::{
30 context::{current_actor, location, owned_profile, server_error, tokens},
31 csrf::{CsrfGuard, csrf_field, csrf_verified},
32 format::{ago, timestamp},
33 layout::narrow,
34};
35
36/// `{token}` from the path — a token's id, never the token itself.
37#[path_param]
38struct Token(str);
39
40#[derive(Debug, Deserialize)]
41struct IssueForm {
42 /// The hidden field every form carries; see [`csrf`](super::csrf).
43 ///
44 /// `default` so that a submission with no token at all is refused by
45 /// `csrf_verified` — a 403 saying what happened — rather than failing
46 /// deserialization into a bare 400 that says nothing.
47 #[serde(default)]
48 csrf_token: String,
49 name: String,
50 /// The chosen lifetime, as [`TokenLifetime::as_str`] writes it.
51 ///
52 /// A `String` rather than a `TokenLifetime` because a rejected value has to
53 /// re-render the form with what was typed, and a deserialization failure is a 400
54 /// with no page.
55 expires: String,
56}
57
58/// Only the person whose settings these are may see them.
59///
60/// The use cases scope every operation to the actor's own tokens regardless, so this
61/// guard decides what is *shown*, not what is allowed.
62async fn own_settings(cx: &Cx) -> Result<String> {
63 Ok(owned_profile(cx).await?.handle.to_string())
64}
65
66async fn listing(cx: &Cx) -> Result<Vec<TokenSummary>> {
67 list_tokens(&current_actor(cx).await?, SystemTime::now(), &tokens(cx))
68 .await
69 .map_err(server_error)
70}
71
72#[page("/{handle}/settings/tokens")]
73async fn tokens_page(cx: &Cx) -> Result {
74 let handle = own_settings(cx).await?;
75 let listed = listing(cx).await?;
76
77 view! {
78 tokens_view(
79 handle: handle.as_str(),
80 tokens: &listed,
81 issued: "",
82 error: "",
83 name: "",
84 expires: TokenLifetime::default().as_str(),
85 )
86 }
87}
88
89/// Issues a token and shows it, once.
90///
91/// **This deliberately does not redirect**, unlike every other form in Steid. The
92/// secret exists only in this response: surviving a redirect would mean putting a live
93/// credential in a URL, where it lands in browser history, logs and referrers. Reloading
94/// re-submits, which issues a second token — harmless, and visible in the list.
95#[page(POST "/{handle}/settings/tokens")]
96async fn issue(cx: &Cx, Form(submitted): Form<IssueForm>) -> Result {
97 csrf_verified(cx, &submitted.csrf_token).await?;
98
99 let handle = own_settings(cx).await?;
100
101 // Parsed before the use case rather than inside the form type, so a value the
102 // `<select>` could not have produced re-renders the page with the reason rather than
103 // failing deserialization into a bare 400.
104 let outcome = match submitted.expires.parse() {
105 Ok(lifetime) => {
106 issue_token(
107 &current_actor(cx).await?,
108 &submitted.name,
109 lifetime,
110 SystemTime::now(),
111 &tokens(cx),
112 )
113 .await
114 }
115 Err(error) => Err(Error::Domain(error)),
116 };
117
118 let (issued, error) = match outcome {
119 Ok(issued) => (issued.secret.reveal().to_owned(), String::new()),
120 Err(Error::Domain(DomainError::Validation { field, reason })) => {
121 (String::new(), format!("That {field} is no good: {reason}."))
122 }
123 Err(Error::Domain(DomainError::Forbidden)) => return Err(not_found().into()),
124 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
125 };
126
127 let listed = listing(cx).await?;
128
129 view! {
130 tokens_view(
131 handle: handle.as_str(),
132 tokens: &listed,
133 issued: issued.as_str(),
134 error: error.as_str(),
135 // Cleared on success so the field is ready for the next one, kept on failure
136 // so a rejected name is not silently thrown away.
137 name: if issued.is_empty() { submitted.name.as_str() } else { "" },
138 // Kept on failure for the same reason the name is, and reset to the default
139 // on success so the next token does not silently inherit this one's choice.
140 expires: if issued.is_empty() {
141 submitted.expires.as_str()
142 } else {
143 TokenLifetime::default().as_str()
144 },
145 )
146 }
147}
148
149/// Revokes a token, then redirects so a reload cannot repeat it.
150#[page(POST "/{handle}/settings/tokens/{token}/revoke")]
151async fn revoke(cx: &Cx, Form(guard): Form<CsrfGuard>) -> Result {
152 csrf_verified(cx, &guard.csrf_token).await?;
153
154 let handle = own_settings(cx).await?;
155 let id = TokenId::from_trusted(path_param::<Token>(cx));
156
157 match revoke_token(&current_actor(cx).await?, &id, &tokens(cx)).await {
158 Ok(()) => {}
159 // Someone else's token, or none at all. Both are "no such token of yours".
160 Err(Error::Domain(DomainError::NotFound { .. })) => {}
161 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
162 }
163
164 view! {
165 (StatusCode::SEE_OTHER)
166 (location(&format!("/{handle}/settings/tokens"))?)
167 }
168}
169
170/// "Expires 2026-12-05", or that it does not.
171///
172/// The date alone, without the time: an expiry chosen as "90 days" is not a fact anyone
173/// needs to the minute, and the full timestamp is on the `title` for anyone who does.
174fn expiry(summary: &TokenSummary) -> String {
175 let Some(expires_at) = summary.expires_at else {
176 return "Never expires".to_owned();
177 };
178
179 let date = timestamp(expires_at)
180 .split(' ')
181 .next()
182 .unwrap_or_default()
183 .to_owned();
184
185 if summary.expired {
186 format!("Expired {date}")
187 } else {
188 format!("Expires {date}")
189 }
190}
191
192/// "Last used 2 hours ago", or that it never was.
193fn last_used(summary: &TokenSummary) -> String {
194 summary.last_used_at.map_or_else(
195 || "Never used".to_owned(),
196 |at| format!("Last used {}", ago(at)),
197 )
198}
199
200#[component]
201async fn tokens_view(
202 handle: &str,
203 tokens: &[TokenSummary],
204 issued: &str,
205 error: &str,
206 name: &str,
207 expires: &str,
208) -> Result {
209 view! {
210 narrow(
211 <h1 class="text-xl font-semibold tracking-tight">"Access tokens"</h1>
212 <p class="mt-1 text-sm text-muted-foreground">
213 "Use a token as the password when git asks. Your username can be anything."
214 </p>
215
216 if !issued.is_empty() {
217 <div class="mt-6 space-y-2">
218 flash(
219 kind: FlashKind::Success,
220 "Copy this now — it is not shown again."
221 )
222 <pre class="overflow-x-auto rounded-lg border border-border bg-surface px-4 py-3 font-mono text-sm">(issued)</pre>
223 </div>
224 }
225
226 if !error.is_empty() {
227 <div class="mt-6">
228 flash(kind: FlashKind::Error, (error))
229 </div>
230 }
231
232 <form method="post" action=(format!("/{handle}/settings/tokens")) class="mt-6 space-y-5">
233 csrf_field()
234 <div class="space-y-2">
235 label(attrs: attributes! { for="name" }, "Token name")
236 input(attrs: attributes! {
237 id="name"
238 name="name"
239 type="text"
240 value=(name)
241 placeholder="laptop"
242 required=(true)
243 })
244 <p class="text-xs text-muted-foreground">
245 "So you can tell which one to revoke later."
246 </p>
247 </div>
248
249 <div class="space-y-2">
250 label(attrs: attributes! { for="expires" }, "Expiry")
251 select(
252 attrs: attributes! { id="expires" name="expires" class="sm:w-48" },
253 for lifetime in TokenLifetime::ALL {
254 <option
255 value=(lifetime.as_str())
256 selected=(lifetime.as_str() == expires)
257 >(lifetime.label())</option>
258 }
259 )
260 <p class="text-xs text-muted-foreground">
261 "A token that expires stops working on its own if it is ever "
262 "leaked or forgotten. Pick "<span class="font-medium">"No expiry"</span>
263 " only for something nobody will be around to rotate."
264 </p>
265 </div>
266
267 button(attrs: attributes! { type="submit" }, "Create token")
268 </form>
269
270 <section class="mt-10">
271 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
272 "Your tokens"
273 </h2>
274
275 if tokens.is_empty() {
276 <p class="mt-2 rounded-lg border border-border px-4 py-6 text-center text-sm text-muted-foreground">
277 "No tokens yet."
278 </p>
279 } else {
280 <ul class="mt-2 divide-y divide-border rounded-lg border border-border">
281 for token in tokens {
282 // An expired token is dimmed rather than removed: it is
283 // exactly the row a person wants to find and clear out, and
284 // Revoke stays at full strength so it is still obviously
285 // clickable.
286 <li class="flex items-center justify-between gap-4 px-4 py-3">
287 <div
288 class=(if token.expired {
289 "min-w-0 space-y-1 opacity-60"
290 } else {
291 "min-w-0 space-y-1"
292 })
293 >
294 <div class="flex flex-wrap items-baseline gap-2">
295 <span class="font-medium">(token.name.as_str())</span>
296 badge(
297 variant: BadgeVariant::Outline,
298 "steid_pat_" (token.prefix.as_str()) "…"
299 )
300 if token.expired {
301 badge(variant: BadgeVariant::Secondary, "Expired")
302 }
303 </div>
304 <p class="text-xs text-muted-foreground">
305 <span title=(token.expires_at.map(timestamp).unwrap_or_default())>
306 (expiry(token))
307 </span>
308 " · "
309 <span title=(token.last_used_at.map(timestamp).unwrap_or_default())>
310 (last_used(token))
311 </span>
312 </p>
313 </div>
314 <form
315 method="post"
316 action=(format!("/{handle}/settings/tokens/{}/revoke", token.id))
317 >
318 csrf_field()
319 // Ghost and small, like a hook row's Delete: a
320 // filled button per row makes a list of ordinary
321 // things read as a list of warnings.
322 button(
323 attrs: attributes! { type="submit" },
324 variant: ButtonVariant::Ghost,
325 size: ButtonSize::Sm,
326 "Revoke"
327 )
328 </form>
329 </li>
330 }
331 </ul>
332 }
333 </section>
334
335 <p class="mt-8">
336 <a
337 href=(format!("/{handle}/settings"))
338 class="text-sm text-muted-foreground hover:text-foreground"
339 >"Back to settings"</a>
340 </p>
341 )
342 }
343}