chadtmiller.com/group-host
atmosphere group host
0
0
Stewards hold recovery keys to a group's identity
crates/group-host/src/lib.rs+13−0
| @@ -37,6 +37,7 @@ pub mod oauth_store; | ||
pub mod plc; | ||
pub mod provision; | ||
pub mod rbac; | ||
pub mod recovery; | ||
pub mod repo; | ||
pub mod scopes; | ||
pub mod secrets; | ||
| @@ -381,6 +382,18 @@ pub fn router(host: Arc<Host>) -> Router { | ||
"/xrpc/com.atproto.moderation.createReport", | ||
post(moderation::create_report), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.listRecoveryKeys", | ||
get(recovery::list_recovery_keys), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.addRecoveryKey", | ||
post(recovery::add_recovery_key), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.removeRecoveryKey", | ||
post(recovery::remove_recovery_key), | ||
) | ||
.route("/oauth/authorize", get(oauth::authorize)) | ||
.route( | ||
"/console/client-metadata.json", | ||
crates/group-host/src/lifecycle.rs+14−3
| @@ -93,12 +93,23 @@ impl Host { | ||
if let Err(e) = &ended { | ||
tracing::warn!(did, error = %format!("{e:#}"), "could not end the DID"); | ||
} | ||
Ok(ended.is_ok()) | ||
Ok(ended.unwrap_or(false)) | ||
} | ||
| ||
async fn tombstone(&self, did: &str) -> Result<()> { | ||
/// Ends `did` in the directory, if nobody but this host could ever use | ||
/// it again: with a steward's recovery key on it, it is theirs to keep, | ||
/// to bring the group back elsewhere, and is left alone. Whether it | ||
/// ended it. | ||
async fn tombstone(&self, did: &str) -> Result<bool> { | ||
let last = self.plc.last_op(did).await?; | ||
let ours = self.secrets.rotation.public().did_key(); | ||
if let atproto::plc::Signed::Update { op, .. } = &last | ||
&& op.rotation_keys.iter().any(|k| *k != ours) | ||
{ | ||
return Ok(false); | ||
} | ||
let end = atproto::plc::tombstone(last.cid(), &self.secrets.rotation); | ||
self.plc.publish(did, &end).await.context("tombstoning") | ||
self.plc.publish(did, &end).await.context("tombstoning")?; | ||
Ok(true) | ||
} | ||
} | ||
crates/group-host/src/recovery.rsnew+272−0
| @@ -0,0 +1,272 @@ | ||
//! Recovery keys: rotation keys on a group's `did:plc` that its stewards | ||
//! hold and the host never sees. | ||
//! | ||
//! A group's identity is in the hands of the rotation keys its PLC | ||
//! document names. Left alone, the only one is this host's, so the host | ||
//! alone could move the group, and nobody could move it without the host. | ||
//! A recovery key sits ahead of the host's: PLC lets a key ranked higher | ||
//! undo, for 72 hours, an operation one ranked lower signed, so whoever | ||
//! holds one can undo anything this host does to the identity, and take | ||
//! the group to another host without it. That is what makes leaving | ||
//! possible. A group with one is, when deleted, left to them: its DID is | ||
//! theirs to bring back elsewhere (`lifecycle.rs`). | ||
//! | ||
//! The keys are the directory's to say; the host remembers only who added | ||
//! which, to show. | ||
//! | ||
//! As the prototype's `methods/recovery.ts`. | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, param}; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::rbac::NS; | ||
use crate::store::Store; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
use anyhow::Result; | ||
use atproto::PublicKey; | ||
use atproto::plc::{Op, Signed}; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode}; | ||
use rusqlite::params; | ||
use serde_json::{Value, json}; | ||
use std::collections::HashMap; | ||
use std::sync::Arc; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| ||
/// PLC takes at most five rotation keys, one of them this host's. | ||
pub const RECOVERY_KEYS_AT_MOST: usize = 4; | ||
| ||
fn refused(error: &'static str, message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, error, message) | ||
} | ||
| ||
impl Store { | ||
/// Who added each of `group`'s recovery keys, and when. | ||
pub fn recovery_keys(&self, group: &str) -> Result<HashMap<String, (String, i64)>> { | ||
let conn = self.conn(); | ||
let mut q = | ||
conn.prepare("SELECT key, added_by, added_at FROM recovery_key WHERE grp = ?1")?; | ||
let rows = q.query_map([group], |r| Ok((r.get(0)?, (r.get(1)?, r.get(2)?))))?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// Notes that `by` added `key` to `group`, or, with no `by`, that it is | ||
/// gone. | ||
pub fn note_recovery_key( | ||
&self, | ||
group: &str, | ||
key: &str, | ||
by: Option<&str>, | ||
at: i64, | ||
) -> Result<()> { | ||
let conn = self.conn(); | ||
match by { | ||
Some(by) => conn.execute( | ||
"INSERT OR REPLACE INTO recovery_key (grp, key, added_by, added_at) VALUES (?1, ?2, ?3, ?4)", | ||
params![group, key, by, at], | ||
)?, | ||
None => conn.execute("DELETE FROM recovery_key WHERE grp = ?1 AND key = ?2", [group, key])?, | ||
}; | ||
Ok(()) | ||
} | ||
} | ||
| ||
/// A group's rotation keys as the directory holds them now. | ||
struct Keys { | ||
last: Signed, | ||
op: Op, | ||
/// This host's key. | ||
ours: String, | ||
/// Every other, in the order they are ranked. | ||
stewards: Vec<String>, | ||
} | ||
| ||
impl Keys { | ||
fn host_holds(&self) -> bool { | ||
self.op.rotation_keys.contains(&self.ours) | ||
} | ||
} | ||
| ||
impl Host { | ||
/// The group a body or query names, for `me`, who may configure it. | ||
async fn configuring( | ||
&self, | ||
headers: &HeaderMap, | ||
lxm: &str, | ||
group: Option<&str>, | ||
) -> Result<(String, String), XrpcError> { | ||
let me = signed_in(self, headers, &format!("{NS}.{lxm}")).await?; | ||
let group = group.ok_or_else(|| invalid("group is required"))?; | ||
group_of(self, group)?; | ||
if !self.may_do(group, &me, "group.configure")? { | ||
return Err(XrpcError::new( | ||
StatusCode::FORBIDDEN, | ||
"Forbidden", | ||
"missing group.configure", | ||
)); | ||
} | ||
Ok((group.to_string(), me)) | ||
} | ||
| ||
async fn rotation_keys(&self, group: &str) -> Result<Keys, XrpcError> { | ||
let last = self.plc.last_op(group).await.map_err(XrpcError::internal)?; | ||
let Signed::Update { op, .. } = &last else { | ||
return Err(refused("NotController", "the group's DID is ended")); | ||
}; | ||
let op = op.clone(); | ||
let ours = self.secrets.rotation.public().did_key(); | ||
let stewards = op | ||
.rotation_keys | ||
.iter() | ||
.filter(|k| **k != ours) | ||
.cloned() | ||
.collect(); | ||
Ok(Keys { | ||
last, | ||
op, | ||
ours, | ||
stewards, | ||
}) | ||
} | ||
| ||
/// Writes the group's rotation keys: its stewards', in order, and | ||
/// this host's last, signed by this host's. | ||
async fn set_rotation_keys( | ||
&self, | ||
group: &str, | ||
keys: &Keys, | ||
stewards: Vec<String>, | ||
) -> Result<(), XrpcError> { | ||
if !keys.host_holds() { | ||
return Err(refused( | ||
"NotController", | ||
"this host no longer holds a rotation key for the group, so it cannot change them", | ||
)); | ||
} | ||
let mut next = keys.op.clone(); | ||
next.rotation_keys = stewards; | ||
next.rotation_keys.push(keys.ours.clone()); | ||
let signed = next.sign(Some(keys.last.cid()), &self.secrets.rotation); | ||
self.plc | ||
.publish(group, &signed) | ||
.await | ||
.map_err(XrpcError::internal) | ||
} | ||
} | ||
| ||
/// The group's rotation keys that matter, the highest ranked first, and | ||
/// who added each, for one who configures it. | ||
pub async fn list_recovery_keys( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let (group, _) = host | ||
.configuring(&headers, "listRecoveryKeys", Some(param(&p, "group")?)) | ||
.await?; | ||
let keys = host.rotation_keys(&group).await?; | ||
let added = host | ||
.store | ||
.recovery_keys(&group) | ||
.map_err(XrpcError::internal)?; | ||
let listed: Vec<Value> = keys | ||
.op | ||
.rotation_keys | ||
.iter() | ||
.map(|key| { | ||
let holder = if *key == keys.ours { "host" } else { "steward" }; | ||
let mut view = json!({"key": key, "holder": holder}); | ||
if let Some((by, at)) = added.get(key) { | ||
view["addedBy"] = json!(by); | ||
view["addedAt"] = json!(iso(*at)); | ||
} | ||
view | ||
}) | ||
.collect(); | ||
Ok(Json( | ||
json!({"keys": listed, "hostHolds": keys.host_holds(), "max": RECOVERY_KEYS_AT_MOST}), | ||
)) | ||
} | ||
| ||
/// Puts a steward's key ahead of the host's, after any earlier ones. | ||
pub async fn add_recovery_key( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let (group, me) = host | ||
.configuring(&headers, "addRecoveryKey", body["group"].as_str()) | ||
.await?; | ||
let key = body["key"].as_str().unwrap_or_default(); | ||
if PublicKey::from_did_key(key).is_err() { | ||
return Err(refused( | ||
"InvalidKey", | ||
"not a did:key the directory takes (secp256k1 or P-256)", | ||
)); | ||
} | ||
let keys = host.rotation_keys(&group).await?; | ||
if keys.op.rotation_keys.iter().any(|k| k == key) { | ||
return Err(refused( | ||
"AlreadyAdded", | ||
"that key is a rotation key already", | ||
)); | ||
} | ||
if keys.stewards.len() >= RECOVERY_KEYS_AT_MOST { | ||
return Err(refused( | ||
"TooManyKeys", | ||
format!("a group has {RECOVERY_KEYS_AT_MOST} recovery keys at most"), | ||
)); | ||
} | ||
let mut stewards = keys.stewards.clone(); | ||
stewards.push(key.into()); | ||
host.set_rotation_keys(&group, &keys, stewards).await?; | ||
let noted = host | ||
.store | ||
.note_recovery_key(&group, key, Some(&me), now_millis()); | ||
noted.map_err(XrpcError::internal)?; | ||
host.record(&group, &me, None, "added a recovery key") | ||
.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// Takes a steward's key off the group's, the host's kept. | ||
pub async fn remove_recovery_key( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let (group, me) = host | ||
.configuring(&headers, "removeRecoveryKey", body["group"].as_str()) | ||
.await?; | ||
let key = body["key"].as_str().unwrap_or_default(); | ||
let keys = host.rotation_keys(&group).await?; | ||
if key == keys.ours { | ||
return Err(refused( | ||
"HostKey", | ||
"this host's own key is not a recovery key", | ||
)); | ||
} | ||
if !keys.stewards.iter().any(|k| k == key) { | ||
return Err(refused( | ||
"UnknownKey", | ||
"that key is not one of the group's recovery keys", | ||
)); | ||
} | ||
let stewards = keys | ||
.stewards | ||
.iter() | ||
.filter(|k| *k != key) | ||
.cloned() | ||
.collect(); | ||
host.set_rotation_keys(&group, &keys, stewards).await?; | ||
let noted = host | ||
.store | ||
.note_recovery_key(&group, key, None, now_millis()); | ||
noted.map_err(XrpcError::internal)?; | ||
host.record(&group, &me, None, "removed a recovery key") | ||
.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({}))) | ||
} | ||
crates/group-host/src/store.rs+10−0
| @@ -318,6 +318,15 @@ pub const MIGRATIONS: &[&str] = &[ | ||
created_at INTEGER NOT NULL | ||
); | ||
CREATE INDEX mod_event_subject ON mod_event (grp, subject, seq); | ||
", | ||
" | ||
CREATE TABLE recovery_key ( | ||
grp TEXT NOT NULL REFERENCES account (did), | ||
key TEXT NOT NULL, | ||
added_by TEXT NOT NULL, | ||
added_at INTEGER NOT NULL, | ||
PRIMARY KEY (grp, key) | ||
); | ||
", | ||
]; | ||
| ||
| @@ -436,6 +445,7 @@ const DEACTIVATION: &str = "SELECT at, by, stewards FROM deactivation WHERE did | ||
const ACTIVATE: &str = "DELETE FROM deactivation WHERE did = ?1"; | ||
/// What goes with an account, in an order its references allow. | ||
const FORGET_ACCOUNT: &[&str] = &[ | ||
"DELETE FROM recovery_key WHERE grp = ?1", | ||
"DELETE FROM mod_event WHERE grp = ?1", | ||
"DELETE FROM mod_subject WHERE grp = ?1", | ||
"DELETE FROM app_password WHERE grp = ?1", | ||
crates/group-host/tests/recovery.rsnew+257−0
| @@ -0,0 +1,257 @@ | ||
//! Recovery keys: a steward's rotation key ahead of the host's, so the | ||
//! group's identity is never the host's alone; and a deleted group's DID | ||
//! left to whoever holds one. | ||
| ||
mod common; | ||
| ||
use atproto::plc::{Signed, tombstone}; | ||
use atproto::{Curve, Keypair}; | ||
use common::groups::*; | ||
use common::spaces::*; | ||
use common::{Running, start}; | ||
use serde_json::{Value as Json, json}; | ||
| ||
async fn group(h: &Running) -> (String, [Authority; 3]) { | ||
let [alice, bob, carol] = people(h).await; | ||
let did = start_group( | ||
h, | ||
&alice, | ||
json!({"handle": RIDERS, "displayName": "Riders"}), | ||
) | ||
.await; | ||
(did, [alice, bob, carol]) | ||
} | ||
| ||
async fn call(h: &Running, who: &Authority, method: &str, body: Json) -> (u16, Json) { | ||
let lxm = format!("{NS}.{method}"); | ||
post(h, &lxm, &body, &[auth(h, who, &lxm)]).await | ||
} | ||
| ||
async fn list(h: &Running, who: &Authority, did: &str) -> (u16, Json) { | ||
let lxm = format!("{NS}.listRecoveryKeys"); | ||
get(h, &lxm, &format!("group={did}"), &[auth(h, who, &lxm)]).await | ||
} | ||
| ||
fn error(said: &(u16, Json)) -> (u16, &str) { | ||
(said.0, said.1["error"].as_str().unwrap_or_default()) | ||
} | ||
| ||
/// The group's rotation keys, as the directory holds them. | ||
async fn rotation_keys(h: &Running, did: &str) -> Vec<String> { | ||
match h.host.plc.last_op(did).await.unwrap() { | ||
Signed::Update { op, .. } => op.rotation_keys, | ||
Signed::Tombstone { .. } => panic!("ended"), | ||
} | ||
} | ||
| ||
fn key() -> (Keypair, String) { | ||
let k = Keypair::generate(Curve::K256); | ||
let did = k.public().did_key(); | ||
(k, did) | ||
} | ||
| ||
#[tokio::test] | ||
async fn puts_a_stewards_key_ahead_of_the_hosts() { | ||
let h = start(&[], false).await; | ||
let (did, [alice, ..]) = group(&h).await; | ||
let host_key = h.host.secrets.rotation.public().did_key(); | ||
let (_, first) = key(); | ||
let (_, second) = key(); | ||
for k in [&first, &second] { | ||
let said = call( | ||
&h, | ||
&alice, | ||
"addRecoveryKey", | ||
json!({"group": did, "key": k}), | ||
) | ||
.await; | ||
assert_eq!(said.0, 200, "{}", said.1); | ||
} | ||
// Earlier keys keep their rank; the host's is last. | ||
assert_eq!( | ||
rotation_keys(&h, &did).await, | ||
[first.clone(), second.clone(), host_key.clone()] | ||
); | ||
let (status, listed) = list(&h, &alice, &did).await; | ||
assert_eq!(status, 200, "{listed}"); | ||
assert_eq!(listed["hostHolds"], true); | ||
assert_eq!(listed["max"], 4); | ||
let keys = listed["keys"].as_array().unwrap(); | ||
assert_eq!(keys[0]["key"], first.as_str()); | ||
assert_eq!(keys[0]["holder"], "steward"); | ||
assert_eq!(keys[0]["addedBy"], alice.did.as_str()); | ||
assert!(keys[0]["addedAt"].is_string()); | ||
assert_eq!(keys[2], json!({"key": host_key, "holder": "host"})); | ||
| ||
// Taken off again, the host's kept. | ||
let said = call( | ||
&h, | ||
&alice, | ||
"removeRecoveryKey", | ||
json!({"group": did, "key": first}), | ||
) | ||
.await; | ||
assert_eq!(said.0, 200, "{}", said.1); | ||
assert_eq!(rotation_keys(&h, &did).await, [second, host_key]); | ||
let (_, grants) = get( | ||
&h, | ||
&format!("{NS}.listGroupTokens"), | ||
&format!("group={did}"), | ||
&[auth(&h, &alice, &format!("{NS}.listGroupTokens"))], | ||
) | ||
.await; | ||
let actions: Vec<&str> = grants["activity"] | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.map(|a| a["action"].as_str().unwrap()) | ||
.collect(); | ||
assert_eq!( | ||
actions[..2], | ||
["removed a recovery key", "added a recovery key"] | ||
); | ||
} | ||
| ||
#[tokio::test] | ||
async fn refuses_a_key_it_should_not_add_or_take_off() { | ||
let h = start(&[], false).await; | ||
let (did, [alice, bob, _]) = group(&h).await; | ||
let host_key = h.host.secrets.rotation.public().did_key(); | ||
let keys: Vec<String> = (0..4).map(|_| key().1).collect(); | ||
for k in &keys { | ||
assert_eq!( | ||
call( | ||
&h, | ||
&alice, | ||
"addRecoveryKey", | ||
json!({"group": did, "key": k}) | ||
) | ||
.await | ||
.0, | ||
200 | ||
); | ||
} | ||
let add = async |who: &Authority, body: Json| call(&h, who, "addRecoveryKey", body).await; | ||
for (body, refused) in [ | ||
( | ||
json!({"group": did, "key": "not a key"}), | ||
(400, "InvalidKey"), | ||
), | ||
(json!({"group": did, "key": keys[0]}), (400, "AlreadyAdded")), | ||
( | ||
json!({"group": did, "key": host_key}), | ||
(400, "AlreadyAdded"), | ||
), | ||
(json!({"group": did, "key": key().1}), (400, "TooManyKeys")), | ||
(json!({"key": key().1}), (400, "InvalidRequest")), | ||
( | ||
json!({"group": "did:plc:nothing", "key": key().1}), | ||
(400, "GroupNotFound"), | ||
), | ||
] { | ||
assert_eq!(error(&add(&alice, body.clone()).await), refused, "{body}"); | ||
} | ||
assert_eq!( | ||
error(&add(&bob, json!({"group": did, "key": key().1})).await), | ||
(403, "Forbidden") | ||
); | ||
assert_eq!(list(&h, &bob, &did).await.0, 403); | ||
let remove = async |body: Json| call(&h, &alice, "removeRecoveryKey", body).await; | ||
assert_eq!( | ||
error(&remove(json!({"group": did, "key": host_key})).await), | ||
(400, "HostKey") | ||
); | ||
assert_eq!( | ||
error(&remove(json!({"group": did, "key": key().1})).await), | ||
(400, "UnknownKey") | ||
); | ||
} | ||
| ||
#[tokio::test] | ||
async fn changes_nothing_once_the_host_holds_no_key() { | ||
let h = start(&[], false).await; | ||
let (did, [alice, ..]) = group(&h).await; | ||
let (steward, theirs) = key(); | ||
assert_eq!( | ||
call( | ||
&h, | ||
&alice, | ||
"addRecoveryKey", | ||
json!({"group": did, "key": theirs}) | ||
) | ||
.await | ||
.0, | ||
200 | ||
); | ||
// The steward takes the identity, leaving the host out, as they may. | ||
let Signed::Update { op, .. } = h.host.plc.last_op(&did).await.unwrap() else { | ||
panic!() | ||
}; | ||
let last = h.host.plc.last_op(&did).await.unwrap(); | ||
let mut next = op.clone(); | ||
next.rotation_keys = vec![theirs.clone()]; | ||
h.host | ||
.plc | ||
.publish(&did, &next.sign(Some(last.cid()), &steward)) | ||
.await | ||
.unwrap(); | ||
| ||
let (_, listed) = list(&h, &alice, &did).await; | ||
assert_eq!(listed["hostHolds"], false); | ||
assert_eq!( | ||
listed["keys"], | ||
json!([{"key": theirs, "holder": "steward", "addedBy": alice.did, "addedAt": listed["keys"][0]["addedAt"]}]) | ||
); | ||
let said = call( | ||
&h, | ||
&alice, | ||
"addRecoveryKey", | ||
json!({"group": did, "key": key().1}), | ||
) | ||
.await; | ||
assert_eq!(error(&said), (400, "NotController")); | ||
let said = call( | ||
&h, | ||
&alice, | ||
"removeRecoveryKey", | ||
json!({"group": did, "key": theirs}), | ||
) | ||
.await; | ||
assert_eq!(error(&said), (400, "NotController")); | ||
} | ||
| ||
#[tokio::test] | ||
async fn says_so_of_an_ended_did() { | ||
let h = start(&[], false).await; | ||
let (did, [alice, ..]) = group(&h).await; | ||
let last = h.host.plc.last_op(&did).await.unwrap(); | ||
h.host | ||
.plc | ||
.publish(&did, &tombstone(last.cid(), &h.host.secrets.rotation)) | ||
.await | ||
.unwrap(); | ||
assert_eq!(error(&list(&h, &alice, &did).await), (400, "NotController")); | ||
} | ||
| ||
#[tokio::test] | ||
async fn leaves_a_deleted_groups_did_to_a_steward_who_holds_a_key() { | ||
let h = start(&[], false).await; | ||
let (did, [alice, ..]) = group(&h).await; | ||
let (_, theirs) = key(); | ||
assert_eq!( | ||
call( | ||
&h, | ||
&alice, | ||
"addRecoveryKey", | ||
json!({"group": did, "key": theirs}) | ||
) | ||
.await | ||
.0, | ||
200 | ||
); | ||
let (status, deleted) = call(&h, &alice, "deleteGroup", json!({"group": did})).await; | ||
assert_eq!(status, 200, "{deleted}"); | ||
assert_eq!(deleted["tombstoned"], false); | ||
// Still theirs to bring back elsewhere. | ||
assert!(rotation_keys(&h, &did).await.contains(&theirs)); | ||
} | ||
docs/design/README.md+2−2
| @@ -120,8 +120,8 @@ says otherwise. | ||
`apps/web/src/pages`. Each is used end to end in `harness/e2e`. | ||
8. **Moderation, recovery and moving.** Reports, labels, subjects and | ||
history, and the console's moderation page (`moderation.rs`; done, see | ||
[moderation](moderation.md)); then recovery keys; importing an | ||
account; migrating a group to another host and moving the host itself: | ||
[moderation](moderation.md)); recovery keys (`recovery.rs`; done, see | ||
[recovery](recovery.md)); then importing an account; migrating a group to another host and moving the host itself: | ||
`methods/{moderation,recovery,importAccount,migration}.ts`, | ||
`hostLabels.ts`, `scripts/move-host.ts`. | ||
9. **MCP and the command.** The MCP tools over what steps 4 to 8 brought, | ||
docs/design/recovery.mdnew+30−0
| @@ -0,0 +1,30 @@ | ||
# Recovery | ||
| ||
A group's identity is its `did:plc`, and whoever holds a rotation key its | ||
PLC document names may change it. Left alone, the only one is this host's: | ||
the host alone could move the group, and nobody could move it without | ||
the host. Recovery keys change that (`recovery.rs`). | ||
| ||
A recovery key is a steward's own rotation key, which the host never | ||
sees, put ahead of the host's in the document. PLC lets a key ranked | ||
higher undo, for 72 hours, an operation one ranked lower signed: so | ||
whoever holds one can undo anything this host does to the group's | ||
identity, and take the group to another host without it. | ||
| ||
- `addRecoveryKey` (for `group.configure`) puts a `did:key` (secp256k1 or | ||
P-256) after any earlier recovery keys, which keep their rank, and | ||
ahead of the host's, which stays last. PLC takes five rotation keys, so | ||
a group has four recovery keys at most. | ||
- `removeRecoveryKey` takes one off; the host's own is not one. | ||
- `listRecoveryKeys` lists them, the highest ranked first, with who added | ||
each where the host added it, and whether the host still holds a key. | ||
| ||
The keys are the directory's to say: the host remembers only who added | ||
which, to show. Once the host holds no key (a steward took the identity | ||
elsewhere), it changes nothing. | ||
| ||
Deleting a group ends its DID in the directory only if nobody but the | ||
host could ever use it again. With a recovery key on it, the DID is its | ||
steward's, to bring the group back elsewhere, and is left alone. | ||
| ||
The console's settings page shows them, to add and take off. | ||
harness/e2e/flows.spec.mjs+15−1
| @@ -3,7 +3,7 @@ | ||
// and what the app then does as the group, read back from the host. | ||
| ||
import { expect, test } from '@playwright/test' | ||
import { App, signIn, signedInAs, url, who, world } from './pages.mjs' | ||
import { App, didKey, signIn, signedInAs, url, who, world } from './pages.mjs' | ||
| ||
test.describe.configure({ mode: 'serial' }) | ||
| ||
| @@ -157,6 +157,20 @@ test('making an app password, and ending what it signed in', async () => { | ||
expect((await signIn()).status).toBe(401) | ||
}) | ||
| ||
test('adding a recovery key, and taking it off', async () => { | ||
const key = didKey() | ||
await page.goto(url('/g/hikers.groups.test/settings')) | ||
await expect(page.locator('.recovery-keys li')).toHaveCount(1) | ||
await page.getByRole('textbox', { name: 'A key of yours, as a did:key' }).fill(key) | ||
await page.getByRole('button', { name: 'Add the recovery key' }).click() | ||
const keys = page.locator('.recovery-keys li') | ||
await expect(keys).toHaveCount(2) | ||
await expect(keys.first()).toContainText(key) | ||
await expect(keys.last()).toContainText('this host') | ||
await keys.first().getByRole('button', { name: 'Take off' }).click() | ||
await expect(page.locator('.recovery-keys li')).toHaveCount(1) | ||
}) | ||
| ||
test('moderating: a label, and the queue', async () => { | ||
await page.goto(url('/g/hikers.groups.test')) | ||
await page.getByRole('link', { name: 'Moderation' }).click() | ||
harness/e2e/pages.mjs+16−0
| @@ -143,3 +143,19 @@ export class App { | ||
return this.send(`${world.host}/xrpc/${nsid}`, init, token) | ||
} | ||
} | ||
| ||
/// A new P-256 key, as a did:key: what a steward holds as a recovery key. | ||
export const didKey = () => { | ||
const { publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' }) | ||
const point = publicKey.export({ format: 'der', type: 'spki' }).subarray(-65) | ||
const compressed = Buffer.concat([Buffer.from([point[64] & 1 ? 3 : 2]), point.subarray(1, 33)]) | ||
const bytes = Buffer.concat([Buffer.from([0x80, 0x24]), compressed]) | ||
const alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' | ||
let n = BigInt(`0x${bytes.toString('hex')}`) | ||
let out = '' | ||
while (n > 0n) { | ||
out = alphabet[Number(n % 58n)] + out | ||
n /= 58n | ||
} | ||
return `did:key:z${out}` | ||
} | ||
web/src/lib/organisms/RecoveryKeys.sveltenew+32−0
| @@ -0,0 +1,32 @@ | ||
<script lang="ts"> | ||
/** | ||
* The group's rotation keys, the highest ranked first: the stewards' | ||
* recovery keys, each to take off, and this host's; and a key to add. | ||
* A recovery key's holder can undo what this host does to the group's | ||
* identity, and take the group elsewhere without it. | ||
*/ | ||
type Key = { key: string; holder: string; addedBy?: string }; | ||
let { keys, hostHolds, max }: { keys: Key[]; hostHolds: boolean; max: number } = $props(); | ||
const stewards = $derived(keys.filter((k) => k.holder === 'steward')); | ||
</script> | ||
| ||
<div class="stack"> | ||
<ol class="recovery-keys"> | ||
{#each keys as k (k.key)} | ||
<li> | ||
<code>{k.key}</code> <span class="mute">{k.holder === 'host' ? 'this host' : `a steward's${k.addedBy ? `, added by ${k.addedBy}` : ''}`}</span> | ||
{#if k.holder === 'steward' && hostHolds} | ||
<form method="post" action="?/unkey"><input type="hidden" name="key" value={k.key} /><button type="submit">Take off</button></form> | ||
{/if} | ||
</li> | ||
{/each} | ||
</ol> | ||
{#if !hostHolds} | ||
<p class="mute">This host no longer holds a key to the group's identity, so it cannot change them.</p> | ||
{:else if stewards.length < max} | ||
<form class="stack" method="post" action="?/key"> | ||
<label class="field">A key of yours, as a did:key <input name="key" required placeholder="did:key:z…" /></label> | ||
<button type="submit">Add the recovery key</button> | ||
</form> | ||
{/if} | ||
</div> | ||