chadtmiller.com/monolith
An atproto PDS
0
0
Accounts sign in with passkeys, added through a link
.changeset/passkeys.mdnew+7−0
| @@ -0,0 +1,7 @@ | ||
--- | ||
default: minor | ||
--- | ||
| ||
# Accounts sign in with passkeys | ||
| ||
An account can sign in on the OAuth sign-in page with a passkey instead of its password, and with no email code. `pds passkey add --name <name>` (or the `passkey_add` MCP tool), with the account's password session, answers a link, good for 15 minutes, to open in a browser on the device that is to keep the passkey; `pds passkey list` and `pds passkey remove --id <id>` list and remove them. The sign-in page offers the device's passkeys in the "Handle or email" field's autofill, and with a `Sign in with a passkey` button. Passkeys are bound to the host of `PDS_PUBLIC_URL`: a browser makes none for an IP address, and once the URL names another host those made before are no longer offered. A password reset removes the account's passkeys. | ||
.claude/skills/ui/SKILL.md+3−0
| @@ -39,6 +39,9 @@ just look consent --details # Technical details open | ||
just look ended # consent answered 400: "This sign-in has ended…" | ||
just look busy # the sign-in held on its way: the button busy, the rest disabled | ||
just look error # the error page | ||
just look add-passkey # the page a passkey link opens (server on localhost, Chromium's virtual authenticator) | ||
just look passkey-added # after Add passkey: the passkey made and taken | ||
just look no-passkey # Sign in with a passkey, the browser giving none: its alert | ||
just look consent --phone --light # one size and scheme alone | ||
just look email resetPassword # an email's HTML part, as the server sent it over SMTP | ||
``` | ||
compat/README.md+1−0
| @@ -55,6 +55,7 @@ in its gates. | ||
| `oauthSilentSignIn` (a remembered device sent back at once) | oauth-clients | Monolith's own: the reference's page API | | | ||
| `oauthDepartures`, `oauthClientDepartures` (spec/OAUTH.md's and spec/OAUTH-CLIENTS.md's departures, held to the spec) | oauth, oauth-clients | Monolith's own | | | ||
| `oauthAccountAuth`, `oauthAccountSessions`, `oauthAccountDevices`, and with `--commands` `oauthAccountCommands` (spec/OAUTH-ACCOUNT.md's routes, which the reference does not serve) | oauth-account | Monolith's own | | | ||
| `passkeyAuth`, `passkeyAdding`, `passkeySigningIn`, `passkeySignInRefused`, `passkeyRemoving`, `passkeyStates`, and with `--commands` `passkeyCommands` (spec/PASSKEYS.md's passkeys, which the reference does not have) | passkeys | Monolith's own | | | ||
| `createSession`, `getSession`, `describeServer`, `refreshSession`, `deleteSession`, `wrongTokens`, `appPasswords`, `sessionRace` | accounts, session, sessions | core | sessions | | ||
| `createAccount`, `createAccountRefused`, `accountRace` | accounts | core | accounts | | ||
| `createRecord`, `putRecord`, `deleteRecord`, `applyWrites`, `getRecord`, `listRecords`, `describeRepo`, `createWithTid`, `concurrent`, `oddRequests`, `crossWrites` | records, odd, accounts | core | records | | ||
crates/pds-cli/src/lib.rs+72−28
| @@ -2,8 +2,9 @@ | ||
//! [flags]`, calling the server at `PDS_URL` over XRPC (`spec/COMMANDS.md`); | ||
//! the routes no lexicon makes a command of (`OWN`): the admin's reads, | ||
//! `pds admin logs` and `pds admin stats`, calling `/xrpc/_logs` and | ||
//! `/xrpc/_stats`, and the account's OAuth routes, the group `oauth`; and | ||
//! `pds xrpc`, any call by its name (`xrpc`). | ||
//! `/xrpc/_stats`, the account's OAuth routes, the group `oauth`, and its | ||
//! passkey routes, the group `passkey`; and `pds xrpc`, any call by its | ||
//! name (`xrpc`). | ||
//! | ||
//! Exit statuses: 0 for the method's answer, 1 for an error it answers, 2 for | ||
//! a usage error (no call made), 3 for a server that cannot be reached. | ||
| @@ -101,20 +102,24 @@ fn command(args: &[String]) -> Result<u8, Stop> { | ||
/// `com.atproto.admin`'s methods. | ||
const ADMIN: &str = "admin"; | ||
| ||
/// The group of the account's OAuth routes, after every other group. | ||
/// The group of the account's OAuth routes, after every other lexicon's. | ||
const OAUTH: &str = "oauth"; | ||
| ||
/// Every group, in the order listed: the lexicons', then `oauth`. | ||
/// The group of the account's passkey routes, after `oauth`. | ||
const PASSKEY: &str = "passkey"; | ||
| ||
/// Every group, in the order listed: the lexicons', then `oauth`, then `passkey`. | ||
fn groups() -> Vec<&'static str> { | ||
let mut groups = pds_lexicon::groups(); | ||
groups.push(OAUTH); | ||
groups.push(PASSKEY); | ||
groups | ||
} | ||
| ||
/// A command of no lexicon's (`spec/COMMANDS.md`, "The admin's reads" and | ||
/// "The account's OAuth sessions"): its group and name, its route, whether | ||
/// it is a `POST` of its flags as JSON rather than a `GET` with them as the | ||
/// query, its description and its flags. | ||
/// A command of no lexicon's (`spec/COMMANDS.md`, "The admin's reads", | ||
/// "The account's OAuth sessions" and "The account's passkeys"): its group | ||
/// and name, its route, whether it is a `POST` of its flags as JSON rather | ||
/// than a `GET` with them as the query, its description and its flags. | ||
struct Own { | ||
group: &'static str, | ||
command: &'static str, | ||
| @@ -124,7 +129,7 @@ struct Own { | ||
args: Vec<Arg>, | ||
} | ||
| ||
static OWN: LazyLock<[Own; 6]> = LazyLock::new(|| { | ||
static OWN: LazyLock<[Own; 9]> = LazyLock::new(|| { | ||
let arg = |name: &str, ty: Type, required: bool, description: &str, schema: Json| Arg { | ||
name: name.into(), | ||
ty, | ||
| @@ -142,14 +147,15 @@ static OWN: LazyLock<[Own; 6]> = LazyLock::new(|| { | ||
description, | ||
args: vec![], | ||
}; | ||
let revoke = |command, route, description, id: &str| Own { | ||
group: OAUTH, | ||
let post = |group, command, route, description, flag: Arg| Own { | ||
group, | ||
command, | ||
route, | ||
post: true, | ||
description, | ||
args: vec![arg("id", Type::String, true, id, string())], | ||
args: vec![flag], | ||
}; | ||
let id = |description: &str| arg("id", Type::String, true, description, string()); | ||
[ | ||
Own { | ||
args: vec![ | ||
| @@ -209,11 +215,12 @@ static OWN: LazyLock<[Own; 6]> = LazyLock::new(|| { | ||
"_oauthSessions", | ||
"The OAuth sessions of your account, the apps you signed in to, newest first: each with its id, client, issuer (atproto or mcp), scope, and when it started, was last refreshed and ends. Needs your account's password session.", | ||
), | ||
revoke( | ||
post( | ||
OAUTH, | ||
"revoke-session", | ||
"_oauthRevokeSession", | ||
"End one of your account's OAuth sessions by its id, as oauth_sessions lists it: the app is signed out at once. Needs your account's password session.", | ||
"The session's id, as `pds oauth sessions` lists it.", | ||
id("The session's id, as `pds oauth sessions` lists it."), | ||
), | ||
get( | ||
OAUTH, | ||
| @@ -221,11 +228,38 @@ static OWN: LazyLock<[Own; 6]> = LazyLock::new(|| { | ||
"_oauthDevices", | ||
"The browsers your account is signed in on through the OAuth sign-in page, newest sign-in first: each with its id, when it signed in, and its user agent and IP address. Needs your account's password session.", | ||
), | ||
revoke( | ||
post( | ||
OAUTH, | ||
"revoke-device", | ||
"_oauthRevokeDevice", | ||
"Sign your account out of one browser by its id, as oauth_devices lists it. Its apps' sessions stay: end those with oauth_revoke_session. Needs your account's password session.", | ||
"The browser's id, as `pds oauth devices` lists it.", | ||
id("The browser's id, as `pds oauth devices` lists it."), | ||
), | ||
get( | ||
PASSKEY, | ||
"list", | ||
"_passkeyList", | ||
"The passkeys of your account, newest first: each with its id, name, when it was added and last signed in, and whether it is backed up. Needs your account's password session.", | ||
), | ||
post( | ||
PASSKEY, | ||
"add", | ||
"_passkeyAdd", | ||
"A link to open in a browser within 15 minutes, which adds a passkey of this name to your account: it then signs in on the OAuth sign-in page with no password. A new link ends the last. Needs your account's password session.", | ||
arg( | ||
"name", | ||
Type::String, | ||
true, | ||
"The passkey's name, 1 to 64 characters, as `pds passkey list` will list it.", | ||
json!({ "type": "string", "minLength": 1, "maxLength": 64 }), | ||
), | ||
), | ||
post( | ||
PASSKEY, | ||
"remove", | ||
"_passkeyRemove", | ||
"Remove one of your account's passkeys by its id, as passkey_list lists it: it no longer signs in. Needs your account's password session.", | ||
id("The passkey's id, as `pds passkey list` lists it."), | ||
), | ||
] | ||
}); | ||
| @@ -928,30 +962,40 @@ mod tests { | ||
} | ||
| ||
/// The account's OAuth routes are the group `oauth`, listed after every | ||
/// other, its commands in the spec's order; a revocation needs `--id`, | ||
/// a list takes no flag. | ||
/// lexicon's group, and its passkey routes the group `passkey`, after | ||
/// it, their commands in the spec's order; a change needs its flag, a | ||
/// list takes none. | ||
#[test] | ||
fn oauth_commands() { | ||
assert_eq!(groups().last(), Some(&OAUTH)); | ||
fn oauth_and_passkey_commands() { | ||
assert_eq!(groups()[groups().len() - 2..], [OAUTH, PASSKEY]); | ||
assert!(!pds_lexicon::groups().contains(&OAUTH)); | ||
let names: Vec<String> = listed(OAUTH).into_iter().map(|(n, _)| n).collect(); | ||
assert!(!pds_lexicon::groups().contains(&PASSKEY)); | ||
let names = |g| -> Vec<String> { listed(g).into_iter().map(|(n, _)| n).collect() }; | ||
assert_eq!( | ||
names, | ||
names(OAUTH), | ||
["sessions", "revoke-session", "devices", "revoke-device"] | ||
); | ||
assert!(top_help().trim_end().ends_with(OWN[5].description)); | ||
for r in OWN.iter().filter(|r| r.group == OAUTH) { | ||
assert_eq!(names(PASSKEY), ["list", "add", "remove"]); | ||
assert!(top_help().trim_end().ends_with(OWN[8].description)); | ||
for r in OWN | ||
.iter() | ||
.filter(|r| r.group == OAUTH || r.group == PASSKEY) | ||
{ | ||
let flags: Vec<&Arg> = r.args.iter().collect(); | ||
let parse = |argv: &[&str]| { | ||
let argv: Vec<String> = argv.iter().map(|a| a.to_string()).collect(); | ||
parse_flags(OAUTH, r.command, &flags, &argv) | ||
parse_flags(r.group, r.command, &flags, &argv) | ||
}; | ||
if r.post { | ||
assert!(help_of(r).contains("--id")); | ||
let flag = if r.command == "add" { "name" } else { "id" }; | ||
assert!(help_of(r).contains(&format!("--{flag}"))); | ||
assert!(matches!(parse(&[]), Err(Stop::Usage(_)))); | ||
assert_eq!( | ||
parse(&["--id", "x"]).ok().flatten().map(Json::Object), | ||
Some(json!({ "id": "x" })) | ||
parse(&[&format!("--{flag}"), "x"]) | ||
.ok() | ||
.flatten() | ||
.map(Json::Object), | ||
Some(json!({ flag: "x" })) | ||
); | ||
} else { | ||
assert!(help_of(r).contains("It takes no flags.")); | ||
crates/pds-server/src/oauth/passkeys/cbor.rsnew+297−0
| @@ -0,0 +1,297 @@ | ||
//! A reader of CBOR (`spec/webauthn/rfc8949.txt`), as far as WebAuthn's | ||
//! attestation objects, COSE keys and extensions need: one well-formed, | ||
//! valid item at a time (§5.3), with its length, so that a caller may say | ||
//! what may follow it. Text is UTF-8, a map has no key twice, and an item | ||
//! nests at most `DEPTH` deep; anything else is refused. Integers' and | ||
//! lengths' arguments need not be in their shortest form, and lengths may | ||
//! be indefinite, as RFC 8949 allows both. | ||
| ||
/// A CBOR data item. | ||
#[derive(Clone, Debug, PartialEq, Eq)] | ||
pub(crate) enum Value { | ||
/// An unsigned integer (major type 0). | ||
Uint(u64), | ||
/// A negative integer, -1 - n (major type 1), by its n. | ||
Neg(u64), | ||
Bytes(Vec<u8>), | ||
Text(String), | ||
Array(Vec<Value>), | ||
/// A map's pairs, in the order given. | ||
Map(Vec<(Value, Value)>), | ||
Tag(u64, Box<Value>), | ||
/// A simple value: `false` 20, `true` 21, `null` 22, `undefined` 23. | ||
Simple(u8), | ||
/// A float, by the bits of its encoding, with their width. | ||
Float(u64, u8), | ||
} | ||
| ||
/// How deep an item nests, at most. | ||
const DEPTH: usize = 16; | ||
| ||
/// Why bytes are refused: they are no item, or one not valid. | ||
#[derive(Debug, PartialEq, Eq)] | ||
pub(crate) struct Malformed; | ||
| ||
/// The item at the start of `bytes`, and how many bytes it takes. | ||
pub(crate) fn item(bytes: &[u8]) -> Result<(Value, usize), Malformed> { | ||
let mut r = Reader { bytes, at: 0 }; | ||
let v = r.value(0)?; | ||
Ok((v, r.at)) | ||
} | ||
| ||
/// `bytes`, if they are one item and nothing after it. | ||
pub(crate) fn one(bytes: &[u8]) -> Result<Value, Malformed> { | ||
match item(bytes)? { | ||
(v, n) if n == bytes.len() => Ok(v), | ||
_ => Err(Malformed), | ||
} | ||
} | ||
| ||
struct Reader<'b> { | ||
bytes: &'b [u8], | ||
at: usize, | ||
} | ||
| ||
/// An item's head: its major type, and its argument, or none for an | ||
/// indefinite length (additional information 31). | ||
struct Head { | ||
major: u8, | ||
info: u8, | ||
arg: Option<u64>, | ||
} | ||
| ||
impl Reader<'_> { | ||
fn take(&mut self, n: usize) -> Result<&[u8], Malformed> { | ||
let end = self.at.checked_add(n).ok_or(Malformed)?; | ||
let b = self.bytes.get(self.at..end).ok_or(Malformed)?; | ||
self.at = end; | ||
Ok(b) | ||
} | ||
| ||
fn head(&mut self) -> Result<Head, Malformed> { | ||
let first = self.take(1)?[0]; | ||
let (major, info) = (first >> 5, first & 0x1f); | ||
let wide = |b: &[u8]| b.iter().fold(0u64, |n, &x| (n << 8) | u64::from(x)); | ||
let arg = match info { | ||
0..=23 => Some(u64::from(info)), | ||
24 => Some(wide(self.take(1)?)), | ||
25 => Some(wide(self.take(2)?)), | ||
26 => Some(wide(self.take(4)?)), | ||
27 => Some(wide(self.take(8)?)), | ||
28..=30 => return Err(Malformed), | ||
_ => None, | ||
}; | ||
Ok(Head { major, info, arg }) | ||
} | ||
| ||
/// A length, as an index: one longer than what is left is refused. | ||
fn len(&self, n: u64) -> Result<usize, Malformed> { | ||
usize::try_from(n) | ||
.ok() | ||
.filter(|n| *n <= self.bytes.len() - self.at) | ||
.ok_or(Malformed) | ||
} | ||
| ||
/// Whether the next byte is the "break" stop code, taken if it is. | ||
fn stop(&mut self) -> Result<bool, Malformed> { | ||
match self.bytes.get(self.at) { | ||
Some(0xff) => { | ||
self.at += 1; | ||
Ok(true) | ||
} | ||
Some(_) => Ok(false), | ||
None => Err(Malformed), | ||
} | ||
} | ||
| ||
/// A byte or text string's bytes: definite, or indefinite, of definite | ||
/// chunks of the same major type. | ||
fn string(&mut self, major: u8, arg: Option<u64>) -> Result<Vec<u8>, Malformed> { | ||
if let Some(n) = arg { | ||
let n = self.len(n)?; | ||
return Ok(self.take(n)?.to_vec()); | ||
} | ||
let mut out = Vec::new(); | ||
while !self.stop()? { | ||
let h = self.head()?; | ||
let (true, Some(n)) = (h.major == major, h.arg) else { | ||
return Err(Malformed); | ||
}; | ||
let n = self.len(n)?; | ||
let chunk = self.take(n)?; | ||
// Each chunk of a text string is text on its own (§3.2.3). | ||
if major == 3 && std::str::from_utf8(chunk).is_err() { | ||
return Err(Malformed); | ||
} | ||
out.extend_from_slice(chunk); | ||
} | ||
Ok(out) | ||
} | ||
| ||
fn value(&mut self, depth: usize) -> Result<Value, Malformed> { | ||
if depth > DEPTH { | ||
return Err(Malformed); | ||
} | ||
let h = self.head()?; | ||
Ok(match (h.major, h.arg) { | ||
(0, Some(n)) => Value::Uint(n), | ||
(1, Some(n)) => Value::Neg(n), | ||
(2, arg) => Value::Bytes(self.string(2, arg)?), | ||
(3, arg) => { | ||
Value::Text(String::from_utf8(self.string(3, arg)?).map_err(|_| Malformed)?) | ||
} | ||
(4, arg) => { | ||
let mut items = Vec::new(); | ||
match arg { | ||
Some(n) => { | ||
for _ in 0..n { | ||
items.push(self.value(depth + 1)?); | ||
} | ||
} | ||
None => { | ||
while !self.stop()? { | ||
items.push(self.value(depth + 1)?); | ||
} | ||
} | ||
} | ||
Value::Array(items) | ||
} | ||
(5, arg) => { | ||
let mut pairs: Vec<(Value, Value)> = Vec::new(); | ||
loop { | ||
let more = match arg { | ||
Some(n) => (pairs.len() as u64) < n, | ||
None => !self.stop()?, | ||
}; | ||
if !more { | ||
break; | ||
} | ||
let k = self.value(depth + 1)?; | ||
let v = self.value(depth + 1)?; | ||
if pairs.iter().any(|(seen, _)| *seen == k) { | ||
return Err(Malformed); | ||
} | ||
pairs.push((k, v)); | ||
} | ||
Value::Map(pairs) | ||
} | ||
(6, Some(tag)) => Value::Tag(tag, Box::new(self.value(depth + 1)?)), | ||
(7, Some(n)) => match h.info { | ||
0..=23 => Value::Simple(h.info), | ||
// A one-byte simple value below 32 is not well-formed (§3.3). | ||
24 if n >= 32 => Value::Simple(n as u8), | ||
25 => Value::Float(n, 2), | ||
26 => Value::Float(n, 4), | ||
27 => Value::Float(n, 8), | ||
_ => return Err(Malformed), | ||
}, | ||
// An indefinite length where none may be, or "break" where an item is. | ||
_ => return Err(Malformed), | ||
}) | ||
} | ||
} | ||
| ||
impl Value { | ||
/// The value of a map's key `k`, if it is a map with that key. | ||
pub fn get(&self, k: &Value) -> Option<&Value> { | ||
match self { | ||
Value::Map(pairs) => pairs.iter().find(|(key, _)| key == k).map(|(_, v)| v), | ||
_ => None, | ||
} | ||
} | ||
| ||
/// Whether it is a map whose keys are exactly `keys`, in any order. | ||
pub fn keyed_exactly(&self, keys: &[Value]) -> bool { | ||
match self { | ||
Value::Map(pairs) => { | ||
pairs.len() == keys.len() && keys.iter().all(|k| pairs.iter().any(|(p, _)| p == k)) | ||
} | ||
_ => false, | ||
} | ||
} | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| ||
fn hex(s: &str) -> Vec<u8> { | ||
::hex::decode(s).unwrap() | ||
} | ||
| ||
/// RFC 8949's examples (Appendix A), and what is not well-formed (Appendix F). | ||
#[test] | ||
fn items() { | ||
assert_eq!(one(&hex("00")), Ok(Value::Uint(0))); | ||
assert_eq!(one(&hex("1903e8")), Ok(Value::Uint(1000))); | ||
assert_eq!(one(&hex("1bffffffffffffffff")), Ok(Value::Uint(u64::MAX))); | ||
assert_eq!(one(&hex("20")), Ok(Value::Neg(0))); | ||
assert_eq!(one(&hex("3863")), Ok(Value::Neg(99))); | ||
assert_eq!(one(&hex("4401020304")), Ok(Value::Bytes(vec![1, 2, 3, 4]))); | ||
assert_eq!(one(&hex("62c3bc")), Ok(Value::Text("ü".into()))); | ||
assert_eq!( | ||
one(&hex("a201020304")), | ||
Ok(Value::Map(vec![ | ||
(Value::Uint(1), Value::Uint(2)), | ||
(Value::Uint(3), Value::Uint(4)) | ||
])) | ||
); | ||
assert_eq!( | ||
one(&hex("5f42010243030405ff")), | ||
Ok(Value::Bytes(vec![1, 2, 3, 4, 5])) | ||
); | ||
assert_eq!( | ||
one(&hex("7f657374726561646d696e67ff")), | ||
Ok(Value::Text("streaming".into())) | ||
); | ||
assert_eq!( | ||
one(&hex("bf61610161629f0203ffff")), | ||
Ok(Value::Map(vec![ | ||
(Value::Text("a".into()), Value::Uint(1)), | ||
( | ||
Value::Text("b".into()), | ||
Value::Array(vec![Value::Uint(2), Value::Uint(3)]) | ||
), | ||
])) | ||
); | ||
assert_eq!(one(&hex("f4")), Ok(Value::Simple(20))); | ||
assert_eq!(one(&hex("f8ff")), Ok(Value::Simple(255))); | ||
assert_eq!(one(&hex("f93c00")), Ok(Value::Float(0x3c00, 2))); | ||
assert_eq!( | ||
one(&hex("c11a514b67b0")), | ||
Ok(Value::Tag(1, Box::new(Value::Uint(1363896240)))) | ||
); | ||
// An item, and what follows it. | ||
assert_eq!(item(&hex("0001")), Ok((Value::Uint(0), 1))); | ||
for bad in [ | ||
"", | ||
"18", | ||
"1c", | ||
"1f", | ||
"3f", | ||
"5f01ff", | ||
"5f4201ff", | ||
"7f4101ff", | ||
"8201", | ||
"9f01", | ||
"a10102 03", | ||
"a2010201 03", | ||
"a20102 0103", | ||
"ff", | ||
"f801", | ||
"fc", | ||
"62c328", | ||
"5b00000000ffffffff", | ||
"0001", | ||
] { | ||
assert_eq!(one(&hex(&bad.replace(' ', ""))), Err(Malformed), "{bad}"); | ||
} | ||
// A map with a key twice. | ||
assert_eq!(one(&hex("a201020103")), Err(Malformed)); | ||
// Nested past its depth. | ||
let deep = format!("{}00", "81".repeat(DEPTH + 1)); | ||
assert_eq!(one(&hex(&deep)), Err(Malformed)); | ||
let fine = format!("{}00", "81".repeat(DEPTH)); | ||
assert!(one(&hex(&fine)).is_ok()); | ||
} | ||
} | ||
crates/pds-server/src/oauth/passkeys/tests.rsnew+713−0
713 lines changed: not loaded until asked for.
crates/pds-server/src/oauth/passkeys/webauthn.rsnew+923−0
923 lines changed: not loaded until asked for.
crates/pds-server/src/oauth/account.rs+108−41
| @@ -1,10 +1,14 @@ | ||
//! The account's own OAuth sessions and devices (`spec/OAUTH-ACCOUNT.md`): | ||
//! The account's own routes (`spec/OAUTH-ACCOUNT.md`, `spec/PASSKEYS.md`): | ||
//! `GET /xrpc/_oauthSessions`, `POST /xrpc/_oauthRevokeSession`, `GET | ||
//! /xrpc/_oauthDevices` and `POST /xrpc/_oauthRevokeDevice`, of no lexicon. | ||
//! Each is answered by `answer`, over XRPC (`xrpc`) and as its MCP tool | ||
//! (`spec/COMMANDS.md`, "The account's OAuth sessions"): the token | ||
//! `getAccountInviteCodes` takes first, then the HTTP method, then a | ||
//! revocation's body, then a point of `global`. | ||
//! /xrpc/_oauthDevices` and `POST /xrpc/_oauthRevokeDevice` for its OAuth | ||
//! sessions and devices, and `GET /xrpc/_passkeyList`, `POST | ||
//! /xrpc/_passkeyAdd` and `POST /xrpc/_passkeyRemove` for its passkeys | ||
//! (`super::passkeys`), of no lexicon. Each is answered by `answer`, over | ||
//! XRPC (`xrpc`) and as its MCP tool (`spec/COMMANDS.md`, "The account's | ||
//! OAuth sessions" and "The account's passkeys"): the token | ||
//! `getAccountInviteCodes` takes first, then the HTTP method, then | ||
//! `_passkeyAdd`'s account's state, then a `POST`'s body, then a point of | ||
//! `global`. | ||
//! | ||
//! A session and a device are named by a public id: the first 16 bytes of a | ||
//! MAC, under OAuth's secret, of the session's or the device's own id, with | ||
| @@ -12,7 +16,7 @@ | ||
//! never starts with `-`. It stays the same for as long as they last, as the | ||
//! secret does, and is none of the tokens and cookies the server seals, nor | ||
//! the device's id or a session's code, so it is taken as none of them; nor | ||
//! can either be found from it. | ||
//! can either be found from it. A passkey is named by its credential ID. | ||
| ||
use super::{LOGIN_LIFE, State, Tx}; | ||
use crate::sessions::Bearer; | ||
| @@ -28,22 +32,28 @@ use std::sync::OnceLock; | ||
pub(super) const SESSION_ID: &str = "session id"; | ||
pub(super) const DEVICE_ID: &str = "device id"; | ||
| ||
/// One of the account's OAuth routes. | ||
/// One of the account's own routes. | ||
#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
pub(crate) enum Route { | ||
Sessions, | ||
RevokeSession, | ||
Devices, | ||
RevokeDevice, | ||
PasskeyList, | ||
PasskeyAdd, | ||
PasskeyRemove, | ||
} | ||
| ||
impl Route { | ||
/// Each, in the order `spec/COMMANDS.md` lists them. | ||
pub const ALL: [Route; 4] = [ | ||
pub const ALL: [Route; 7] = [ | ||
Route::Sessions, | ||
Route::RevokeSession, | ||
Route::Devices, | ||
Route::RevokeDevice, | ||
Route::PasskeyList, | ||
Route::PasskeyAdd, | ||
Route::PasskeyRemove, | ||
]; | ||
| ||
/// Its route, as its path names it after `/xrpc/`, and its request's | ||
| @@ -54,6 +64,17 @@ impl Route { | ||
Route::RevokeSession => "_oauthRevokeSession", | ||
Route::Devices => "_oauthDevices", | ||
Route::RevokeDevice => "_oauthRevokeDevice", | ||
Route::PasskeyList => "_passkeyList", | ||
Route::PasskeyAdd => "_passkeyAdd", | ||
Route::PasskeyRemove => "_passkeyRemove", | ||
} | ||
} | ||
| ||
/// Its group of commands. | ||
fn group(self) -> &'static str { | ||
match self { | ||
Route::PasskeyList | Route::PasskeyAdd | Route::PasskeyRemove => "passkey", | ||
_ => "oauth", | ||
} | ||
} | ||
| ||
| @@ -64,6 +85,9 @@ impl Route { | ||
Route::RevokeSession => "oauth_revoke_session", | ||
Route::Devices => "oauth_devices", | ||
Route::RevokeDevice => "oauth_revoke_device", | ||
Route::PasskeyList => "passkey_list", | ||
Route::PasskeyAdd => "passkey_add", | ||
Route::PasskeyRemove => "passkey_remove", | ||
} | ||
} | ||
| ||
| @@ -72,11 +96,19 @@ impl Route { | ||
Route::ALL.into_iter().find(|r| r.tool() == name) | ||
} | ||
| ||
/// The HTTP method it takes: a list `GET`, a revocation `POST`. | ||
/// The HTTP method it takes: a list `GET`, a change `POST`. | ||
pub fn method(self) -> Method { | ||
match self { | ||
Route::Sessions | Route::Devices => Method::GET, | ||
Route::RevokeSession | Route::RevokeDevice => Method::POST, | ||
Route::Sessions | Route::Devices | Route::PasskeyList => Method::GET, | ||
_ => Method::POST, | ||
} | ||
} | ||
| ||
/// The member of a `POST`'s body it takes, as its tool's argument. | ||
fn argument(self) -> &'static str { | ||
match self { | ||
Route::PasskeyAdd => "name", | ||
_ => "id", | ||
} | ||
} | ||
| ||
| @@ -94,11 +126,20 @@ impl Route { | ||
Route::RevokeDevice => { | ||
"Sign your account out of one browser by its id, as oauth_devices lists it. Its apps' sessions stay: end those with oauth_revoke_session. Needs your account's password session." | ||
} | ||
Route::PasskeyList => { | ||
"The passkeys of your account, newest first: each with its id, name, when it was added and last signed in, and whether it is backed up. Needs your account's password session." | ||
} | ||
Route::PasskeyAdd => { | ||
"A link to open in a browser within 15 minutes, which adds a passkey of this name to your account: it then signs in on the OAuth sign-in page with no password. A new link ends the last. Needs your account's password session." | ||
} | ||
Route::PasskeyRemove => { | ||
"Remove one of your account's passkeys by its id, as passkey_list lists it: it no longer signs in. Needs your account's password session." | ||
} | ||
} | ||
} | ||
| ||
/// Their MCP tools, in order, as `spec/COMMANDS.md`, "The account's | ||
/// OAuth sessions", gives them. | ||
/// OAuth sessions" and "The account's passkeys", give them. | ||
pub fn tools() -> impl Iterator<Item = Json> { | ||
Route::ALL.into_iter().map(|r| { | ||
let (schema, annotations) = if r.method() == Method::GET { | ||
| @@ -107,20 +148,26 @@ impl Route { | ||
json!({ "readOnlyHint": true }), | ||
) | ||
} else { | ||
let arg = r.argument(); | ||
let mut property = json!({ "type": "string" }); | ||
if r == Route::PasskeyAdd { | ||
property["minLength"] = json!(1); | ||
property["maxLength"] = json!(64); | ||
} | ||
( | ||
json!({ | ||
"type": "object", | ||
"properties": { "id": { "type": "string" } }, | ||
"required": ["id"], | ||
"properties": { arg: property }, | ||
"required": [arg], | ||
}), | ||
json!({ "readOnlyHint": false, "destructiveHint": true }), | ||
json!({ "readOnlyHint": false, "destructiveHint": r != Route::PasskeyAdd }), | ||
) | ||
}; | ||
// Its command's name, as `revoke-session` of `oauth_revoke_session`. | ||
let command = r.tool()["oauth_".len()..].replace('_', "-"); | ||
let command = r.tool()[r.group().len() + 1..].replace('_', "-"); | ||
json!({ | ||
"name": r.tool(), | ||
"title": pds_lexicon::title("oauth", &command), | ||
"title": pds_lexicon::title(r.group(), &command), | ||
"description": r.description(), | ||
"inputSchema": schema, | ||
"annotations": annotations, | ||
| @@ -139,9 +186,10 @@ fn forbidden<T>() -> Result<T, XrpcError> { | ||
) | ||
} | ||
| ||
/// Answer a call of a route: its token, then its HTTP method, then a | ||
/// revocation's body, then its point of `global`, then what it does. A call | ||
/// whose OAuth access token passed is `Bearer::OAuth`, and refused. | ||
/// Answer a call of a route: its token, then its HTTP method, then | ||
/// `_passkeyAdd`'s account's state (`spec/LIFECYCLE.md`, "Its own calls"), | ||
/// then a `POST`'s body, then its point of `global`, then what it does. A | ||
/// call whose OAuth access token passed is `Bearer::OAuth`, and refused. | ||
pub(crate) async fn answer(svc: &Shared, route: Route, call: &Call<'_>) -> Result<Json, XrpcError> { | ||
if let Bearer::OAuth(_) = call.bearer { | ||
return forbidden(); | ||
| @@ -154,21 +202,25 @@ pub(crate) async fn answer(svc: &Shared, route: Route, call: &Call<'_>) -> Resul | ||
call.method | ||
)); | ||
} | ||
let id = if want == Method::POST { | ||
Some(id_of(call)?) | ||
if route == Route::PasskeyAdd { | ||
crate::lifecycle::gate(svc, route.name(), &did)?; | ||
} | ||
let arg = if want == Method::POST { | ||
Some(argument_of(call, route)?) | ||
} else { | ||
None | ||
}; | ||
limits::charge(svc, call, None, None)?; | ||
crate::ops::spawn(act(svc.clone(), route, did, id)) | ||
crate::ops::spawn(act(svc.clone(), route, did, arg)) | ||
.await | ||
.unwrap_or_else(|_| internal()) | ||
} | ||
| ||
/// A revocation's `id`, from its body: at most `limits::MAX_BODY` bytes, | ||
/// else `413`; then `application/json`, an object with `id` a string, its | ||
/// other properties ignored. | ||
fn id_of(call: &Call) -> Result<String, XrpcError> { | ||
/// A `POST`'s argument, from its body: at most `limits::MAX_BODY` bytes, | ||
/// else `413`; then `application/json`, an object with `id` a string, or | ||
/// `_passkeyAdd`'s `name` one of 1 to 64 characters, its other properties | ||
/// ignored. | ||
fn argument_of(call: &Call, route: Route) -> Result<String, XrpcError> { | ||
if call.body.len() > limits::MAX_BODY { | ||
return limits::too_large(); | ||
} | ||
| @@ -189,42 +241,57 @@ fn id_of(call: &Call) -> Result<String, XrpcError> { | ||
let Ok(Json::Object(b)) = serde_json::from_slice::<Json>(call.body) else { | ||
return invalid("Invalid request body"); | ||
}; | ||
match b.get("id") { | ||
Some(Json::String(id)) => Ok(id.clone()), | ||
Some(_) => invalid("Input/id must be a string"), | ||
None => invalid("Input must have the property \"id\""), | ||
let name = route.argument(); | ||
match b.get(name) { | ||
Some(Json::String(s)) if route != Route::PasskeyAdd => Ok(s.clone()), | ||
Some(Json::String(s)) => match s.chars().count() { | ||
0 => invalid("Input/name must not be shorter than 1 characters"), | ||
65.. => invalid("Input/name must not be longer than 64 characters"), | ||
_ => Ok(s.clone()), | ||
}, | ||
Some(_) => invalid(format!("Input/{name} must be a string")), | ||
None => invalid(format!("Input must have the property \"{name}\"")), | ||
} | ||
} | ||
| ||
/// What a route does for account `did`, answered once what it shows, or | ||
/// the end it logged, is on disk. | ||
/// What a route does for account `did`, with its argument, answered once | ||
/// what it shows, or the change it logged, is on disk. | ||
async fn act( | ||
svc: Shared, | ||
route: Route, | ||
did: String, | ||
id: Option<String>, | ||
arg: Option<String>, | ||
) -> Result<Json, XrpcError> { | ||
let id = id.unwrap_or_default(); | ||
let id = arg.unwrap_or_default(); | ||
let mut tx = Tx::new(&svc); | ||
let out = tx.change(|st, now| match route { | ||
Route::Sessions => (vec![], json!({ "sessions": sessions(&svc, st, &did, now) })), | ||
Route::Devices => (vec![], json!({ "devices": devices(&svc, st, &did, now) })), | ||
Route::Sessions => ( | ||
vec![], | ||
Ok(json!({ "sessions": sessions(&svc, st, &did, now) })), | ||
), | ||
Route::Devices => ( | ||
vec![], | ||
Ok(json!({ "devices": devices(&svc, st, &did, now) })), | ||
), | ||
Route::RevokeSession => ( | ||
session_named(&svc, st, &did, &id, now) | ||
.map(|sid| json!({ "t": "oauthEndSession", "sid": sid })) | ||
.into_iter() | ||
.collect(), | ||
json!({}), | ||
Ok(json!({})), | ||
), | ||
Route::RevokeDevice => ( | ||
device_named(&svc, st, &did, &id) | ||
.map(|device| json!({ "t": "oauthSignOut", "device": device, "did": did })) | ||
.into_iter() | ||
.collect(), | ||
json!({}), | ||
Ok(json!({})), | ||
), | ||
Route::PasskeyList | Route::PasskeyAdd | Route::PasskeyRemove => { | ||
super::passkeys::act(&svc, st, route, &did, &id) | ||
} | ||
}); | ||
if tx.done().await { Ok(out) } else { internal() } | ||
if tx.done().await { out } else { internal() } | ||
} | ||
| ||
/// The public id of a session or device, its id `id`, for `label`. | ||
crates/pds-server/src/oauth/page.rs+150−72
| @@ -32,7 +32,7 @@ const DEVICE_COOKIE_LIFE: u64 = 365 * 24 * 60 * 60; | ||
const DEVICE_GRACE: u64 = 30; | ||
| ||
/// A header's value as text, if it has one. | ||
fn header_text<'h>(headers: &'h HeaderMap, name: &str) -> Option<&'h str> { | ||
pub(super) fn header_text<'h>(headers: &'h HeaderMap, name: &str) -> Option<&'h str> { | ||
headers.get(name).and_then(|v| v.to_str().ok()) | ||
} | ||
| ||
| @@ -58,11 +58,13 @@ fn cookie(headers: &HeaderMap, name: &str) -> Option<String> { | ||
.map(|(_, v)| v) | ||
} | ||
| ||
/// The device a request is from, and the key of the cookies to give it, if | ||
/// it is to be given any. | ||
struct Device { | ||
id: String, | ||
/// The device a request is from, the key of the cookies to give it, if it | ||
/// is to be given any, and whether the request named a device, with | ||
/// cookies the server sealed. | ||
pub(super) struct Device { | ||
pub id: String, | ||
give: Option<String>, | ||
pub named: bool, | ||
} | ||
| ||
impl Device { | ||
| @@ -70,6 +72,7 @@ impl Device { | ||
Device { | ||
id: new_id(16), | ||
give: Some(new_id(16)), | ||
named: false, | ||
} | ||
} | ||
} | ||
| @@ -91,18 +94,36 @@ fn device(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap) -> Device { | ||
return Device::new(); | ||
}; | ||
tx.change(|st, now| match st.device_keys.get(&id) { | ||
None => (vec![], Device { id, give: None }), | ||
Some((current, _)) if *current == key => (vec![], Device { id, give: None }), | ||
None => ( | ||
vec![], | ||
Device { | ||
id, | ||
give: None, | ||
named: true, | ||
}, | ||
), | ||
Some((current, _)) if *current == key => ( | ||
vec![], | ||
Device { | ||
id, | ||
give: None, | ||
named: true, | ||
}, | ||
), | ||
Some((current, at)) if now.saturating_sub(*at) <= DEVICE_GRACE => ( | ||
vec![], | ||
Device { | ||
give: Some(current.clone()), | ||
id, | ||
named: true, | ||
}, | ||
), | ||
Some(_) => ( | ||
vec![json!({ "t": "oauthDeviceEnd", "device": id })], | ||
Device::new(), | ||
Device { | ||
named: true, | ||
..Device::new() | ||
}, | ||
), | ||
}) | ||
} | ||
| @@ -160,7 +181,7 @@ fn csp(script: &str) -> String { | ||
| ||
/// A page: the app the build embeds (`super::assets`), and its data, as | ||
/// `window["<name>"]=JSON.parse("…");` statements, its one inline script. | ||
fn page(status: u16, title: &'static str, data: &[(&str, &Json)]) -> Response { | ||
pub(super) fn page(status: u16, title: &'static str, data: &[(&str, &Json)]) -> Response { | ||
let statements: String = data | ||
.iter() | ||
.map(|(name, v)| format!("window[\"{name}\"]=JSON.parse({});", js_json(v))) | ||
| @@ -291,12 +312,12 @@ pub(super) fn query(uri: &Uri) -> Vec<(String, String)> { | ||
.collect() | ||
} | ||
| ||
fn param<'q>(q: &'q [(String, String)], k: &str) -> Option<&'q str> { | ||
pub(super) fn param<'q>(q: &'q [(String, String)], k: &str) -> Option<&'q str> { | ||
q.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) | ||
} | ||
| ||
/// An account, as the page and the API show it. | ||
fn account_json(svc: &Service, a: &Account) -> Json { | ||
pub(super) fn account_json(svc: &Service, a: &Account) -> Json { | ||
let m = crate::email::lock(&a.mail).clone(); | ||
let deactivated = crate::read(&a.state).deactivated; | ||
let mut out = json!({ | ||
| @@ -327,7 +348,7 @@ fn account_json(svc: &Service, a: &Account) -> Json { | ||
} | ||
| ||
/// Whether a request is a navigation to a page, as the authorization page needs. | ||
fn navigation(svc: &Service, headers: &HeaderMap, sites: &[&str]) -> bool { | ||
pub(super) fn navigation(svc: &Service, headers: &HeaderMap, sites: &[&str]) -> bool { | ||
header_text(headers, "sec-fetch-mode") == Some("navigate") | ||
&& header_text(headers, "sec-fetch-dest") == Some("document") | ||
&& header_text(headers, "sec-fetch-site").is_some_and(|s| sites.contains(&s)) | ||
| @@ -422,25 +443,37 @@ pub(super) async fn authorize( | ||
}; | ||
// Each set the request includes, resolved again (`spec/OAUTH-PERMISSION-SETS.md`). | ||
let mut r = match svc.oauth.sets.resolve_all(&svc, &loaded.request.scope).await { | ||
Ok(sets) => authorization_page(&svc, request_uri, &client, &loaded, &sets), | ||
Ok(sets) => authorization_page(&svc, request_uri, &client, &loaded, &sets, &device.id), | ||
Err((nsid, _)) => error_page(400, "invalid_scope", &format!("Permission set {nsid} could not be resolved")), | ||
}; | ||
device_cookie(&svc, &mut r, &device); | ||
let csrf = format!("{CSRF_COOKIE}={}; Path=/; SameSite=Lax{}", hex::encode(rand::random::<[u8; 16]>()), secure(&svc)); | ||
if let Ok(v) = csrf.parse() { | ||
r.headers_mut().append(header::SET_COOKIE, v); | ||
} | ||
csrf_cookie(&svc, &mut r); | ||
r | ||
}) | ||
.await | ||
} | ||
| ||
/// Give a page the `csrf-token` cookie its script sends back as `x-csrf-token`. | ||
pub(super) fn csrf_cookie(svc: &Service, r: &mut Response) { | ||
let csrf = format!( | ||
"{CSRF_COOKIE}={}; Path=/; SameSite=Lax{}", | ||
hex::encode(rand::random::<[u8; 16]>()), | ||
secure(svc) | ||
); | ||
if let Ok(v) = csrf.parse() { | ||
r.headers_mut().append(header::SET_COOKIE, v); | ||
} | ||
} | ||
| ||
/// The authorization page of a request loaded on device `device`, which it | ||
/// gives a new passkey challenge (`spec/PASSKEYS.md`, "The page's options"). | ||
fn authorization_page( | ||
svc: &Service, | ||
request_uri: &str, | ||
client: &client::Client, | ||
loaded: &Loaded, | ||
sets: &std::collections::HashMap<String, std::sync::Arc<Json>>, | ||
device: &str, | ||
) -> Response { | ||
let r = &loaded.request; | ||
let now = svc.sessions.now(); | ||
| @@ -486,10 +519,15 @@ fn authorization_page( | ||
{ | ||
data["selectedDid"] = json!(a.did); | ||
} | ||
let passkey = super::passkeys::challenge_for(svc, device); | ||
page( | ||
200, | ||
"Sign in", | ||
&[("__authorizeData", &data), ("__sessions", &json!(sessions))], | ||
&[ | ||
("__authorizeData", &data), | ||
("__sessions", &json!(sessions)), | ||
("__passkeyOptions", &passkey), | ||
], | ||
) | ||
} | ||
| ||
| @@ -541,11 +579,12 @@ fn api_error(status: u16, description: &str) -> Response { | ||
r | ||
} | ||
| ||
/// A body field's type. | ||
/// A body field's type: `Any` is checked by its endpoint, in its own order. | ||
#[derive(Clone, Copy)] | ||
enum Field { | ||
Text(fn(&str) -> bool), | ||
Bool, | ||
Any, | ||
} | ||
| ||
/// The fields each endpoint takes: name, type, and whether it is required. | ||
| @@ -574,11 +613,19 @@ fn fields(endpoint: &str) -> Option<&'static [(&'static str, Field, bool)]> { | ||
]; | ||
const SIGN_OUT: &[(&str, Field, bool)] = | ||
&[("did", Field::Text(pds_repo::data::valid_did), true)]; | ||
const PASSKEY_SIGN_IN: &[(&str, Field, bool)] = &[ | ||
("locale", Field::Text(super::valid_locale), true), | ||
("credential", Field::Any, true), | ||
("remember", Field::Bool, false), | ||
]; | ||
const PASSKEY_REGISTER: &[(&str, Field, bool)] = &[("credential", Field::Any, true)]; | ||
Some(match endpoint { | ||
"sign-in" => SIGN_IN, | ||
"consent" => CONSENT, | ||
"reject" => &[], | ||
"reject" | "passkey-options" => &[], | ||
"sign-out" => SIGN_OUT, | ||
"passkey-sign-in" => PASSKEY_SIGN_IN, | ||
"passkey-register" => PASSKEY_REGISTER, | ||
_ => return None, | ||
}) | ||
} | ||
| @@ -630,6 +677,7 @@ fn body_of(fields: &[(&str, Field, bool)], body: &[u8]) -> Result<Map<String, Js | ||
(None, _) => !required, | ||
(Some(Json::String(s)), Field::Text(valid)) => valid(s), | ||
(Some(Json::Bool(_)), Field::Bool) => true, | ||
(Some(_), Field::Any) => true, | ||
_ => false, | ||
}; | ||
if !right { | ||
| @@ -662,7 +710,14 @@ pub(super) async fn api( | ||
if header_text(&headers, "origin").is_some_and(|o| o != svc.oauth.issuer) { | ||
return api_error(400, "Invalid origin"); | ||
} | ||
let Some(request_id) = referer_request(&svc, &headers) else { | ||
// A call of the authorization page is for its request; `passkey-register`, | ||
// the passkey page's, for its link (`spec/PASSKEYS.md`, "passkey-register"). | ||
let from = if endpoint == "passkey-register" { | ||
super::passkeys::referer_link(&svc, &headers) | ||
} else { | ||
referer_request(&svc, &headers) | ||
}; | ||
let Some(from) = from else { | ||
return api_error(400, "Invalid referer"); | ||
}; | ||
let csrf = header_text(&headers, "x-csrf-token"); | ||
| @@ -699,23 +754,21 @@ pub(super) async fn api( | ||
let whence = Whence::of(&headers, &client); | ||
finish(async move { | ||
let mut tx = Tx::new(&svc); | ||
let mut device = device(&svc, &mut tx, &headers); | ||
let answer = match endpoint.as_str() { | ||
"sign-in" => { | ||
sign_in( | ||
&svc, | ||
&mut tx, | ||
&mut device, | ||
&request_id, | ||
&client, | ||
&whence, | ||
&b, | ||
) | ||
.await | ||
} | ||
"consent" => consent(&svc, &mut tx, &headers, &device.id, &request_id, &b).await, | ||
"reject" => reject(&svc, &mut tx, &request_id), | ||
_ => sign_out(&mut tx, &device.id, &b).map_err(Refusal::from), | ||
// The passkey page names no device, and is given none. | ||
let mut device = (endpoint != "passkey-register").then(|| device(&svc, &mut tx, &headers)); | ||
let request_id = from.as_str(); | ||
let answer = match device.as_mut() { | ||
None => super::passkeys::register(&svc, &mut tx, &from, &b), | ||
Some(device) => match endpoint.as_str() { | ||
"sign-in" => sign_in(&svc, &mut tx, device, request_id, &client, &whence, &b).await, | ||
"consent" => consent(&svc, &mut tx, &headers, &device.id, request_id, &b).await, | ||
"reject" => reject(&svc, &mut tx, request_id), | ||
"passkey-options" => super::passkeys::options(&svc, device), | ||
"passkey-sign-in" => { | ||
super::passkeys::sign_in(&svc, &mut tx, device, request_id, &whence, &b) | ||
} | ||
_ => sign_out(&mut tx, &device.id, &b).map_err(Refusal::from), | ||
}, | ||
}; | ||
if let Some(floor) = floor { | ||
tokio::time::sleep_until(floor).await; | ||
| @@ -740,7 +793,9 @@ pub(super) async fn api( | ||
} | ||
}; | ||
set(&mut r, "cache-control", "no-store"); | ||
device_cookie(&svc, &mut r, &device); | ||
if let Some(device) = &device { | ||
device_cookie(&svc, &mut r, device); | ||
} | ||
r | ||
}) | ||
.await | ||
| @@ -756,11 +811,21 @@ const FACTOR_TRUST: u64 = 30 * 24 * 60 * 60; | ||
| ||
/// What the API answers in place of what was asked: its status, `error` | ||
/// and description, and for a rate limit, the seconds to wait. | ||
struct Refusal { | ||
status: u16, | ||
error: &'static str, | ||
description: String, | ||
retry_after: Option<u64>, | ||
pub(super) struct Refusal { | ||
pub status: u16, | ||
pub error: &'static str, | ||
pub description: String, | ||
pub retry_after: Option<u64>, | ||
} | ||
| ||
/// The refusal of a call below the free-space floor that would keep something. | ||
pub(super) fn out_of_space() -> Refusal { | ||
Refusal { | ||
status: 507, | ||
error: "temporarily_unavailable", | ||
description: "Not enough free space to store this".into(), | ||
retry_after: None, | ||
} | ||
} | ||
| ||
impl From<String> for Refusal { | ||
| @@ -850,17 +915,14 @@ async fn sign_in( | ||
// Its checks passed, below the free space nothing is kept, a code | ||
// made or used up, or the sign-in. | ||
if super::low(svc) { | ||
return Err(Refusal { | ||
status: 507, | ||
error: "temporarily_unavailable", | ||
description: "Not enough free space to store this".into(), | ||
retry_after: None, | ||
}); | ||
return Err(out_of_space()); | ||
} | ||
match code { | ||
Some(_) => { | ||
let used = crate::email::use_entry(&did, AuthFactor); | ||
let remembered = sign_in_here(tx, device, &did, remember, whence, Some(&used)); | ||
let remembered = sign_in_here(tx, device, &did, remember, whence, |_, _| { | ||
Ok(vec![used.clone()]) | ||
})?; | ||
if !tx.failed { | ||
crate::email::apply(svc, &did, &mut m, &[used]); | ||
} | ||
| @@ -870,7 +932,10 @@ async fn sign_in( | ||
Some(crate::email::make(svc, &did, &mut m, AuthFactor)?), | ||
false, | ||
), | ||
None => (None, sign_in_here(tx, device, &did, remember, whence, None)), | ||
None => ( | ||
None, | ||
sign_in_here(tx, device, &did, remember, whence, |_, _| Ok(vec![]))?, | ||
), | ||
} | ||
}; | ||
if let Some(mail) = mail { | ||
| @@ -883,33 +948,50 @@ async fn sign_in( | ||
retry_after: None, | ||
}); | ||
} | ||
let mut out = json!({ "account": account_json(svc, &account) }); | ||
Ok(signed_in(svc, &account, device, request_id, remembered)) | ||
} | ||
| ||
/// What a sign-in of `account` on `device`, for request `request_id`, | ||
/// answers: the account, and, when it was not remembered there, an | ||
/// ephemeral token of the sign-in. | ||
pub(super) fn signed_in( | ||
svc: &Service, | ||
account: &Account, | ||
device: &Device, | ||
request_id: &str, | ||
remembered: bool, | ||
) -> Json { | ||
let mut out = json!({ "account": account_json(svc, account) }); | ||
if !remembered { | ||
let exp = svc.sessions.now() + EPHEMERAL_LIFE; | ||
out["ephemeralToken"] = json!(svc.oauth.seal( | ||
"ephemeral", | ||
&json!({ "did": did, "device": device.id, "request": request_id, "exp": exp }) | ||
&json!({ "did": account.did, "device": device.id, "request": request_id, "exp": exp }) | ||
)); | ||
} | ||
Ok(out) | ||
out | ||
} | ||
| ||
/// Sign `did` in on `device`, with a code it used up (`used`), in one frame: | ||
/// remembered, or with `remember` left out when it is signed in here | ||
/// already, it is signed in here from now, from `whence`; otherwise it is | ||
/// not, or no longer. Either way the device is given new cookies, and those | ||
/// it had are old (`spec/OAUTH.md`, "Devices"). Answers whether it is | ||
/// remembered. | ||
fn sign_in_here( | ||
/// Sign `did` in on `device`, in one frame with the entries `with` makes | ||
/// under OAuth's lock, as a code it used up, unless it refuses: remembered, | ||
/// or with `remember` left out when it is signed in here already, it is | ||
/// signed in here from now, from `whence`; otherwise it is not, or no | ||
/// longer. Either way the device is given new cookies, and those it had are | ||
/// old (`spec/OAUTH.md`, "Devices"). Answers whether it is remembered. | ||
pub(super) fn sign_in_here( | ||
tx: &mut Tx<'_>, | ||
device: &mut Device, | ||
did: &str, | ||
remember: Option<bool>, | ||
whence: &Whence, | ||
used: Option<&Json>, | ||
) -> bool { | ||
with: impl FnOnce(&State, u64) -> Result<Vec<Json>, Refusal>, | ||
) -> Result<bool, Refusal> { | ||
let (id, key) = (device.id.as_str(), new_id(16)); | ||
let remembered = tx.change(|st, now| { | ||
let first = match with(st, now) { | ||
Ok(entries) => entries, | ||
Err(no) => return (vec![], Err(no)), | ||
}; | ||
let signed = st.signed_in(id).iter().any(|(d, _)| d == did); | ||
let remembered = remember.unwrap_or(signed); | ||
let entry = if remembered { | ||
| @@ -921,16 +1003,12 @@ fn sign_in_here( | ||
}; | ||
let renewed = json!({ "t": "oauthDeviceKey", "device": id, "key": key, "at": now }); | ||
( | ||
used.cloned() | ||
.into_iter() | ||
.chain(entry) | ||
.chain([renewed]) | ||
.collect(), | ||
remembered, | ||
first.into_iter().chain(entry).chain([renewed]).collect(), | ||
Ok(remembered), | ||
) | ||
}); | ||
})?; | ||
device.give = Some(key); | ||
remembered | ||
Ok(remembered) | ||
} | ||
| ||
/// Whether `Authorization: Bearer` holds an ephemeral token of a sign-in of `did`, on this device, for this request. | ||
crates/pds-server/src/oauth/passkeys.rsnew+576−0
576 lines changed: not loaded until asked for.
crates/pds-server/src/compact.rs+25−1
| @@ -860,7 +860,9 @@ impl Folder { | ||
let mut rest: Vec<Json> = self.invites.entries(); | ||
rest.extend(self.held); | ||
rest.extend(self.lifecycle.entries(keep)); | ||
rest.extend(latest_devices(latest_refreshes(self.oauth))); | ||
rest.extend(latest_devices(latest_refreshes(latest_passkey_uses( | ||
self.oauth, | ||
)))); | ||
rest.extend(self.spent); | ||
rest.extend( | ||
standing | ||
| @@ -1070,6 +1072,28 @@ fn latest_refreshes(oauth: Vec<Json>) -> Vec<Json> { | ||
.collect() | ||
} | ||
| ||
/// OAuth's entries, in order, but each passkey's sign-ins before its last: | ||
/// a sign-in sets all that one keeps of a passkey's (its count, BS and last | ||
/// use), so only the last counts in a replay, and however often a passkey | ||
/// signs in, what is kept of it stays the same. | ||
fn latest_passkey_uses(oauth: Vec<Json>) -> Vec<Json> { | ||
let is_use = |e: &Json| e["t"] == "oauthPasskeyUse"; | ||
let mut last: HashMap<String, usize> = HashMap::new(); | ||
for (i, e) in oauth.iter().enumerate() { | ||
if is_use(e) | ||
&& let Some(id) = e["id"].as_str() | ||
{ | ||
last.insert(id.to_string(), i); | ||
} | ||
} | ||
oauth | ||
.into_iter() | ||
.enumerate() | ||
.filter(|(i, e)| !is_use(e) || e["id"].as_str().is_none_or(|id| last.get(id) == Some(i))) | ||
.map(|(_, e)| e) | ||
.collect() | ||
} | ||
| ||
/// OAuth's entries, in order, but of each device only what its entries | ||
/// leave: each account's last sign-in on it, unless a sign-out of that | ||
/// account or the device's end came after, and its last cookies' key, unless | ||
crates/pds-server/src/email.rs+3−1
| @@ -910,11 +910,13 @@ async fn reset_password(s: Shared, b: Map<String, Json>) -> Result<Resp, XrpcErr | ||
use_entry(&did, Purpose::ResetPassword), | ||
]; | ||
// Every session it has ends, in the same frame; and of OAuth's, its | ||
// sessions, the requests approved for it, and its sign-ins on every device. | ||
// sessions, the requests approved for it, its sign-ins on every | ||
// device, and its passkeys, with its link to add one. | ||
let ends = crate::oauth::Ends { | ||
sessions: true, | ||
requests: true, | ||
devices: true, | ||
passkeys: true, | ||
..Default::default() | ||
}; | ||
let n = s | ||
crates/pds-server/src/lib.rs+16−2
| @@ -22,8 +22,10 @@ | ||
//! registrations, and the updates and notices sent them); the firehose is `events`, the MCP | ||
//! endpoint `mcp`, the PLC directory `plc`, requests to URLs others name, | ||
//! with SSRF protection, `outbound`, OAuth's authorization server `oauth`, | ||
//! with the account's own routes for its OAuth sessions and devices in | ||
//! `oauth::account`, | ||
//! with the account's own routes for its OAuth sessions and devices, and | ||
//! for its passkeys, in `oauth::account`, and passkeys, which sign it in | ||
//! on the authorization page, in `oauth::passkeys` (they have no NSID, so | ||
//! no area of `AREAS` answers them), | ||
//! OAuth access tokens on every method and what their scopes allow | ||
//! `scopes`, the single-use values OAuth spends `replay`, single-use values | ||
//! the spaces spend `single_use`, what keeps the server up when anyone may | ||
| @@ -897,6 +899,18 @@ fn router(svc: Shared) -> Router { | ||
"/xrpc/_oauthRevokeDevice", | ||
any(|s, m, h, p, b| account::xrpc(s, m, h, p, b, Own::RevokeDevice)), | ||
) | ||
.route( | ||
"/xrpc/_passkeyList", | ||
any(|s, m, h, p, b| account::xrpc(s, m, h, p, b, Own::PasskeyList)), | ||
) | ||
.route( | ||
"/xrpc/_passkeyAdd", | ||
any(|s, m, h, p, b| account::xrpc(s, m, h, p, b, Own::PasskeyAdd)), | ||
) | ||
.route( | ||
"/xrpc/_passkeyRemove", | ||
any(|s, m, h, p, b| account::xrpc(s, m, h, p, b, Own::PasskeyRemove)), | ||
) | ||
.route("/xrpc/com.atproto.repo.uploadBlob", any(blobs::upload)) | ||
.route("/xrpc/{*method}", any(handle)) | ||
.route("/mcp", any(mcp::endpoint)) | ||
crates/pds-server/src/lifecycle.rs+3−1
crates/pds-server/src/log.rs+27−1
crates/pds-server/src/mcp.rs+34−12
crates/pds-server/src/oauth.rs+46−6
crates/pds-server/src/ops.rs+7−3
crates/pds-server/src/sessions.rs+14−0
crates/pds-server/Cargo.toml+5−0
docs/guide/calling.md+16−0
docs/guide/contributing.md+9−5
docs/guide/deploying.md+1−1
docs-site/astro.config.mjs+1−1
harness/checks/commands.mjs+74−62
harness/checks/crashes.mjs+3−0
harness/checks/lifecycle.mjs+52−2
harness/checks/limits.mjs+37−1
harness/checks/oauth-account.mjs+3−3
harness/checks/oauth-mcp.mjs+29−0
harness/checks/pages.mjs+459−10
469 lines changed: not loaded until asked for.
harness/checks/passkeys.mjsnew+1427−0
1427 lines changed: not loaded until asked for.
harness/lib/observe.mjs+8−3
harness/lib/via.mjs+55−36
harness/lib/webauthn.mjsnew+347−0
harness/compare.mjs+3−1
harness/dev.mjs+3−1
harness/look.mjs+34−4
spec/webauthn/LICENSE-W3C.mdnew+35−0
spec/webauthn/README.mdnew+14−0
spec/webauthn/rfc8017.txtnew+4371−0
A large diff, not shown.
spec/webauthn/rfc8230.txtnew+675−0
675 lines changed: not loaded until asked for.
spec/webauthn/rfc8812.txtnew+533−0
533 lines changed: not loaded until asked for.
spec/webauthn/rfc8949.txtnew+3674−0
A large diff, not shown.
spec/webauthn/rfc9052.txtnew+3603−0
A large diff, not shown.
spec/webauthn/rfc9053.txtnew+2443−0
A large diff, not shown.
spec/webauthn/webauthn-3.mdnew+9888−0
A large diff, not shown.
spec/COMMANDS.md+46−9
spec/DURABILITY.md+3−2
spec/EMAIL.md+3−1
spec/LIFECYCLE.md+7−2
spec/LIMITS.md+1−1
spec/OAUTH-ACCOUNT.md+2−1
spec/OAUTH-PAGES.md+120−9
spec/OAUTH.md+31−15
spec/OPERATIONS.md+8−5
spec/PASSKEYS.mdnew+479−0
479 lines changed: not loaded until asked for.