~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

The console switches between accounts signed in in one browser

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:console/switch-accounts
.claude/skills/ui/SKILL.md+1−0
@@ -31,6 +31,7 @@ just look /g/riders.groups.test --as bob # a group bob is not in
just look /g/lanterns.groups.test --as alice --click 'button[popovertarget=invite]' # a dialog open
just look /g/lanterns.groups.test/settings --as alice --element .group-card --all # one element, in all four
just look / --as alice --phone --dark --click '.user-menu summary' # a menu, on a phone
just look / --as bob,alice --click '.user-menu summary' # signed in to both, alice in use, bob to switch to
just look /new --as alice --type '[name=displayName]=A name long enough to wrap twice over on a phone' # typed into, then shot
just look /g/lanterns.groups.test --as alice --out target/look/before --name group # pictures to keep apart
```
crates/group-host/src/actors.rs+10−3
@@ -18,8 +18,8 @@ use std::sync::Arc;
type Answer = Result<Json<Value>, XrpcError>;
/// Who is asking, by the console's cookie or service auth: nothing, for
/// no one.
/// Who is asking, by the console's cookie or service auth, and the other
/// accounts the browser is signed in to: nothing, for no one.
pub async fn get_viewer(State(host): State<Arc<Host>>, headers: HeaderMap) -> Answer {
let signup = host.config.signup_pds.as_str();
let Some(me) = caller(&host, &headers, &format!("{NS}.getViewer")).await? else {
@@ -30,7 +30,14 @@ pub async fn get_viewer(State(host): State<Arc<Host>>, headers: HeaderMap) -> An
if let Some(handle) = doc.as_ref().and_then(did::handle) {
actor["handle"] = json!(handle);
}
Ok(Json(json!({ "actor": actor, "signUpAt": signup })))
let mut answer = json!({ "actor": actor, "signUpAt": signup });
let others = host.console_others(&headers, Some(&me));
let others = others.map_err(XrpcError::internal)?;
if !others.is_empty() {
let views = futures::future::join_all(others.iter().map(|(d, _)| host.actor_view(d)));
answer["accounts"] = json!(views.await);
}
Ok(Json(answer))
}
impl Host {
crates/group-host/src/console_login.rs+132−9
@@ -12,6 +12,12 @@
//! else's approval cannot sign a person in as them. Signing out refuses
//! every cookie signed before.
//!
//! A browser can be signed in to several accounts at once: signing in to
//! another keeps the one before in a second cookie, of such signed
//! cookies, the one used last first, and switching (`/console/switch`)
//! swaps one of those for the one in use, with no sign-in. Signing out
//! goes on as the one used last, if any is left.
//!
//! Every server a person's handle leads to (their PDS, its authorization
//! server) is reached only at a public address, as a client's metadata is.
//!
@@ -24,10 +30,10 @@ use crate::time::now_millis;
use crate::xrpc::XrpcError;
use atproto::jose;
use atproto::{Curve, Keypair, did};
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{AppendHeaders, IntoResponse, Redirect, Response};
use axum::{Form, Json};
use rusqlite::{OptionalExtension, params};
use serde_json::{Value, json};
use std::collections::HashMap;
@@ -36,6 +42,12 @@ use std::sync::Arc;
/// The session cookie, and the cookie naming a sign-in under way.
pub const COOKIE: &str = "group_host_session";
const STARTED: &str = "group_host_login";
/// The cookie holding the other accounts a browser is signed in to: their
/// session cookies, `~` between, the one used last first.
const OTHERS: &str = "group_host_accounts";
/// How many other accounts a browser stays signed in to; signing in to one
/// more lets go of the one used least lately.
const MOST: usize = 4;
/// How long a sign-in lasts, and how long approving one may take.
const LASTS: i64 = 30 * 86_400_000;
const TAKES: i64 = 15 * 60_000;
@@ -158,6 +170,14 @@ pub fn cookie_of<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
.map(|(_, v)| v)
}
/// The `Set-Cookie` keeping `others`, as many as a browser keeps: none
/// clears it.
fn others_cookie(host: &Host, others: &[(String, String)]) -> String {
let kept: Vec<&str> = others.iter().take(MOST).map(|(_, v)| v.as_str()).collect();
let max_age = if kept.is_empty() { 0 } else { LASTS / 1000 };
cookie(host, OTHERS, &kept.join("~"), max_age)
}
/// A page of the console's to go back to: a path there, never elsewhere.
fn back_to(asked: Option<&String>) -> String {
let path = asked.map_or("/", String::as_str);
@@ -206,7 +226,36 @@ impl Host {
/// Who a request's session cookie names, while it lasts and they have
/// not signed out since it was signed.
pub fn console_caller(&self, headers: &HeaderMap) -> anyhow::Result<Option<String>> {
let Some((claims, sig)) = cookie_of(headers, COOKIE).and_then(|c| c.split_once('.')) else {
match cookie_of(headers, COOKIE) {
Some(value) => self.session_of(value),
None => Ok(None),
}
}
/// The other accounts a request's cookies hold, with their session
/// cookies, the one used last first: only those that still hold, each
/// once, and never `but`.
pub fn console_others(
&self,
headers: &HeaderMap,
but: Option<&str>,
) -> anyhow::Result<Vec<(String, String)>> {
let mut found: Vec<(String, String)> = Vec::new();
for value in cookie_of(headers, OTHERS).unwrap_or_default().split('~') {
let Some(did) = self.session_of(value)? else {
continue;
};
if Some(did.as_str()) != but && found.iter().all(|(d, _)| *d != did) {
found.push((did, value.to_string()));
}
}
Ok(found)
}
/// Who the session cookie `value` names, while it lasts and they have
/// not signed out since it was signed.
fn session_of(&self, value: &str) -> anyhow::Result<Option<String>> {
let Some((claims, sig)) = value.split_once('.') else {
return Ok(None);
};
if jose::b64(hmac(&self.cookie_key(), claims.as_bytes())) != sig {
@@ -565,22 +614,96 @@ pub async fn callback(
&host.session_cookie(&p.did, now),
LASTS / 1000,
);
// The account in use before, if another, is kept beside it.
let before = host.console_caller(&headers).map_err(XrpcError::internal)?;
let mut others = host
.console_others(&headers, Some(&p.did))
.map_err(XrpcError::internal)?;
if let (Some(did), Some(value)) = (before, cookie_of(&headers, COOKIE))
&& did != p.did
{
others.retain(|(d, _)| *d != did);
others.insert(0, (did, value.to_string()));
}
tracing::info!(did = p.did, "signed in to the console");
let headers = AppendHeaders([(header::SET_COOKIE, session), (header::SET_COOKIE, done)]);
Ok((headers, Redirect::to(&p.back)).into_response())
let mut res = Redirect::to(&p.back).into_response();
let set = res.headers_mut();
for c in [session, done] {
set.append(header::SET_COOKIE, c.parse().expect("a cookie is a header"));
}
if !others.is_empty() || cookie_of(&headers, OTHERS).is_some() {
let kept = others_cookie(&host, &others);
set.append(
header::SET_COOKIE,
kept.parse().expect("a cookie is a header"),
);
}
Ok(res)
}
/// Switches the browser to `did`, another account it is signed in to,
/// and back to the page `back`: its cookie becomes the one in use, and the
/// one in use is kept beside it, first.
pub async fn switch(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Form(form): Form<HashMap<String, String>>,
) -> Result<Response, XrpcError> {
let to = form.get("did").map(String::as_str).unwrap_or_default();
let current = host.console_caller(&headers).map_err(XrpcError::internal)?;
let mut others = host
.console_others(&headers, current.as_deref())
.map_err(XrpcError::internal)?;
let Some(at) = others.iter().position(|(did, _)| did == to) else {
let why = "this browser is not signed in to that account";
return Ok(failed(StatusCode::BAD_REQUEST, why));
};
let (_, value) = others.remove(at);
if let (Some(did), Some(was)) = (current, cookie_of(&headers, COOKIE)) {
others.insert(0, (did, was.to_string()));
}
let headers = AppendHeaders([
(
header::SET_COOKIE,
cookie(&host, COOKIE, &value, LASTS / 1000),
),
(header::SET_COOKIE, others_cookie(&host, &others)),
]);
Ok((headers, Redirect::to(&back_to(form.get("back")))).into_response())
}
/// Signs out: this cookie, and every one signed before now.
/// Signs out: this cookie, and every one signed before now. The browser
/// goes on as the other account it used last, if it is signed in to one.
pub async fn logout(
State(host): State<Arc<Host>>,
headers: HeaderMap,
) -> Result<Response, XrpcError> {
let who = host.console_caller(&headers).map_err(XrpcError::internal)?;
if let Some(did) = who {
if let Some(did) = &who {
host.store
.sign_out(&did, now_millis())
.sign_out(did, now_millis())
.map_err(XrpcError::internal)?;
}
let gone = cookie(&host, COOKIE, "", 0);
Ok(([(header::SET_COOKIE, gone)], Redirect::to("/")).into_response())
// Read once they are signed out, so none of their cookies is left.
let mut others = host
.console_others(&headers, who.as_deref())
.map_err(XrpcError::internal)?;
let next = match others.is_empty() {
true => cookie(&host, COOKIE, "", 0),
false => cookie(&host, COOKIE, &others.remove(0).1, LASTS / 1000),
};
let mut res = Redirect::to("/").into_response();
let set = res.headers_mut();
set.append(
header::SET_COOKIE,
next.parse().expect("a cookie is a header"),
);
if cookie_of(&headers, OTHERS).is_some() {
let kept = others_cookie(&host, &others);
set.append(
header::SET_COOKIE,
kept.parse().expect("a cookie is a header"),
);
}
Ok(res)
}
crates/group-host/src/lib.rs+1−0
@@ -440,6 +440,7 @@ pub fn router(host: Arc<Host>) -> Router {
post(account_move::cancel_account_move),
)
.route("/console/callback", get(console_login::callback))
.route("/console/switch", post(console_login::switch))
.route("/console/logout", post(console_login::logout))
.merge(token_routes())
.merge(oauth_routes())
crates/group-host/tests/console_login.rs+142−2
@@ -1,5 +1,6 @@
//! Signing in to the console as oneself, at one's own PDS, as a
//! confidential client; and signing out.
//! confidential client; to several accounts in one browser, switching
//! between them; and signing out.
mod common;
@@ -229,6 +230,16 @@ fn location(res: &reqwest::Response) -> String {
/// Signs in as `who`, going back to `back`: the last answer, and the
/// cookie naming the sign-in.
async fn sign_in(h: &Running, who: &str, back: &str) -> (reqwest::Response, Option<String>) {
sign_in_beside(h, who, back, "").await
}
/// Signs in as `who` in a browser holding the cookies `jar` (`;` between).
async fn sign_in_beside(
h: &Running,
who: &str,
back: &str,
jar: &str,
) -> (reqwest::Response, Option<String>) {
let b = browser();
let url = reqwest::Url::parse_with_params(
&format!("{}/console/login", h.url),
@@ -243,7 +254,7 @@ async fn sign_in(h: &Running, who: &str, back: &str) -> (reqwest::Response, Opti
let approved = b.get(location(&started)).send().await.unwrap();
let back = b
.get(location(&approved))
.header("cookie", login.clone().unwrap())
.header("cookie", format!("{}; {jar}", login.clone().unwrap()))
.send()
.await
.unwrap();
@@ -624,3 +635,132 @@ async fn viewer(h: &Running, cookie: &str) -> (u16, Json_) {
.unwrap();
(res.status().as_u16(), res.json().await.unwrap_or_default())
}
/// The cookies a browser holds, `;` between, once `res` set them over
/// `jar`: a cookie set empty is gone, and the sign-in's own is left out.
fn kept(jar: &str, res: &reqwest::Response) -> String {
let mut all: Vec<(String, String)> = jar
.split(';')
.filter_map(|p| p.trim().split_once('='))
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
for set in res.headers().get_all("set-cookie") {
let pair = set.to_str().unwrap().split(';').next().unwrap();
let (name, value) = pair.split_once('=').unwrap();
all.retain(|(k, _)| k != name);
if !value.is_empty() && name != "group_host_login" {
all.push((name.to_string(), value.to_string()));
}
}
let pairs: Vec<String> = all.iter().map(|(k, v)| format!("{k}={v}")).collect();
pairs.join("; ")
}
async fn switch(h: &Running, jar: &str, did: &str, back: &str) -> reqwest::Response {
browser()
.post(format!("{}/console/switch", h.url))
.header("cookie", jar)
.form(&[("did", did), ("back", back)])
.send()
.await
.unwrap()
}
async fn sign_out(h: &Running, jar: &str) -> reqwest::Response {
browser()
.post(format!("{}/console/logout", h.url))
.header("cookie", jar)
.send()
.await
.unwrap()
}
/// The DIDs of the other accounts the viewer is signed in to.
fn others(viewer: &Json_) -> Vec<String> {
let all = viewer["accounts"].as_array().cloned().unwrap_or_default();
all.iter()
.map(|a| a["did"].as_str().unwrap().to_string())
.collect()
}
#[tokio::test]
async fn switches_between_accounts_signed_in_in_one_browser() {
let h = start_reachable(&[]).await;
let (one, _) = person(&h, true).await;
let (two, _) = person(&h, true).await;
let (three, _) = person(&h, true).await;
// One account: nothing else to switch to.
let (back, _) = sign_in(&h, &one, "/").await;
assert!(set_cookie(&back, "group_host_accounts").is_none());
let first = kept("", &back);
let (_, shown) = viewer(&h, &first).await;
assert_eq!(shown["actor"]["did"], one);
assert_eq!(shown.get("accounts"), None);
// Signing in to another keeps the first beside it, and the same one
// again keeps it once.
let (back, _) = sign_in_beside(&h, &two, "/g/riders", &first).await;
assert_eq!(location(&back), "/g/riders");
let both = kept(&first, &back);
let (_, shown) = viewer(&h, &both).await;
assert_eq!(shown["actor"]["did"], two);
assert_eq!(others(&shown), [one.as_str()]);
assert_eq!(shown["accounts"][0]["handle"], "person.test");
let (back, _) = sign_in_beside(&h, &two, "/", &both).await;
let again = kept(&both, &back);
assert_eq!(others(&viewer(&h, &again).await.1), [one.as_str()]);
// Signing in to one already beside makes it the one in use, once.
let (back, _) = sign_in_beside(&h, &one, "/", &both).await;
let flipped = kept(&both, &back);
let (_, shown) = viewer(&h, &flipped).await;
assert_eq!(shown["actor"]["did"], one);
assert_eq!(others(&shown), [two.as_str()]);
// Switching swaps them, with no sign-in, going back to the page it
// was asked from; only to an account this browser is signed in to.
let res = switch(&h, &both, &one, "/g/riders").await;
assert_eq!(res.status(), 303);
assert_eq!(location(&res), "/g/riders");
let swapped = kept(&both, &res);
let (_, shown) = viewer(&h, &swapped).await;
assert_eq!(shown["actor"]["did"], one);
assert_eq!(others(&shown), [two.as_str()]);
let res = switch(&h, &first, &two, "//elsewhere.test").await;
assert_eq!(res.status(), 400);
let res = switch(&h, "", &two, "/").await;
assert_eq!(res.status(), 400);
// Elsewhere is never where it goes back to.
let res = switch(&h, &swapped, &two, "//elsewhere.test").await;
assert_eq!(location(&res), "/");
// Three: the one used last first.
let (back, _) = sign_in_beside(&h, &three, "/", &swapped).await;
let all = kept(&swapped, &back);
let (_, shown) = viewer(&h, &all).await;
assert_eq!(shown["actor"]["did"], three);
assert_eq!(others(&shown), [one.as_str(), two.as_str()]);
// Signing out of one goes on as the one used before it, and that one
// is never offered again by the cookies signed before.
let res = sign_out(&h, &all).await;
assert_eq!(res.status(), 303);
let left = kept(&all, &res);
let (_, shown) = viewer(&h, &left).await;
assert_eq!(shown["actor"]["did"], one);
assert_eq!(others(&shown), [two.as_str()]);
assert_eq!(others(&viewer(&h, &swapped).await.1), [two.as_str()]);
let res = switch(&h, &all, &three, "/").await;
assert_eq!(res.status(), 400);
// Out of the next, and the last, as no one.
let res = sign_out(&h, &left).await;
let last = kept(&left, &res);
assert!(!last.contains("group_host_accounts="), "{last}");
let (_, shown) = viewer(&h, &last).await;
assert_eq!(shown["actor"]["did"], two);
assert_eq!(shown.get("accounts"), None);
let res = sign_out(&h, &last).await;
let none = kept(&last, &res);
assert_eq!(viewer(&h, &none).await.1.get("actor"), None);
}
docs/reference/api.md+3−2
@@ -101,7 +101,7 @@ same writes ([membership](../design/membership.md#invites)).
| Method | What it does |
| --- | --- |
| `GET fyi.opensocial.getViewer` | who is asking, by the console's cookie or service auth, and where someone with no account makes one (`signUpAt`, `SIGNUP_PDS`) |
| `GET fyi.opensocial.getViewer` | who is asking, by the console's cookie or service auth, the other accounts the browser is signed in to (`accounts`), and where someone with no account makes one (`signUpAt`, `SIGNUP_PDS`) |
| `GET fyi.opensocial.getActor` | a person's DID and handle, to someone signed in: themselves, or anyone the host shows (a member of a group here, or someone asking to join one); to themselves also whether they may start a group |
| `GET fyi.opensocial.getActorGroups` | the groups here a person is in, as far as the caller shares them |
| `GET fyi.opensocial.searchActors` | accounts whose handle matches what is typed, from where `ACTOR_SEARCH` says; anyone may ask |
@@ -235,7 +235,8 @@ Groups between hosts, and accounts here to become groups ([moving](../design/mov
| Route | What it does |
| --- | --- |
| `GET /console/login`, `GET /console/callback`, `POST /console/logout` | signing in to the console as oneself (`?handle=`), or signing up at `SIGNUP_PDS` (`?create`), and out |
| `GET /console/login`, `GET /console/callback`, `POST /console/logout` | signing in to the console as oneself (`?handle=`), or signing up at `SIGNUP_PDS` (`?create`), and out; signing in again keeps the account before beside it, and signing out goes on as the one used last |
| `POST /console/switch` | switching to another account the browser is signed in to (`did`), and back to the page `back` |
| `GET /console/move/login` | signing in to an account to move here |
| `GET /console/client-metadata.json` | the host's metadata as the console's OAuth client |
docs/development.md+1−0
@@ -73,6 +73,7 @@ which states to look at and what the pages are held to.
```sh
just look /g/riders.groups.test --as alice # signed in as alice
just look / --as bob,alice --click '.user-menu summary' # signed in to both, alice in use
just look / --seed full --as bob --phone --dark # a seeded state, on a phone, dark
just look /g/lanterns.groups.test --as alice --click 'button[popovertarget=invite]'
```
harness/look/look.mjs+33−16
@@ -17,7 +17,9 @@
//
// --as <name> signed in as that account (alice, bob, ...),
// at its PDS's own page, as a person signs in;
// signed out without it
// signed out without it. Several, a comma
// between (alice,bob), adds each in turn, the
// last the one in use, the others to switch to
// --seed <name|file> runs a seed first: one of harness/look/seeds
// by name (full, long, waiting, apps), or a file of
// your own. On a kept world each runs once
@@ -88,7 +90,7 @@ const targets = [];
const steps = [];
const seeds = [];
const sides = new Set();
let as = null;
let as = [];
let element;
let up = false;
let out = join(root, 'target/look');
@@ -98,7 +100,10 @@ for (let i = 0; i < argv.length; i++) {
const a = argv[i];
const next = () => argv[++i] ?? fail(`${a} needs a value`);
if (a === '--up') up = true;
else if (a === '--as') as = next().replace(/^@/, '').split('.')[0];
else if (a === '--as')
as = next()
.split(',')
.map((n) => n.trim().replace(/^@/, '').split('.')[0]);
else if (a === '--seed') seeds.push(next());
else if (a === '--click') steps.push({ click: next() });
else if (a === '--type') {
@@ -116,8 +121,8 @@ for (let i = 0; i < argv.length; i++) {
}
if (!up && !targets.length) fail('which page? a path, as / or /g/riders.groups.test/settings');
for (const t of targets) if (!t.startsWith('/')) fail(`${t}: a page is its path, starting with /`);
if (as && !ACCOUNTS.includes(as))
fail(`--as ${as}: no such account; one of ${ACCOUNTS.join(', ')}`);
for (const n of as)
if (!ACCOUNTS.includes(n)) fail(`--as ${n}: no such account; one of ${ACCOUNTS.join(', ')}`);
/// The projects asked for: each of the sizes and schemes given, or
/// desktop light and phone dark.
@@ -197,16 +202,25 @@ const who = Object.fromEntries(world.accounts.map((a) => [a.handle.split('.')[0]
const browser = await chromium.launch({ args: [resolving] });
/// A browser signed in as `name`, at their PDS's own page, as a person
/// does: kept as the world keeps it, so each look after need not.
async function signedIn(name) {
if (world.signedIn[name]) return world.signedIn[name];
const context = await browser.newContext({ ignoreHTTPSErrors: true });
/// A browser signed in as each of `names` in turn, at their PDS's own
/// page, as a person does, adding each after the first from the header's
/// menu: kept as the world keeps it, so each look after need not.
async function signedIn(names) {
const key = names.join(',');
if (world.signedIn[key]) return world.signedIn[key];
const before = names.length > 1 ? await signedIn(names.slice(0, -1)) : undefined;
const name = names.at(-1);
const context = await browser.newContext({ ignoreHTTPSErrors: true, storageState: before });
const page = await context.newPage();
// Once its script has run, as a person's click comes: before, the
// form posts itself, which the page's policy stops going elsewhere.
await page.goto(world.base, { waitUntil: 'networkidle' });
await page.getByRole('banner').getByRole('button', { name: 'Sign in' }).click();
if (before) {
await page.locator('.user-menu summary').click();
await page.getByRole('button', { name: 'Add account' }).click();
} else {
await page.getByRole('banner').getByRole('button', { name: 'Sign in' }).click();
}
const dialog = page.getByRole('dialog', { name: 'Sign in with your Atmosphere account' });
// Sent as typed, under any accounts the field suggests.
const handle = dialog.getByRole('combobox', { name: 'Handle' });
@@ -217,10 +231,10 @@ async function signedIn(name) {
await page.getByRole('button', { name: 'Sign in' }).click();
await page.getByRole('button', { name: /^(accept|authorize|allow)$/i }).click();
await page.locator('.user-menu').waitFor({ timeout: 30_000 });
world.signedIn[name] = await context.storageState();
world.signedIn[key] = await context.storageState();
await context.close();
save();
return world.signedIn[name];
return world.signedIn[key];
}
/// What a seed is given: ways to write to the world as its people do.
@@ -271,7 +285,7 @@ const tools = {
page: async (name) => {
const context = await browser.newContext({
ignoreHTTPSErrors: true,
storageState: await signedIn(name)
storageState: await signedIn([name])
});
return context.newPage();
},
@@ -298,7 +312,7 @@ for (const seed of seeds) {
save();
}
const storageState = as ? await signedIn(as) : undefined;
const storageState = as.length ? await signedIn(as) : undefined;
const named = (t) => name ?? (t.replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '') || 'home');
mkdirSync(out, { recursive: true });
@@ -360,7 +374,10 @@ try {
say(
`${named(target)}-${project}: ${wide.by}px wider than the screen, at ${wide.at.join(', ')}`
);
const file = join(out, `${named(target)}${as ? `-${as}` : ''}-${project}.png`);
const file = join(
out,
`${named(target)}${as.length ? `-${as.join('-')}` : ''}-${project}.png`
);
const opts = { path: file, animations: 'disabled', caret: 'hide' };
if (element) await page.locator(element).first().screenshot(opts);
else await page.screenshot({ ...opts, fullPage: !steps.length });
lexicons/fyi/opensocial/getViewer.json+9−1
@@ -4,7 +4,7 @@
"defs": {
"main": {
"type": "query",
"description": "Who is asking: by the console's session cookie, or their service auth. Nothing, for no one. For the console to show who is signed in.",
"description": "Who is asking: by the console's session cookie, or their service auth. Nothing, for no one. For the console to show who is signed in, and the other accounts it can switch to.",
"parameters": {
"type": "params",
"properties": {}
@@ -19,6 +19,14 @@
"ref": "fyi.opensocial.defs#actorView",
"description": "Who is asking, with the handle their DID document names and canCreateGroup; absent when no one is."
},
"accounts": {
"type": "array",
"items": {
"type": "ref",
"ref": "fyi.opensocial.defs#actorView"
},
"description": "The other accounts this browser is signed in to, by the console's cookies, the one used last first, which it can switch to; absent when there are none."
},
"signUpAt": {
"type": "string",
"format": "uri",
web/src/lib/molecules/UserMenu.svelte+40−7
@@ -1,15 +1,32 @@
<script lang="ts">
import Avatar from '#lib/atoms/Avatar.svelte';
import { SIGN_IN } from '#lib/signIn.ts';
import { page } from '$app/state';
/**
* Who is signed in, as their picture and handle, opening a menu of
* what is theirs: their invites, how many are waiting (`invites`), as a
* dot on their picture too while any are; their groups, starting one,
* moving an account here, and, last, signing out (`/console/logout`,
* the host's). It closes on a click elsewhere, on Escape, and on going
* to another page.
* what is theirs: the other accounts this browser is signed in to
* (`accounts`), each switched to in a click (`/console/switch`, the
* host's, back to this page), and adding another, by the sign-in
* dialog; their invites, how many are waiting (`invites`), as a dot on
* their picture too while any are; their groups, starting one, moving
* an account here, and, last, signing out (`/console/logout`), which
* goes on as the account used before. It closes on a click elsewhere,
* on Escape, and on going to another page.
*/
let { handle, did, invites = 0 }: { handle?: string; did: string; invites?: number } = $props();
let {
handle,
did,
invites = 0,
accounts = []
}: {
handle?: string;
did: string;
invites?: number;
accounts?: { did: string; handle?: string }[];
} = $props();
const name = $derived(handle ? `@${handle}` : did);
const named = (a: { did: string; handle?: string }) => (a.handle ? `@${a.handle}` : a.did);
const here = $derived(`${page.url.pathname}${page.url.search}`);
const waiting = $derived(invites === 1 ? '1 invite waiting' : `${invites} invites waiting`);
let menu: HTMLDetailsElement;
function away(e: Event) {
@@ -33,6 +50,20 @@
>
</summary>
<div class="menu">
{#if accounts.length}<p class="menu-label">Switch account</p>{/if}
{#each accounts as account (account.did)}
<form method="post" action="/console/switch">
<input type="hidden" name="did" value={account.did} />
<input type="hidden" name="back" value={here} />
<button class="account" type="submit" aria-label={`Switch to ${named(account)}`}
><Avatar name={account.handle ?? account.did} size="sm" /><span class="handle mono"
>{named(account)}</span
></button
>
</form>
{/each}
<button type="button" popovertarget={SIGN_IN} onclick={close}>Add account</button>
<hr />
<a href="/#invites" onclick={close}
>Invites{#if invites}<span class="badge">{invites}</span>{/if}</a
>
@@ -41,7 +72,9 @@
<a href="/move" onclick={close}>Move an account here</a>
<hr />
<form method="post" action="/console/logout">
<button class="quiet" type="submit">Sign out</button>
<button class="quiet" type="submit"
>{accounts.length ? 'Sign out of this account' : 'Sign out'}</button
>
</form>
</div>
</details>
web/src/lib/organisms/SiteHeader.svelte+5−3
web/src/routes/+layout.svelte+6−1
web/src/routes/+layout.ts+3−1
web/src/app.css+21−1