authoravatarclover caruso<git@paperclover.net>2026-10-23 18:18:08-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-24 19:01:23-07:00
log608212cba743fa289f7d666112d5a4fc6e5b4fa9
treeaccd3d0effb07dcfc4bc1fc15c4b33297371c214
parent7e83355b579b72267ab1c4fdfb53e8daf2031581
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Sign in to Snow Globe with granted Astheno accounts

Snow sign on now offers Astheno, but only to accounts an admin links to an Astheno username on the Users page, at creation or later. The first sign-in Astheno verifies as that username binds the account, taking over an existing Shale guest; any other Astheno account is refused and nothing is created. Shale still turns any provider into a guest, but a linked Astheno identity signs in as its Snow Globe account instead. Assisted-by: claude-opus-5.5

8 files changed, 304 insertions(+), 78 deletions(-)

dashboard/src/auth.rs+6-15
......@@ -492,7 +492,10 @@ impl Store {
492492 }
493493 Ok(())
494494 }
495 fn next(&self, id: &str, flow: &str, path: &str) -> Result<String> {
495 pub(crate) fn next(&self, id: &str, flow: &str, path: &str) -> Result<String> {
496 if !array(&user(&self.db.lock().unwrap(), id)?["requiredActions"]).is_empty() {
497 return Ok("/account".into());
498 }
496499 if flow.is_empty() {
497500 if !path.starts_with('/')
498501 || path.starts_with("//")
......@@ -510,9 +513,6 @@ impl Store {
510513 "Guest accounts can use Shale. Open Shale to continue.",
511514 ));
512515 }
513 if !array(&user(&db, id)?["requiredActions"]).is_empty() {
514 return Ok("/account".into());
515 }
516516 let value = pending(&db, flow, "file", false)?;
517517 if value.is_null() {
518518 return Err(Error::new(
......@@ -901,11 +901,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
901901 if body["remember"] == false {
902902 session = session.replace(&format!("; Max-Age={SESSION_TTL}"), "");
903903 }
904 let next = if !array(&user["requiredActions"]).is_empty() {
905 "/account".into()
906 } else {
907 auth.next(&id, string(&body["flow"]), string(&body["next"]))?
908 };
904 let next = auth.next(&id, string(&body["flow"]), string(&body["next"]))?;
909905 return Ok(
910906 ([("set-cookie", session)], axum::Json(json!({"next":next}))).into_response(),
911907 );
......@@ -1104,12 +1100,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
11041100 if body.get("remember").unwrap_or(&value["remember"]) == false {
11051101 session = session.replace(&format!("; Max-Age={SESSION_TTL}"), "");
11061102 }
1107 let next =
1108 if !array(&self::user(&auth.db.lock().unwrap(), id)?["requiredActions"]).is_empty() {
1109 "/account".into()
1110 } else {
1111 auth.next(id, string(&value["flow"]), string(&value["next"]))?
1112 };
1103 let next = auth.next(id, string(&value["flow"]), string(&value["next"]))?;
11131104 return Ok(([("set-cookie", session)], axum::Json(json!({"next":next}))).into_response());
11141105 }
11151106 if path == "/auth/setup" {
dashboard/src/guest.rs+219-48
......@@ -84,15 +84,16 @@ pub fn provision(auth: &auth::Store, input: Value) -> Result<Value> {
8484}
8585
8686pub fn providers(auth: &auth::Store, next: &str) -> Result<Value> {
87 if oidc::guest_target(auth, next).is_err() {
88 return Ok(json!([]));
89 }
87 let shale = oidc::guest_target(auth, next).is_ok();
9088 let db = auth.db.lock().unwrap();
91 let mut query = db.prepare("SELECT id FROM guest_providers ORDER BY id")?;
89 let mut query =
90 db.prepare("SELECT id FROM guest_providers WHERE ?1 OR id='astheno' ORDER BY id")?;
9291 let mut ids = query
93 .query_map([], |r| r.get::<_, String>(0))?
92 .query_map([shale], |r| r.get::<_, String>(0))?
9493 .collect::<std::result::Result<Vec<_>, _>>()?;
95 ids.push("atproto".into());
94 if shale {
95 ids.push("atproto".into());
96 }
9697 Ok(json!(
9798 ids.iter()
9899 .map(|id| json!({"id":id,"name":known(id).unwrap_or(id)}))
......@@ -105,6 +106,15 @@ fn registration(auth: &auth::Store, provider: &str) -> Result<(String, String)>
105106 .optional()?.ok_or_else(|| Error::new(503, "This sign-in provider isn't available. Use your Snow Globe account or try again later."))
106107}
107108
109/// Shale takes any provider and mints guests; everywhere else only linked Astheno accounts get in.
110fn destination(auth: &auth::Store, provider: &str, next: &str) -> Result<(String, bool)> {
111 match oidc::guest_target(auth, next) {
112 Ok(next) => Ok((next, true)),
113 Err(_) if provider == "astheno" => Ok((next.to_owned(), false)),
114 Err(error) => Err(error),
115 }
116}
117
108118async fn response_bytes(mut response: reqwest::Response) -> Result<Vec<u8>> {
109119 let status = response.status();
110120 let endpoint = format!(
......@@ -507,20 +517,26 @@ fn account(
507517 .optional()?;
508518 if let Some(id) = existing {
509519 let profile = auth::user(&tx, &id)?;
510 if !is_guest(&profile) || profile["enabled"] != true {
511 return Err(Error::new(
512 403,
513 "This guest account is disabled. Contact Clover.",
514 ));
520 if profile["enabled"] != true {
521 return Err(Error::new(403, "This account is disabled. Contact Clover."));
522 }
523 if is_guest(&profile) {
524 tx.execute(
525 "UPDATE users SET profile=json_patch(profile,?) WHERE id=?",
526 sql![json!({"firstName":name,"attributes":{"picture":picture.map(|picture| vec![picture])}}).to_string(), id],
527 )?;
515528 }
516 tx.execute(
517 "UPDATE users SET profile=json_patch(profile,?) WHERE id=?",
518 sql![json!({"firstName":name,"attributes":{"picture":picture.map(|picture| vec![picture])}}).to_string(), id],
519 )?;
520529 tx.commit()?;
521530 return Ok(id);
522531 }
523 let id = create(&tx, provider, &username(provider, subject), name, picture)?;
532 let login = username(provider, subject);
533 let revived: Option<String> = tx
534 .query_row("SELECT id FROM users WHERE username=?", [&login], |r| r.get(0))
535 .optional()?;
536 let id = match revived {
537 Some(id) => id,
538 None => create(&tx, provider, &login, name, picture)?,
539 };
524540 tx.execute(
525541 "INSERT INTO external_identities VALUES (?,?,?)",
526542 sql![provider, subject, id],
......@@ -529,11 +545,94 @@ fn account(
529545 Ok(id)
530546}
531547
532/// Astheno's per-client subjects require binding reserved names at verified sign-in.
548/// Astheno's per-client subjects require binding granted names at verified sign-in. An account an admin linked to
549/// the name takes the identity over from a guest; otherwise a guest reserved under the name receives it.
533550fn claim(auth: &auth::Store, subject: &str, username: &str) -> Result<()> {
534 auth.db.lock().unwrap().execute(
535 "INSERT OR IGNORE INTO external_identities SELECT 'astheno',?,id FROM users WHERE username=? AND id NOT IN (SELECT user_id FROM external_identities)",
536 sql![subject, format!("guest-astheno-{username}")],
551 let mut db = auth.db.lock().unwrap();
552 let tx = db.transaction()?;
553 let linked: Option<String> = tx
554 .query_row(
555 "SELECT id FROM users WHERE json_extract(profile,'$.attributes.astheno[0]')=? AND id NOT IN (SELECT user_id FROM external_identities)",
556 [username],
557 |r| r.get(0),
558 )
559 .optional()?;
560 if let Some(id) = linked {
561 tx.execute(
562 "DELETE FROM external_identities WHERE provider='astheno' AND subject=? AND user_id IN (SELECT id FROM users WHERE json_extract(profile,'$.kind')='guest')",
563 [subject],
564 )?;
565 tx.execute(
566 "INSERT OR IGNORE INTO external_identities VALUES ('astheno',?,?)",
567 sql![subject, id],
568 )?;
569 } else {
570 tx.execute(
571 "INSERT OR IGNORE INTO external_identities SELECT 'astheno',?,id FROM users WHERE username=? AND id NOT IN (SELECT user_id FROM external_identities)",
572 sql![subject, format!("guest-astheno-{username}")],
573 )?;
574 }
575 tx.commit()?;
576 Ok(())
577}
578
579/// Snow Globe sign-in admits only accounts an admin linked to this identity.
580fn member(auth: &auth::Store, provider: &str, subject: &str) -> Result<String> {
581 let db = auth.db.lock().unwrap();
582 let id: Option<String> = db
583 .query_row(
584 "SELECT user_id FROM external_identities WHERE provider=? AND subject=?",
585 sql![provider, subject],
586 |r| r.get(0),
587 )
588 .optional()?;
589 id.filter(|id| {
590 auth::user(&db, id).is_ok_and(|user| !is_guest(&user) && user["enabled"] == true)
591 })
592 .ok_or_else(|| Error::new(403, "This account isn't linked to a Snow Globe account."))
593}
594
595fn astheno_name(handle: &str) -> Result<String> {
596 let name = handle.to_lowercase();
597 if name.len() > 16
598 || !name.starts_with(|c: char| c.is_ascii_alphanumeric())
599 || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
600 {
601 return Err(Error::new(400, "Enter an Astheno username."));
602 }
603 Ok(name)
604}
605
606/// Grants Snow Globe sign-in to whoever Astheno verifies as this username; the first such sign-in binds the account.
607pub fn link(db: &Connection, id: &str, handle: &str) -> Result<()> {
608 let name = astheno_name(handle.trim().trim_start_matches('@'))?;
609 if is_guest(&auth::user(db, id)?) {
610 return Err(Error::new(400, "Guests sign in with their own provider."));
611 }
612 unlink(db, id)?;
613 let taken: bool = db.query_row(
614 "SELECT EXISTS(SELECT 1 FROM users WHERE json_extract(profile,'$.attributes.astheno[0]')=?)",
615 [&name],
616 |r| r.get(0),
617 )?;
618 if taken {
619 return Err(Error::new(409, "Another account already has that Astheno username."));
620 }
621 db.execute(
622 "UPDATE users SET profile=json_patch(profile,?) WHERE id=?",
623 sql![json!({"attributes":{"astheno":[name]}}).to_string(), id],
624 )?;
625 Ok(())
626}
627
628pub fn unlink(db: &Connection, id: &str) -> Result<()> {
629 db.execute(
630 "DELETE FROM external_identities WHERE provider='astheno' AND user_id=?",
631 [id],
632 )?;
633 db.execute(
634 "UPDATE users SET profile=json_patch(profile,'{\"attributes\":{\"astheno\":null}}') WHERE id=?",
635 [id],
537636 )?;
538637 Ok(())
539638}
......@@ -635,16 +734,7 @@ pub async fn add(auth: &auth::Store, provider: &str, handle: &str) -> Result<Val
635734 let name = handle.unwrap_or_else(|| did.clone());
636735 grant(auth, provider, Some(&did), &name)
637736 }
638 _ => {
639 let name = handle.to_lowercase();
640 if name.len() > 16
641 || !name.starts_with(|c: char| c.is_ascii_alphanumeric())
642 || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
643 {
644 return Err(Error::new(400, "Enter an Astheno username."));
645 }
646 grant(auth, provider, None, &name)
647 }
737 _ => grant(auth, provider, None, &astheno_name(handle)?),
648738 }
649739}
650740
......@@ -721,8 +811,9 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
721811 let callback = format!("{}auth/guest/callback/{provider}", auth.origin);
722812 if parts[3] == "start" {
723813 auth.limit(headers, "guest")?;
724 let next = oidc::guest_target(
814 let (next, _) = destination(
725815 auth,
816 provider,
726817 query.get("next").map(String::as_str).unwrap_or_default(),
727818 )?;
728819 if provider == "atproto" {
......@@ -763,7 +854,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
763854 let state = auth::issue(
764855 &auth.db.lock().unwrap(),
765856 "guest",
766 json!({"provider":provider,"next":next,"verifier":verifier,"nonce":nonce}),
857 json!({"provider":provider,"next":next,"flow":query.get("flow"),"verifier":verifier,"nonce":nonce}),
767858 300,
768859 )?;
769860 let mut target = url::Url::parse(if provider == "github" {
......@@ -822,7 +913,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
822913 }
823914 auth::pending(&db, state, "guest", true)?
824915 };
825 let next = oidc::guest_target(auth, string(&flow["next"]))?;
916 let (next, shale) = destination(auth, provider, string(&flow["next"]))?;
826917 let result = async {
827918 let code = query
828919 .get("code")
......@@ -833,7 +924,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
833924 "Sign-in wasn't completed. Return to Shale and try again.",
834925 )
835926 })?;
836 if provider == "atproto" {
927 let id = if provider == "atproto" {
837928 let profile = tokio::time::timeout(
838929 Duration::from_secs(45),
839930 atproto::finish(
......@@ -860,22 +951,28 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
860951 id
861952 ],
862953 )?;
863 return auth.create_session(&id, "dashboard", headers, None);
864 }
865 let (client, secret) = registration(auth, provider)?;
866 let (subject, name, picture, handle) =
867 exchange(&http()?, provider, &client, &secret, code, &callback, &flow).await?;
868 if let Some(handle) = handle {
869 claim(auth, &subject, &handle)?;
870 }
871 let id = account(auth, provider, &subject, &name, picture.as_deref())?;
872 auth.create_session(&id, "dashboard", headers, None)
954 id
955 } else {
956 let (client, secret) = registration(auth, provider)?;
957 let (subject, name, picture, handle) =
958 exchange(&http()?, provider, &client, &secret, code, &callback, &flow).await?;
959 if let Some(handle) = handle {
960 claim(auth, &subject, &handle)?;
961 }
962 if shale {
963 account(auth, provider, &subject, &name, picture.as_deref())?
964 } else {
965 member(auth, provider, &subject)?
966 }
967 };
968 let session = auth.create_session(&id, "dashboard", headers, None)?;
969 Ok::<_, Error>((session, auth.next(&id, string(&flow["flow"]), &next)?))
873970 }
874971 .await;
875972 match result {
876 Ok(session) => Ok((
973 Ok((session, location)) => Ok((
877974 StatusCode::FOUND,
878 [("location", next), ("set-cookie", session)],
975 [("location", location), ("set-cookie", session)],
879976 axum::response::AppendHeaders([("set-cookie", auth::set_cookie(COOKIE, "", Some(0)))]),
880977 )
881978 .into_response()),
......@@ -889,7 +986,12 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
889986 [
890987 (
891988 "location",
892 format!("/sign-in?next={}&guest_error=1", encoded(&next)),
989 format!(
990 "/sign-in?next={}&flow={}&guest_error={}",
991 encoded(&next),
992 encoded(string(&flow["flow"])),
993 if error.status == 403 { "denied" } else { "1" }
994 ),
893995 ),
894996 ("set-cookie", auth::set_cookie(COOKIE, "", Some(0))),
895997 ],
......@@ -904,7 +1006,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Response {
9041006 Ok(response) => response,
9051007 Err(error) => Error::new(
9061008 error.status,
907 "Guest sign-in couldn't continue. Return to Shale and try again.",
1009 "Sign-in couldn't continue. Go back and try again.",
9081010 )
9091011 .into_response(),
9101012 };
......@@ -1212,6 +1314,75 @@ mod tests {
12121314 std::fs::remove_dir_all(path).unwrap();
12131315 }
12141316
1317 #[test]
1318 fn only_granted_astheno_names_reach_snow_globe_accounts() {
1319 let path = std::env::temp_dir().join(format!("guest-link-test-{}", uuid::Uuid::new_v4()));
1320 let auth = auth::Store::new(
1321 &path,
1322 "https://snowglobe.paperclover.net",
1323 "https://file.paperclover.net",
1324 "auth.paperclover.net",
1325 )
1326 .unwrap();
1327 let add = |id: &str, name: &str| {
1328 auth.db.lock().unwrap().execute("INSERT INTO users(id,profile) VALUES (?,?)", [id, &json!({"username":name,"enabled":true,"requiredActions":[]}).to_string()]).unwrap();
1329 };
1330 add("snow", "snow");
1331 add("meghan", "meghan");
1332 let link = |id: &str, handle: &str| link(&auth.db.lock().unwrap(), id, handle);
1333 // What the callback does after Astheno verifies `handle` as `subject`.
1334 let shale = |subject: &str, handle: &str| {
1335 claim(&auth, subject, handle).unwrap();
1336 account(&auth, "astheno", subject, handle, None).unwrap()
1337 };
1338 let snow = |subject: &str, handle: &str| {
1339 claim(&auth, subject, handle).unwrap();
1340 member(&auth, "astheno", subject)
1341 };
1342
1343 // Ungranted names are Shale guests and never reach an account, even one with the same username.
1344 let guest = shale("sub-clover", "clover");
1345 let impostor = shale("sub-snow", "snow");
1346 assert!(is_guest(&auth::user(&auth.db.lock().unwrap(), &impostor).unwrap()));
1347 assert_eq!(snow("sub-snow", "snow").unwrap_err().status, 403);
1348 assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403);
1349
1350 // A grant binds the first verified sign-in, taking over an existing guest.
1351 link("snow", " @Clover ").unwrap();
1352 link("meghan", "meghan").unwrap();
1353 assert_eq!(snow("sub-clover", "clover").unwrap(), "snow");
1354 assert_eq!(shale("sub-clover", "clover"), "snow");
1355 assert!(auth::user(&auth.db.lock().unwrap(), "snow").unwrap()["firstName"].is_null());
1356 assert_eq!(shale("sub-meghan", "meghan"), "meghan");
1357 assert_eq!(snow("sub-meghan", "meghan").unwrap(), "meghan");
1358
1359 // Once bound, another subject presenting the name is just a guest.
1360 assert_ne!(shale("sub-reused", "meghan"), "meghan");
1361 assert_eq!(snow("sub-reused", "meghan").unwrap_err().status, 403);
1362
1363 // Names are unique, guests can't be linked, and names must be plausible.
1364 assert_eq!(link("meghan", "clover").unwrap_err().status, 409);
1365 assert_eq!(link(&impostor, "snow").unwrap_err().status, 400);
1366 assert_eq!(link("meghan", "has space").unwrap_err().status, 400);
1367
1368 // Disabling or unlinking ends access; the guest it replaced comes back on Shale.
1369 auth.db.lock().unwrap().execute("UPDATE users SET profile=json_set(profile,'$.enabled',json('false')) WHERE id='snow'", []).unwrap();
1370 assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403);
1371 unlink(&auth.db.lock().unwrap(), "snow").unwrap();
1372 assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403);
1373 assert_eq!(shale("sub-clover", "clover"), guest);
1374
1375 // Snow Globe offers only Astheno, once it is registered.
1376 assert_eq!(providers(&auth, "/").unwrap(), json!([]));
1377 provision(&auth, json!({"provider":"astheno","enabled":true,"clientId":"client","clientSecret":"0123456789abcdef"})).unwrap();
1378 provision(&auth, json!({"provider":"github","enabled":true,"clientId":"client","clientSecret":"0123456789abcdef"})).unwrap();
1379 assert_eq!(providers(&auth, "/").unwrap(), json!([{"id":"astheno","name":"Astheno"}]));
1380 assert_eq!(destination(&auth, "github", "/").unwrap_err().status, 400);
1381 assert_eq!(destination(&auth, "astheno", "/").unwrap(), ("/".to_owned(), false));
1382 drop(auth);
1383 std::fs::remove_dir_all(path).unwrap();
1384 }
1385
12151386 #[tokio::test]
12161387 async fn adding_needs_a_registered_provider_and_a_plausible_name() {
12171388 let path = std::env::temp_dir().join(format!("guest-add-test-{}", uuid::Uuid::new_v4()));
dashboard/src/users.rs+18-7
......@@ -231,8 +231,8 @@ pub async fn route(
231231 if parts.is_empty() && method == Method::POST {
232232 let mut profile = profile(&body["profile"], true)?;
233233 let setup = string(&body["setup"]["kind"]);
234 if setup != "invite" && setup != "password" {
235 return Err(Error::new(400, "Choose an invitation or a password."));
234 if !["invite", "password", "astheno"].contains(&setup) {
235 return Err(Error::new(400, "Choose an invitation, a password, or Astheno."));
236236 }
237237 let hash = if setup == "password" {
238238 Some(
......@@ -249,11 +249,11 @@ pub async fn route(
249249 let id = uuid::Uuid::new_v4().to_string();
250250 profile["enabled"] = json!(true);
251251 profile["emailVerified"] = json!(false);
252 profile["requiredActions"] = json!([if hash.is_some() {
253 "UPDATE_PASSWORD"
254 } else {
255 "SETUP"
256 }]);
252 profile["requiredActions"] = match setup {
253 "password" => json!(["UPDATE_PASSWORD"]),
254 "invite" => json!(["SETUP"]),
255 _ => json!([]),
256 };
257257 profile["createdTimestamp"] = json!((now() * 1000.0) as i64);
258258 profile["attributes"] = json!({});
259259 {
......@@ -278,6 +278,9 @@ pub async fn route(
278278 if let Some(hash) = &hash {
279279 auth::set_password(&transaction, &id, hash)?;
280280 }
281 if setup == "astheno" || !string(&body["astheno"]).is_empty() {
282 guest::link(&transaction, &id, string(&body["astheno"]))?;
283 }
281284 transaction.commit()?;
282285 }
283286 return Ok((StatusCode::CREATED,axum::Json(json!({"id":id,"url":if setup=="invite" {Some(app.auth.setup_link(&id)?)}else{None}}))).into_response());
......@@ -386,6 +389,14 @@ pub async fn route(
386389 identity::confirm_key(&transaction,id,&fingerprint)?;
387390 Value::Null
388391 }
392 [_, "astheno"] if method == Method::PUT => {
393 guest::link(&transaction, id, string(&body["handle"]))?;
394 Value::Null
395 }
396 [_, "astheno"] if method == Method::DELETE => {
397 guest::unlink(&transaction, id)?;
398 Value::Null
399 }
389400 [_, "credentials"] if method == Method::GET => auth::credentials(&transaction, id)?,
390401 [_, "logout"] if method == Method::POST => {
391402 transaction.execute("DELETE FROM sessions WHERE user_id=?", [id])?;
dashboard/web/api.contract.ts+5-1
......@@ -229,7 +229,7 @@ export type Api = Hono<{}, {
229229 };
230230 "/users": {
231231 $get: Endpoint<{users:(User & {sessions:Session[]})[]; groups:Group[]}>;
232 $post: Endpoint<{ id: string; url: string | null }, { json: { profile: { email: string; firstName: string; lastName: string; username: string; }; groups: string[]; setup: { kind: "invite"; } | { kind: "password"; password: string; }; }; }, 201>;
232 $post: Endpoint<{ id: string; url: string | null }, { json: { profile: { email: string; firstName: string; lastName: string; username: string; }; groups: string[]; setup: { kind: "invite"; } | { kind: "password"; password: string; } | { kind: "astheno"; }; astheno?: string; }; }, 201>;
233233 };
234234 "/users/guests": {
235235 $post: Endpoint<{ id: string; created: boolean }, { json: { provider: "github" | "astheno" | "atproto"; handle: string; }; }>;
......@@ -241,6 +241,10 @@ export type Api = Hono<{}, {
241241 "/users/groups": {
242242 $put: Endpoint<null, { json: { users: string[]; add: string[]; remove: string[]; }; }, 204, "body">;
243243 };
244 "/users/:id/astheno": {
245 $put: Endpoint<null, { param: { id: string; }; json: { handle: string; }; }, 204, "body">;
246 $delete: Endpoint<null, { param: { id: string; }; }, 204, "body">;
247 };
244248 "/users/:id/groups/:group": {
245249 $put: Endpoint<null, { param: { id: string; group: string; }; }, 204, "body">;
246250 $delete: Endpoint<null, { param: { id: string; group: string; }; }, 204, "body">;
dashboard/web/pages/SignIn.tsx+2-2
......@@ -22,7 +22,7 @@ export function SignIn() {
2222 const [passwordStep, setPasswordStep] = createSignal(false);
2323 const [visible, setVisible] = createSignal(false);
2424 const [busy, setBusy] = createSignal(false);
25 const [error, setError] = createSignal(params.has("guest_error") ? (atproto ? "Sign-in couldn't start. Check your handle and try again." : "Guest sign-in wasn't completed. Choose a provider to try again.") : "");
25 const [error, setError] = createSignal(params.has("guest_error") ? (params.get("guest_error") === "denied" ? "That account can't sign in here. Ask Clover for access." : atproto ? "Sign-in couldn't start. Check your handle and try again." : "Sign-in wasn't completed. Choose a provider to try again.") : "");
2626 const [notice, setNotice] = createSignal("");
2727 let conditional: AbortController | undefined;
2828 let disposed = false;
......@@ -103,7 +103,7 @@ export function SignIn() {
103103 }>
104104 <Show when={!setup && !passwordStep() && status()?.providers?.length}>
105105 <div id="kc-social-providers" class="guest-providers">
106 <For each={status()?.providers}>{(provider) => <a rel="external" data-provider={provider.id} class="pf-v5-c-button pf-m-primary pf-m-block" href={provider.id === "atproto" ? `/sign-in?${statusQuery}&atproto=1` : `/auth/guest/start/${provider.id}?next=${encodeURIComponent(params.get("next") ?? "")}`}>{provider.id === "atproto" ? <span innerHTML={atprotoIcon} /> : provider.id === "astheno" ? <Stone size={18} aria-hidden="true" /> : <img src={githubIcon} width="18" height="18" alt="" />}<span>continue with {provider.name}</span></a>}</For>
106 <For each={status()?.providers}>{(provider) => <a rel="external" data-provider={provider.id} class="pf-v5-c-button pf-m-primary pf-m-block" href={provider.id === "atproto" ? `/sign-in?${statusQuery}&atproto=1` : `/auth/guest/start/${provider.id}?${new URLSearchParams({ next: params.get("next") ?? "", flow: params.get("flow") ?? "" })}`}>{provider.id === "atproto" ? <span innerHTML={atprotoIcon} /> : provider.id === "astheno" ? <Stone size={18} aria-hidden="true" /> : <img src={githubIcon} width="18" height="18" alt="" />}<span>continue with {provider.name}</span></a>}</For>
107107 </div>
108108 </Show>
109109 <div id="kc-form"><div id="kc-form-wrapper">
dashboard/web/pages/Users.tsx+36-5
......@@ -34,6 +34,8 @@ const GUESTS = {
3434 atproto: { name: "AT Protocol", field: "AT handle", placeholder: "alice.bsky.social" },
3535} as const;
3636
37const ASTHENO_HINT = "Whoever holds this Astheno username can sign in as this account, on Snow Globe and Shale. Their first sign-in binds it.";
38
3739const STATES = { all: "users", guests: "guests", disabled: "disabled", pending: "setup pending" } as const;
3840
3941type Params = { q?: string; group?: string; state?: keyof typeof STATES };
......@@ -247,7 +249,7 @@ function List(props: { data: Resource<Data>; ready: Accessor<Data | undefined>;
247249 title: "New user",
248250 confirmLabel: "create user",
249251 body: () => {
250 const [invite, setInvite] = createSignal(true);
252 const [kind, setKind] = createSignal<"invite" | "password" | "astheno">("invite");
251253 return (
252254 <>
253255 <label class="field">username<input name="username" class="search" required autocomplete="off" spellcheck={false} autofocus /></label>
......@@ -267,11 +269,17 @@ function List(props: { data: Resource<Data>; ready: Accessor<Data | undefined>;
267269 <div class="field">
268270 first sign-in
269271 <TabBar label="First sign-in">
270 <button type="button" aria-pressed={invite()} onClick={() => setInvite(true)}>create an invitation link</button>
271 <button type="button" aria-pressed={!invite()} onClick={() => setInvite(false)}>set a password</button>
272 <button type="button" aria-pressed={kind() === "invite"} onClick={() => setKind("invite")}>create an invitation link</button>
273 <button type="button" aria-pressed={kind() === "password"} onClick={() => setKind("password")}>set a password</button>
274 <button type="button" aria-pressed={kind() === "astheno"} onClick={() => setKind("astheno")}>astheno only</button>
272275 </TabBar>
276 <input type="hidden" name="kind" value={kind()} />
273277 </div>
274 <Show when={!invite()}>
278 <label class="field">astheno username{kind() === "astheno" ? "" : " (optional)"}
279 <input name="astheno" class="search" required={kind() === "astheno"} maxLength={17} autocomplete="off" spellcheck={false} placeholder="janedoe" />
280 <span class="hint">{ASTHENO_HINT}</span>
281 </label>
282 <Show when={kind() === "password"}>
275283 <label class="field">temporary password
276284 <input name="password" class="search" type="password" required minLength={8} maxLength={1024} autocomplete="new-password" />
277285 <span class="hint">They pick their own at first sign-in</span>
......@@ -286,7 +294,8 @@ function List(props: { data: Resource<Data>; ready: Accessor<Data | undefined>;
286294 json: {
287295 profile: { username: text("username"), email: text("email"), firstName: text("firstName"), lastName: text("lastName") },
288296 groups: form.getAll("groups").map(String),
289 setup: form.has("password") ? { kind: "password", password: text("password") } : { kind: "invite" },
297 setup: text("kind") === "password" ? { kind: "password", password: text("password") } : { kind: text("kind") as "invite" | "astheno" },
298 astheno: text("astheno") || undefined,
290299 },
291300 }));
292301 await props.refetch();
......@@ -546,6 +555,22 @@ function Profile(props: { user: User; data: Data; refetch: () => unknown }) {
546555 setSetupLink(""); toast("Revoked the setup link");
547556 });
548557
558 const astheno = () => props.user.attributes?.astheno?.[0];
559 const linkAstheno = () => showTextDialog({
560 title: `Astheno sign-in for ${props.user.username}`,
561 label: "Astheno username",
562 placeholder: "janedoe",
563 body: () => <div class="field"><span class="hint">{ASTHENO_HINT}</span></div>,
564 confirmLabel: "link",
565 onConfirm: async (handle) => {
566 await parseResponse(api.users[":id"].astheno.$put({ param: param(), json: { handle } }));
567 await props.refetch();
568 },
569 });
570 const unlinkAstheno = () => run("astheno", async () => {
571 await parseResponse(api.users[":id"].astheno.$delete({ param: param() }));
572 await props.refetch();
573 });
549574 const setPassword = () => showConfirmDialog({
550575 title: `Set ${props.user.username}'s password`,
551576 body: <><label class="field">new password, at least 8 characters<input name="password" class="search" type="password" required minLength={8} maxLength={1024} autocomplete="new-password" /></label><Checkbox name="temporary" checked>ask for a new one at next sign-in</Checkbox></>,
......@@ -658,6 +683,12 @@ function Profile(props: { user: User; data: Data; refetch: () => unknown }) {
658683 );
659684 }}
660685 </Loaded>
686 <h2 class="card-title opens">astheno</h2>
687 <Show when={astheno()} fallback={<p class="muted">Not linked. Only linked accounts can sign in with Astheno.</p>}>
688 <p>{astheno()}</p>
689 </Show>
690 <button class="button small" disabled={!!astheno() || busy() === "astheno"} onClick={linkAstheno}>link</button>{" "}
691 <button class="button small" disabled={!astheno() || busy() === "astheno"} onClick={unlinkAstheno}>unlink</button>
661692 <h2 class="card-title opens">setup link</h2>
662693 <p class="muted">One use, valid for 24 hours. A new link replaces the previous one.</p>
663694 <button class="button small" disabled={!props.user.enabled || busy() === "link"} onClick={createLink}>create setup link</button>{" "}
tools/dashboard-auth-test.py+17
......@@ -300,6 +300,23 @@ def main():
300300 replacement = request('/api/users/' + invitation['id'] + '/setup-link', 'POST', {}, cookies)['url']
301301 request('/api/users/' + invitation['id'] + '/setup-link', 'DELETE', {}, cookies, 204)
302302 request('/auth/status?' + replacement.split('?', 1)[1], cookies={}, status=410)
303 with sqlite3.connect(data / 'accounts.sqlite') as db:
304 db.execute("INSERT INTO guest_providers VALUES ('astheno','client','0123456789abcdef')")
305 assert request('/auth/status', cookies={})['providers'] == [{'id': 'astheno', 'name': 'Astheno'}]
306 identity = {'profile': {'username': 'astheno-only', 'email': '', 'firstName': '', 'lastName': ''}, 'groups': [], 'setup': {'kind': 'astheno'}}
307 request('/api/users', 'POST', identity, cookies, 400)
308 only = request('/api/users', 'POST', {**identity, 'astheno': ' @Janedoe '}, cookies, 201)
309 assert only['url'] is None
310 linked = {u['id']: u for u in request('/api/users', cookies=cookies)['users']}[only['id']]
311 assert linked['requiredActions'] == [] and linked['attributes']['astheno'] == ['janedoe']
312 request('/api/users/' + invitation['id'] + '/astheno', 'PUT', {'handle': 'janedoe'}, cookies, 409)
313 request('/api/users/' + only['id'] + '/astheno', 'PUT', {'handle': 'janedoe'}, cookies, 204)
314 request('/api/users/' + only['id'] + '/astheno', 'DELETE', {}, cookies, 204)
315 assert 'astheno' not in {u['id']: u for u in request('/api/users', cookies=cookies)['users']}[only['id']].get('attributes', {})
316 redirect = request('/auth/guest/start/astheno?next=%2F', status=302, include_headers=True)
317 assert redirect['location'].startswith('https://identity.astheno.software/authorize?')
318 request('/auth/guest/start/github?next=%2F', status=400)
319 request('/auth/guest/start/atproto?next=%2F', status=400)
303320 request('/api/users/' + invitation['id'], 'PATCH', {'enabled': False}, cookies, 204)
304321 request('/api/me', cookies=newcomer, status=401)
305322 stop(); start()
tools/guest-provider.py+1
......@@ -6,6 +6,7 @@ https://shale.paperclover.net and callback
66https://snowglobe.paperclover.net/auth/guest/callback/github.
77For Astheno Identity, register a confidential OpenID Connect client with callback
88https://snowglobe.paperclover.net/auth/guest/callback/astheno and openid/profile scopes.
9The same client signs in Snow Globe accounts linked to an Astheno username on the Users page.
910GitHub requests only read:user. Neither provider grants repository access.
1011
1112Run: python3 tools/guest-provider.py github --client-id CLIENT_ID