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