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

People sign in to the console as themselves, at their own PDS

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/console-login
crates/atproto/src/jose.rs+9−6
@@ -31,6 +31,14 @@ pub fn b64(bytes: impl AsRef<[u8]>) -> String {
URL_SAFE_NO_PAD.encode(bytes)
}
/// The JSON object `part` holds, base64url: a JWT's header or claims.
pub fn json_of(part: &str) -> Option<Value> {
let bytes = URL_SAFE_NO_PAD.decode(part).ok()?;
serde_json::from_slice::<Value>(&bytes)
.ok()
.filter(Value::is_object)
}
/// SHA-256 of `text`, base64url: a PKCE challenge, a DPoP proof's `ath`.
pub fn sha256(text: &str) -> String {
b64(Sha256::digest(text.as_bytes()))
@@ -120,12 +128,7 @@ pub fn parts(token: &str) -> Result<(Value, Value), JoseError> {
return err("not a compact JWT");
};
let decode = |part: &str, what: &str| {
let bytes = URL_SAFE_NO_PAD.decode(part);
let json = bytes
.ok()
.and_then(|b| serde_json::from_slice::<Value>(&b).ok());
json.filter(Value::is_object)
.ok_or_else(|| JoseError(format!("bad JSON in a JWT {what}")))
json_of(part).ok_or_else(|| JoseError(format!("bad JSON in a JWT {what}")))
};
Ok((decode(header, "header")?, decode(claims, "payload")?))
}
crates/group-host/src/console_login.rsnew+504−0
504 lines changed: not loaded until asked for.
crates/group-host/src/group_api.rs+4−3
@@ -18,15 +18,16 @@ use std::sync::Arc;
type Answer = Result<Json<Value>, XrpcError>;
/// Who calls `lxm`, by their service auth for this host; none without
/// any.
/// Who calls `lxm`: by their service auth for this host, or else the
/// console's session cookie; none without either.
pub(crate) async fn caller(
host: &Host,
headers: &HeaderMap,
lxm: &str,
) -> Result<Option<String>, XrpcError> {
// Signed in to the console, with no other say.
if !headers.contains_key(header::AUTHORIZATION) {
return Ok(None);
return host.console_caller(headers).map_err(XrpcError::internal);
}
let claims = service_caller(host, headers, lxm).await?;
let ours = &host.config.service_did;
crates/group-host/src/lib.rs+8−0
@@ -10,6 +10,7 @@ pub mod authority_api;
pub mod authorization;
pub mod blobs;
pub mod config;
pub mod console_login;
pub mod firehose;
pub mod group;
pub mod group_api;
@@ -350,6 +351,13 @@ pub fn router(host: Arc<Host>) -> Router {
post(group_tokens::revoke_group_token),
)
.route("/oauth/authorize", get(oauth::authorize))
.route(
"/console/client-metadata.json",
get(console_login::client_metadata),
)
.route("/console/login", get(console_login::login))
.route("/console/callback", get(console_login::callback))
.route("/console/logout", post(console_login::logout))
.merge(token_routes())
.merge(oauth_routes())
.route("/.well-known/did.json", get(api::did_json))
crates/group-host/src/oauth_clients.rs+21−12
@@ -254,26 +254,24 @@ impl Host {
})
}
/// The JSON at `url`, an https URL at a public address (or http at any
/// address, while this host is on http itself, as a network of test
/// servers is). The connection goes to the address checked, so a name
/// that resolves elsewhere a moment later is not followed there.
async fn fetch_json(&self, url: &str, what: &str) -> Result<Value, OAuthError> {
let at = Url::parse(url).map_err(|_| invalid_metadata(format!("{url} is not a URL")))?;
/// A client for requests to `url`, an https URL at a public address
/// (or http at any address, while this host is on http itself, as a
/// network of test servers is), and the URL. Its connections go to the
/// addresses checked, so a name that resolves elsewhere a moment later
/// is not followed there, and it follows no redirect.
pub(crate) async fn pinned(&self, url: &str) -> Result<(reqwest::Client, Url), String> {
let at = Url::parse(url).map_err(|_| format!("{url} is not a URL"))?;
let http_here = self.config.public_url.starts_with("http://");
let scheme_ok = at.scheme() == "https" || (http_here && at.scheme() == "http");
if !scheme_ok || at.fragment().is_some() || !at.username().is_empty() {
return Err(invalid_metadata(format!("{url} is not an https URL")));
return Err(format!("{url} is not an https URL"));
}
let unreadable = |why: String| invalid_metadata(format!("{what} at {url}: {why}"));
let host = at.host_str().unwrap_or_default().to_string();
let port = at.port_or_known_default().unwrap_or_default();
let found = tokio::net::lookup_host(format!("{host}:{port}")).await;
let addrs: Vec<SocketAddr> = found.map_err(|e| unreadable(e.to_string()))?.collect();
let addrs: Vec<SocketAddr> = found.map_err(|e| format!("{url}: {e}"))?.collect();
if !http_here && !addrs.iter().all(|a| public(a.ip())) {
return Err(invalid_metadata(format!(
"{url} is not at a public address"
)));
return Err(format!("{url} is not at a public address"));
}
let pinned = reqwest::Client::builder()
.timeout(Duration::from_secs(10))
@@ -281,6 +279,13 @@ impl Host {
.resolve_to_addrs(host.trim_matches(['[', ']']), &addrs)
.build()
.expect("a client builds");
Ok((pinned, at))
}
/// The JSON object at `url`, fetched by a [`Host::pinned`] client.
pub(crate) async fn public_json(&self, url: &str, what: &str) -> Result<Value, String> {
let unreadable = |why: String| format!("{what} at {url}: {why}");
let (pinned, at) = self.pinned(url).await.map_err(unreadable)?;
let sent = pinned.get(at).header("accept", "application/json");
let res = sent.send().await.map_err(|e| unreadable(e.to_string()))?;
if !res.status().is_success() {
@@ -294,6 +299,10 @@ impl Host {
json.ok_or_else(|| unreadable("not a JSON object".into()))
}
async fn fetch_json(&self, url: &str, what: &str) -> Result<Value, OAuthError> {
self.public_json(url, what).await.map_err(invalid_metadata)
}
/// How `client` authenticates on a request whose form is `form`: as
/// itself alone, if public; with an assertion signed by one of its
/// keys, for this host, if confidential.
crates/group-host/src/store.rs+17−0
@@ -277,6 +277,23 @@ pub const MIGRATIONS: &[&str] = &[
created_at INTEGER NOT NULL,
PRIMARY KEY (grp, name)
);
",
"
CREATE TABLE console_login (
state TEXT PRIMARY KEY,
did TEXT NOT NULL,
issuer TEXT NOT NULL,
token_endpoint TEXT NOT NULL,
revocation_endpoint TEXT,
key BLOB NOT NULL,
verifier TEXT NOT NULL,
back TEXT NOT NULL,
started INTEGER NOT NULL
);
CREATE TABLE console_logout (
did TEXT PRIMARY KEY,
at INTEGER NOT NULL
);
",
];
crates/group-host/tests/console_login.rsnew+497−0
497 lines changed: not loaded until asked for.
docs/design/README.md+2−2
@@ -105,8 +105,8 @@ says otherwise.
provisioning (`provision.rs`; done): `auth.ts`, `pds/auth.ts`, `pds/oauth/*`,
`methods/{authorization,groupAuth,appPasswords,connectedApps,provision}.ts`.
The console signs its people in at their own PDS here, as a
confidential client, and keeps the session on the server, as knotless
does.
confidential client, as knotless does, keeping only a signed cookie
(`console_login.rs`; done).
7. **The console.** Home, starting a group, a group's page (members,
roles, invites, requests, apps), approving an app, a person's
sessions and app passwords: the console's pages in `apps/web/src/pages`.
docs/design/signing-in.md+26−1
@@ -6,6 +6,29 @@ says yes. A group has no password, so whoever signs an app in as a group
is one of its members, acting with their roles, and the app gets what
those roles allow and nothing more.
## Signing in to the console
People sign in to the console as themselves, at their own PDS
(`console_login.rs`). The host is a confidential OAuth client of it, as
knotless-serve is of its accounts', its client id
`<CONSOLE_URL>/console/client-metadata.json`, its key derived from the
host's secret. It asks for `atproto` alone: the console's methods act as
the group, never as the person, so the host needs only to know who they
are. `/console/login` resolves their handle or DID to their PDS and its
authorization server, pushes the request (PKCE, DPoP, a client assertion,
their handle as the hint) and sends the browser there to approve;
`/console/callback` checks that the browser coming back is the one that
started, and the answer is from that server, exchanges the code, checks
the token is for the person who started, revokes it at once, and signs
them in. The host keeps nothing of theirs.
The browser holds a cookie the host signed, naming the person, HttpOnly
and SameSite=Lax, good for thirty days; with it, the host's methods know
who calls as service auth would say. `/console/logout` signs out, and
refuses every cookie signed before. Every server a handle leads to is
reached only at a public address, as a client's metadata is. The console
forwards `/console/*` to the host, cookies and all.
## The server
The host is a standard atproto authorization server (`oauth.rs`):
@@ -184,7 +207,9 @@ at the token endpoint, its client id (and its assertion, if confidential)
in the body and a DPoP proof in the header. It must be one the host makes
groups for (`PROVISIONING_CLIENTS`), and its scope must hold `atproto`
and nothing its metadata does not declare. All of that is checked before
the group is made. The session is issued as a code exchange issues one,
the group is made. What follows it (narrowing the scope, issuing the
grant) fails only on an internal error, which leaves the group made, and
its founder's to run, with no session for the app: it asks again. The session is issued as a code exchange issues one,
narrowed to the founder's roles as an approval is, and recorded as the
founder's: from then on an ordinary grant, refreshed at `/oauth/token`,
listed among the group's, revoked there.
web/src/lib/molecules/SignIn.sveltenew+16−0
@@ -0,0 +1,16 @@
<script lang="ts">
/**
* Signing in, as oneself, at one's own PDS: a handle, sent to the group
* host's `/console/login`, which goes there and back to `back`.
*/
let { back = '/' }: { back?: string } = $props();
</script>
<form class="sign-in" method="get" action="/console/login">
<input type="hidden" name="back" value={back} />
<label>
Your handle
<input name="handle" required autocomplete="username" placeholder="you.bsky.social" />
</label>
<button type="submit">Sign in</button>
</form>
web/src/lib/organisms/SiteHeader.svelte+9−1
@@ -1,3 +1,11 @@
<script lang="ts">
import SignIn from '#lib/molecules/SignIn.svelte';
import { page } from '$app/state';
</script>
<header class="top">
<div class="wrap"><a class="brand" href="/">opensocial</a></div>
<div class="wrap">
<a class="brand" href="/">opensocial</a>
<SignIn back={page.url.pathname} />
</div>
</header>
web/src/hooks.server.ts+19−1
@@ -1,6 +1,24 @@
import type { HandleFetch } from '@sveltejs/kit/hooks';
import type { Handle, HandleFetch } from '@sveltejs/kit/hooks';
import { GROUP_HOST } from '$app/env/private';
/**
* Signing in and out is the group host's (`/console/*`): asked of this
* site, it is asked of the host, cookies and all, and its answer, its
* redirects and the cookies it sets among it, is the browser's.
*/
export const handle: Handle = async ({ event, resolve }) => {
if (!event.url.pathname.startsWith('/console/')) return resolve(event);
const asked = new Request(`${GROUP_HOST}${event.url.pathname}${event.url.search}`, {
method: event.request.method,
headers: event.request.headers,
body: event.request.method === 'GET' || event.request.method === 'HEAD' ? undefined : await event.request.arrayBuffer(),
redirect: 'manual'
});
asked.headers.set('x-forwarded-host', event.url.host);
asked.headers.set('x-forwarded-proto', event.url.protocol.slice(0, -1));
return globalThis.fetch(asked);
};
/**
* Asked of this site, XRPC methods are asked of the group host directly,
* and with the global fetch: the host can share the console's origin, as